mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-05 09:25:14 +03:00
style: address Sphinx double-backtick snippet syntax (#33389)
This commit is contained in:
1 parent
f405a2c57d
commit
d8a680ee57
145 files changed
+1306
-1307
No files matched your search
@@ -149,7 +149,7 @@ def send_email(to: str, msg: str, *, priority: str = "normal") -> bool:
|
||||
Args:
|
||||
to: The email address of the recipient.
|
||||
msg: The message body to send.
|
||||
priority: Email priority level (`'low'`, ``'normal'``, `'high'`).
|
||||
priority: Email priority level (`'low'`, `'normal'`, `'high'`).
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully, False otherwise.
|
||||
|
||||
@@ -149,7 +149,7 @@ def send_email(to: str, msg: str, *, priority: str = "normal") -> bool:
|
||||
Args:
|
||||
to: The email address of the recipient.
|
||||
msg: The message body to send.
|
||||
priority: Email priority level (`'low'`, ``'normal'``, `'high'`).
|
||||
priority: Email priority level (`'low'`, `'normal'`, `'high'`).
|
||||
|
||||
Returns:
|
||||
True if email was sent successfully, False otherwise.
|
||||
|
||||
@@ -26,8 +26,8 @@ class Chat__ModuleName__(BaseChatModel):
|
||||
|
||||
# TODO: Replace with relevant packages, env vars.
|
||||
Setup:
|
||||
Install ``__package_name__`` and set environment variable
|
||||
``__MODULE_NAME___API_KEY``.
|
||||
Install `__package_name__` and set environment variable
|
||||
`__MODULE_NAME___API_KEY`.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
@@ -145,9 +145,9 @@ class Chat__ModuleName__(BaseChatModel):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# TODO: Example output.
|
||||
# TODO: Example output.
|
||||
|
||||
See ``Chat__ModuleName__.bind_tools()`` method for more.
|
||||
See `Chat__ModuleName__.bind_tools()` method for more.
|
||||
|
||||
# TODO: Delete if .with_structured_output() isn't supported.
|
||||
Structured output:
|
||||
@@ -171,7 +171,7 @@ class Chat__ModuleName__(BaseChatModel):
|
||||
|
||||
# TODO: Example output.
|
||||
|
||||
See ``Chat__ModuleName__.with_structured_output()`` for more.
|
||||
See `Chat__ModuleName__.with_structured_output()` for more.
|
||||
|
||||
# TODO: Delete if JSON mode response format isn't supported.
|
||||
JSON mode:
|
||||
@@ -255,7 +255,7 @@ class Chat__ModuleName__(BaseChatModel):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# TODO: Example output.
|
||||
# TODO: Example output.
|
||||
|
||||
Response metadata
|
||||
.. code-block:: python
|
||||
@@ -265,7 +265,7 @@ class Chat__ModuleName__(BaseChatModel):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# TODO: Example output.
|
||||
# TODO: Example output.
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
@@ -314,11 +314,11 @@ class Chat__ModuleName__(BaseChatModel):
|
||||
Args:
|
||||
messages: the prompt composed of a list of messages.
|
||||
stop: a list of strings on which the model should stop generating.
|
||||
If generation stops due to a stop token, the stop token itself
|
||||
SHOULD BE INCLUDED as part of the output. This is not enforced
|
||||
across models right now, but it's a good practice to follow since
|
||||
it makes it much easier to parse the output of the model
|
||||
downstream and understand why generation stopped.
|
||||
If generation stops due to a stop token, the stop token itself
|
||||
SHOULD BE INCLUDED as part of the output. This is not enforced
|
||||
across models right now, but it's a good practice to follow since
|
||||
it makes it much easier to parse the output of the model
|
||||
downstream and understand why generation stopped.
|
||||
run_manager: A run manager with callbacks for the LLM.
|
||||
"""
|
||||
# Replace this with actual logic to generate a response from a list
|
||||
@@ -362,11 +362,11 @@ class Chat__ModuleName__(BaseChatModel):
|
||||
Args:
|
||||
messages: the prompt composed of a list of messages.
|
||||
stop: a list of strings on which the model should stop generating.
|
||||
If generation stops due to a stop token, the stop token itself
|
||||
SHOULD BE INCLUDED as part of the output. This is not enforced
|
||||
across models right now, but it's a good practice to follow since
|
||||
it makes it much easier to parse the output of the model
|
||||
downstream and understand why generation stopped.
|
||||
If generation stops due to a stop token, the stop token itself
|
||||
SHOULD BE INCLUDED as part of the output. This is not enforced
|
||||
across models right now, but it's a good practice to follow since
|
||||
it makes it much easier to parse the output of the model
|
||||
downstream and understand why generation stopped.
|
||||
run_manager: A run manager with callbacks for the LLM.
|
||||
"""
|
||||
last_message = messages[-1]
|
||||
|
||||
+2
-2
@@ -14,8 +14,8 @@ class __ModuleName__Loader(BaseLoader):
|
||||
|
||||
# TODO: Replace with relevant packages, env vars.
|
||||
Setup:
|
||||
Install ``__package_name__`` and set environment variable
|
||||
``__MODULE_NAME___API_KEY``.
|
||||
Install `__package_name__` and set environment variable
|
||||
`__MODULE_NAME___API_KEY`.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
|
||||
@@ -8,8 +8,8 @@ class __ModuleName__Embeddings(Embeddings):
|
||||
|
||||
# TODO: Replace with relevant packages, env vars.
|
||||
Setup:
|
||||
Install ``__package_name__`` and set environment variable
|
||||
``__MODULE_NAME___API_KEY``.
|
||||
Install `__package_name__` and set environment variable
|
||||
`__MODULE_NAME___API_KEY`.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
@@ -49,7 +49,7 @@ class __ModuleName__Embeddings(Embeddings):
|
||||
Embed multiple text:
|
||||
.. code-block:: python
|
||||
|
||||
input_texts = ["Document 1...", "Document 2..."]
|
||||
input_texts = ["Document 1...", "Document 2..."]
|
||||
embed.embed_documents(input_texts)
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -14,8 +14,8 @@ class __ModuleName__Retriever(BaseRetriever):
|
||||
|
||||
# TODO: Replace with relevant packages, env vars, etc.
|
||||
Setup:
|
||||
Install ``__package_name__`` and set environment variable
|
||||
``__MODULE_NAME___API_KEY``.
|
||||
Install `__package_name__` and set environment variable
|
||||
`__MODULE_NAME___API_KEY`.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ class __ModuleName__Toolkit(BaseToolkit):
|
||||
|
||||
# TODO: Replace with relevant packages, env vars, etc.
|
||||
Setup:
|
||||
Install ``__package_name__`` and set environment variable
|
||||
``__MODULE_NAME___API_KEY``.
|
||||
Install `__package_name__` and set environment variable
|
||||
`__MODULE_NAME___API_KEY`.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
|
||||
@@ -27,8 +27,8 @@ class __ModuleName__Tool(BaseTool): # type: ignore[override]
|
||||
|
||||
Setup:
|
||||
# TODO: Replace with relevant packages, env vars.
|
||||
Install ``__package_name__`` and set environment variable
|
||||
``__MODULE_NAME___API_KEY``.
|
||||
Install `__package_name__` and set environment variable
|
||||
`__MODULE_NAME___API_KEY`.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ class __ModuleName__VectorStore(VectorStore):
|
||||
|
||||
# TODO: Replace with relevant packages, env vars.
|
||||
Setup:
|
||||
Install ``__package_name__`` and set environment variable ``__MODULE_NAME___API_KEY``.
|
||||
Install `__package_name__` and set environment variable `__MODULE_NAME___API_KEY`.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ class AgentAction(Serializable):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "agent"]``
|
||||
`["langchain", "schema", "agent"]`
|
||||
"""
|
||||
return ["langchain", "schema", "agent"]
|
||||
|
||||
@@ -163,7 +163,7 @@ class AgentFinish(Serializable):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "agent"]``
|
||||
`["langchain", "schema", "agent"]`
|
||||
"""
|
||||
return ["langchain", "schema", "agent"]
|
||||
|
||||
|
||||
@@ -247,7 +247,7 @@ class CallbackManagerMixin:
|
||||
!!! warning
|
||||
This method is called for non-chat models (regular LLMs). If you're
|
||||
implementing a handler for a chat model, you should use
|
||||
``on_chat_model_start`` instead.
|
||||
`on_chat_model_start` instead.
|
||||
|
||||
Args:
|
||||
serialized: The serialized LLM.
|
||||
@@ -274,7 +274,7 @@ class CallbackManagerMixin:
|
||||
|
||||
!!! warning
|
||||
This method is called for chat models. If you're implementing a handler for
|
||||
a non-chat model, you should use ``on_llm_start`` instead.
|
||||
a non-chat model, you should use `on_llm_start` instead.
|
||||
|
||||
Args:
|
||||
serialized: The serialized chat model.
|
||||
@@ -414,7 +414,7 @@ class RunManagerMixin:
|
||||
Args:
|
||||
name: The name of the custom event.
|
||||
data: The data for the custom event. Format will match
|
||||
the format specified by the user.
|
||||
the format specified by the user.
|
||||
run_id: The ID of the run.
|
||||
tags: The tags associated with the custom event
|
||||
(includes inherited tags).
|
||||
@@ -496,7 +496,7 @@ class AsyncCallbackHandler(BaseCallbackHandler):
|
||||
!!! warning
|
||||
This method is called for non-chat models (regular LLMs). If you're
|
||||
implementing a handler for a chat model, you should use
|
||||
``on_chat_model_start`` instead.
|
||||
`on_chat_model_start` instead.
|
||||
|
||||
Args:
|
||||
serialized: The serialized LLM.
|
||||
@@ -523,7 +523,7 @@ class AsyncCallbackHandler(BaseCallbackHandler):
|
||||
|
||||
!!! warning
|
||||
This method is called for chat models. If you're implementing a handler for
|
||||
a non-chat model, you should use ``on_llm_start`` instead.
|
||||
a non-chat model, you should use `on_llm_start` instead.
|
||||
|
||||
Args:
|
||||
serialized: The serialized chat model.
|
||||
@@ -876,7 +876,7 @@ class AsyncCallbackHandler(BaseCallbackHandler):
|
||||
Args:
|
||||
name: The name of the custom event.
|
||||
data: The data for the custom event. Format will match
|
||||
the format specified by the user.
|
||||
the format specified by the user.
|
||||
run_id: The ID of the run.
|
||||
tags: The tags associated with the custom event
|
||||
(includes inherited tags).
|
||||
|
||||
@@ -96,11 +96,10 @@ def get_usage_metadata_callback(
|
||||
"""Get usage metadata callback.
|
||||
|
||||
Get context manager for tracking usage metadata across chat model calls using
|
||||
``AIMessage.usage_metadata``.
|
||||
`AIMessage.usage_metadata`.
|
||||
|
||||
Args:
|
||||
name: The name of the context variable. Defaults to
|
||||
``'usage_metadata_callback'``.
|
||||
name: The name of the context variable.
|
||||
|
||||
Yields:
|
||||
The usage metadata callback.
|
||||
|
||||
@@ -130,7 +130,7 @@ class BaseChatMessageHistory(ABC):
|
||||
"""Convenience method for adding a human message string to the store.
|
||||
|
||||
!!! note
|
||||
This is a convenience method. Code should favor the bulk ``add_messages``
|
||||
This is a convenience method. Code should favor the bulk `add_messages`
|
||||
interface instead to save on round-trips to the persistence layer.
|
||||
|
||||
This method may be deprecated in a future release.
|
||||
@@ -147,7 +147,7 @@ class BaseChatMessageHistory(ABC):
|
||||
"""Convenience method for adding an AI message string to the store.
|
||||
|
||||
!!! note
|
||||
This is a convenience method. Code should favor the bulk ``add_messages``
|
||||
This is a convenience method. Code should favor the bulk `add_messages`
|
||||
interface instead to save on round-trips to the persistence layer.
|
||||
|
||||
This method may be deprecated in a future release.
|
||||
|
||||
@@ -44,8 +44,8 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818
|
||||
Defaults to `False`.
|
||||
|
||||
Raises:
|
||||
ValueError: If ``send_to_llm`` is True but either observation or
|
||||
``llm_output`` are not provided.
|
||||
ValueError: If `send_to_llm` is True but either observation or
|
||||
`llm_output` are not provided.
|
||||
"""
|
||||
if isinstance(error, str):
|
||||
error = create_message(
|
||||
|
||||
@@ -108,7 +108,7 @@ def _generate_response_from_error(error: BaseException) -> list[ChatGeneration]:
|
||||
|
||||
|
||||
def _format_for_tracing(messages: list[BaseMessage]) -> list[BaseMessage]:
|
||||
"""Format messages for tracing in ``on_chat_model_start``.
|
||||
"""Format messages for tracing in `on_chat_model_start`.
|
||||
|
||||
- Update image content blocks to OpenAI Chat Completions format (backward
|
||||
compatibility).
|
||||
@@ -342,7 +342,7 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
|
||||
)
|
||||
"""Version of `AIMessage` output format to store in message content.
|
||||
|
||||
`AIMessage.content_blocks` will lazily parse the contents of ``content`` into a
|
||||
`AIMessage.content_blocks` will lazily parse the contents of `content` into a
|
||||
standard format. This flag can be used to additionally store the standard format
|
||||
in message content, e.g., for serialization purposes.
|
||||
|
||||
@@ -1533,7 +1533,7 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
|
||||
- a `TypedDict` class,
|
||||
- or a Pydantic class.
|
||||
|
||||
If ``schema`` is a Pydantic class then the model output will be a
|
||||
If `schema` is a Pydantic class then the model output will be a
|
||||
Pydantic instance of that class, and the model-generated fields will be
|
||||
validated by the Pydantic class. Otherwise the model output will be a
|
||||
dict and will not be validated. See `langchain_core.utils.function_calling.convert_to_openai_tool`
|
||||
@@ -1546,26 +1546,26 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
|
||||
then both the raw model response (a BaseMessage) and the parsed model
|
||||
response will be returned. If an error occurs during output parsing it
|
||||
will be caught and returned as well. The final output is always a dict
|
||||
with keys ``'raw'``, ``'parsed'``, and ``'parsing_error'``.
|
||||
with keys `'raw'`, `'parsed'`, and `'parsing_error'`.
|
||||
|
||||
Raises:
|
||||
ValueError: If there are any unsupported ``kwargs``.
|
||||
ValueError: If there are any unsupported `kwargs`.
|
||||
NotImplementedError: If the model does not implement
|
||||
``with_structured_output()``.
|
||||
`with_structured_output()`.
|
||||
|
||||
Returns:
|
||||
A Runnable that takes same inputs as a `langchain_core.language_models.chat.BaseChatModel`.
|
||||
|
||||
If ``include_raw`` is False and ``schema`` is a Pydantic class, Runnable outputs
|
||||
an instance of ``schema`` (i.e., a Pydantic object).
|
||||
If `include_raw` is False and `schema` is a Pydantic class, Runnable outputs
|
||||
an instance of `schema` (i.e., a Pydantic object).
|
||||
|
||||
Otherwise, if ``include_raw`` is False then Runnable outputs a dict.
|
||||
Otherwise, if `include_raw` is False then Runnable outputs a dict.
|
||||
|
||||
If ``include_raw`` is True, then Runnable outputs a dict with keys:
|
||||
If `include_raw` is True, then Runnable outputs a dict with keys:
|
||||
|
||||
- ``'raw'``: BaseMessage
|
||||
- ``'parsed'``: None if there was a parsing error, otherwise the type depends on the ``schema`` as described above.
|
||||
- ``'parsing_error'``: BaseException | None
|
||||
- `'raw'`: BaseMessage
|
||||
- `'parsed'`: None if there was a parsing error, otherwise the type depends on the `schema` as described above.
|
||||
- `'parsing_error'`: BaseException | None
|
||||
|
||||
Example: Pydantic schema (include_raw=False):
|
||||
.. code-block:: python
|
||||
@@ -1693,7 +1693,7 @@ class SimpleChatModel(BaseChatModel):
|
||||
|
||||
!!! note
|
||||
This implementation is primarily here for backwards compatibility. For new
|
||||
implementations, please use ``BaseChatModel`` directly.
|
||||
implementations, please use `BaseChatModel` directly.
|
||||
|
||||
"""
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ from langchain_core.runnables import RunnableConfig
|
||||
|
||||
|
||||
class FakeMessagesListChatModel(BaseChatModel):
|
||||
"""Fake ``ChatModel`` for testing purposes."""
|
||||
"""Fake `ChatModel` for testing purposes."""
|
||||
|
||||
responses: list[BaseMessage]
|
||||
"""List of responses to **cycle** through in order."""
|
||||
@@ -228,10 +228,10 @@ class GenericFakeChatModel(BaseChatModel):
|
||||
"""Generic fake chat model that can be used to test the chat model interface.
|
||||
|
||||
* Chat model should be usable in both sync and async tests
|
||||
* Invokes ``on_llm_new_token`` to allow for testing of callback related code for new
|
||||
tokens.
|
||||
* Invokes `on_llm_new_token` to allow for testing of callback related code for new
|
||||
tokens.
|
||||
* Includes logic to break messages into message chunk to facilitate testing of
|
||||
streaming.
|
||||
streaming.
|
||||
|
||||
"""
|
||||
|
||||
@@ -242,7 +242,7 @@ class GenericFakeChatModel(BaseChatModel):
|
||||
to make the interface more generic if needed.
|
||||
|
||||
!!! note
|
||||
if you want to pass a list, you can use ``iter`` to convert it to an iterator.
|
||||
if you want to pass a list, you can use `iter` to convert it to an iterator.
|
||||
|
||||
!!! warning
|
||||
Streaming is not implemented yet. We should try to implement it in the future by
|
||||
|
||||
@@ -835,7 +835,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
|
||||
1. Take advantage of batched calls,
|
||||
2. Need more output from the model than just the top generated value,
|
||||
3. Are building chains that are agnostic to the underlying language model
|
||||
type (e.g., pure text completion models vs chat models).
|
||||
type (e.g., pure text completion models vs chat models).
|
||||
|
||||
Args:
|
||||
prompts: List of string prompts.
|
||||
@@ -857,8 +857,8 @@ class BaseLLM(BaseLanguageModel[str], ABC):
|
||||
|
||||
Raises:
|
||||
ValueError: If prompts is not a list.
|
||||
ValueError: If the length of ``callbacks``, ``tags``, ``metadata``, or
|
||||
``run_name`` (if provided) does not match the length of prompts.
|
||||
ValueError: If the length of `callbacks`, `tags`, `metadata`, or
|
||||
`run_name` (if provided) does not match the length of prompts.
|
||||
|
||||
Returns:
|
||||
An LLMResult, which contains a list of candidate Generations for each input
|
||||
@@ -1105,7 +1105,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
|
||||
1. Take advantage of batched calls,
|
||||
2. Need more output from the model than just the top generated value,
|
||||
3. Are building chains that are agnostic to the underlying language model
|
||||
type (e.g., pure text completion models vs chat models).
|
||||
type (e.g., pure text completion models vs chat models).
|
||||
|
||||
Args:
|
||||
prompts: List of string prompts.
|
||||
@@ -1126,8 +1126,8 @@ class BaseLLM(BaseLanguageModel[str], ABC):
|
||||
to the model provider API call.
|
||||
|
||||
Raises:
|
||||
ValueError: If the length of ``callbacks``, ``tags``, ``metadata``, or
|
||||
``run_name`` (if provided) does not match the length of prompts.
|
||||
ValueError: If the length of `callbacks`, `tags`, `metadata`, or
|
||||
`run_name` (if provided) does not match the length of prompts.
|
||||
|
||||
Returns:
|
||||
An LLMResult, which contains a list of candidate Generations for each input
|
||||
|
||||
@@ -107,7 +107,7 @@ class Reviver:
|
||||
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
|
||||
``ignore_unserializable_fields`` is False.
|
||||
`ignore_unserializable_fields` is False.
|
||||
"""
|
||||
if (
|
||||
value.get("lc") == 1
|
||||
|
||||
@@ -34,7 +34,7 @@ class SerializedConstructor(BaseSerialized):
|
||||
"""Serialized constructor."""
|
||||
|
||||
type: Literal["constructor"]
|
||||
"""The type of the object. Must be ``'constructor'``."""
|
||||
"""The type of the object. Must be `'constructor'`."""
|
||||
kwargs: dict[str, Any]
|
||||
"""The constructor arguments."""
|
||||
|
||||
@@ -43,14 +43,14 @@ class SerializedSecret(BaseSerialized):
|
||||
"""Serialized secret."""
|
||||
|
||||
type: Literal["secret"]
|
||||
"""The type of the object. Must be ``'secret'``."""
|
||||
"""The type of the object. Must be `'secret'`."""
|
||||
|
||||
|
||||
class SerializedNotImplemented(BaseSerialized):
|
||||
"""Serialized not implemented."""
|
||||
|
||||
type: Literal["not_implemented"]
|
||||
"""The type of the object. Must be ``'not_implemented'``."""
|
||||
"""The type of the object. Must be `'not_implemented'`."""
|
||||
repr: str | None
|
||||
"""The representation of the object. Optional."""
|
||||
|
||||
@@ -93,17 +93,17 @@ class Serializable(BaseModel, ABC):
|
||||
It relies on the following methods and properties:
|
||||
|
||||
- `is_lc_serializable`: Is this class serializable?
|
||||
By design, even if a class inherits from Serializable, it is not serializable by
|
||||
default. This is to prevent accidental serialization of objects that should not
|
||||
be serialized.
|
||||
- ``get_lc_namespace``: Get the namespace of the langchain object.
|
||||
During deserialization, this namespace is used to identify
|
||||
the correct class to instantiate.
|
||||
Please see the ``Reviver`` class in ``langchain_core.load.load`` for more details.
|
||||
During deserialization an additional mapping is handle
|
||||
classes that have moved or been renamed across package versions.
|
||||
- ``lc_secrets``: A map of constructor argument names to secret ids.
|
||||
- ``lc_attributes``: List of additional attribute names that should be included
|
||||
By design, even if a class inherits from Serializable, it is not serializable by
|
||||
default. This is to prevent accidental serialization of objects that should not
|
||||
be serialized.
|
||||
- `get_lc_namespace`: Get the namespace of the langchain object.
|
||||
During deserialization, this namespace is used to identify
|
||||
the correct class to instantiate.
|
||||
Please see the `Reviver` class in `langchain_core.load.load` for more details.
|
||||
During deserialization an additional mapping is handle
|
||||
classes that have moved or been renamed across package versions.
|
||||
- `lc_secrets`: A map of constructor argument names to secret ids.
|
||||
- `lc_attributes`: List of additional attribute names that should be included
|
||||
as part of the serialized representation.
|
||||
"""
|
||||
|
||||
|
||||
@@ -193,7 +193,7 @@ class AIMessage(BaseMessage):
|
||||
) -> None:
|
||||
"""Initialize `AIMessage`.
|
||||
|
||||
Specify ``content`` as positional arg or ``content_blocks`` for typing.
|
||||
Specify `content` as positional arg or `content_blocks` for typing.
|
||||
|
||||
Args:
|
||||
content: The content of the message.
|
||||
@@ -335,7 +335,7 @@ class AIMessage(BaseMessage):
|
||||
|
||||
Args:
|
||||
html: Whether to return an HTML-formatted string.
|
||||
Defaults to `False`.
|
||||
Defaults to `False`.
|
||||
|
||||
Returns:
|
||||
A pretty representation of the message.
|
||||
@@ -380,7 +380,7 @@ class AIMessageChunk(AIMessage, BaseMessageChunk):
|
||||
type: Literal["AIMessageChunk"] = "AIMessageChunk" # type: ignore[assignment]
|
||||
"""The type of the message (used for deserialization).
|
||||
|
||||
Defaults to ``AIMessageChunk``.
|
||||
Defaults to `AIMessageChunk`.
|
||||
|
||||
"""
|
||||
|
||||
@@ -390,8 +390,8 @@ class AIMessageChunk(AIMessage, BaseMessageChunk):
|
||||
chunk_position: Literal["last"] | None = None
|
||||
"""Optional span represented by an aggregated AIMessageChunk.
|
||||
|
||||
If a chunk with ``chunk_position="last"`` is aggregated into a stream,
|
||||
``tool_call_chunks`` in message content will be parsed into `tool_calls`.
|
||||
If a chunk with `chunk_position="last"` is aggregated into a stream,
|
||||
`tool_call_chunks` in message content will be parsed into `tool_calls`.
|
||||
"""
|
||||
|
||||
@property
|
||||
@@ -596,14 +596,14 @@ class AIMessageChunk(AIMessage, BaseMessageChunk):
|
||||
def add_ai_message_chunks(
|
||||
left: AIMessageChunk, *others: AIMessageChunk
|
||||
) -> AIMessageChunk:
|
||||
"""Add multiple ``AIMessageChunk``s together.
|
||||
"""Add multiple `AIMessageChunk`s together.
|
||||
|
||||
Args:
|
||||
left: The first ``AIMessageChunk``.
|
||||
*others: Other ``AIMessageChunk``s to add.
|
||||
left: The first `AIMessageChunk`.
|
||||
*others: Other `AIMessageChunk`s to add.
|
||||
|
||||
Returns:
|
||||
The resulting ``AIMessageChunk``.
|
||||
The resulting `AIMessageChunk`.
|
||||
|
||||
"""
|
||||
content = merge_content(left.content, *(o.content for o in others))
|
||||
@@ -713,11 +713,11 @@ def add_usage(left: UsageMetadata | None, right: UsageMetadata | None) -> UsageM
|
||||
)
|
||||
|
||||
Args:
|
||||
left: The first ``UsageMetadata`` object.
|
||||
right: The second ``UsageMetadata`` object.
|
||||
left: The first `UsageMetadata` object.
|
||||
right: The second `UsageMetadata` object.
|
||||
|
||||
Returns:
|
||||
The sum of the two ``UsageMetadata`` objects.
|
||||
The sum of the two `UsageMetadata` objects.
|
||||
|
||||
"""
|
||||
if not (left or right):
|
||||
@@ -740,9 +740,9 @@ def add_usage(left: UsageMetadata | None, right: UsageMetadata | None) -> UsageM
|
||||
def subtract_usage(
|
||||
left: UsageMetadata | None, right: UsageMetadata | None
|
||||
) -> UsageMetadata:
|
||||
"""Recursively subtract two ``UsageMetadata`` objects.
|
||||
"""Recursively subtract two `UsageMetadata` objects.
|
||||
|
||||
Token counts cannot be negative so the actual operation is ``max(left - right, 0)``.
|
||||
Token counts cannot be negative so the actual operation is `max(left - right, 0)`.
|
||||
|
||||
Example:
|
||||
.. code-block:: python
|
||||
@@ -777,11 +777,11 @@ def subtract_usage(
|
||||
)
|
||||
|
||||
Args:
|
||||
left: The first ``UsageMetadata`` object.
|
||||
right: The second ``UsageMetadata`` object.
|
||||
left: The first `UsageMetadata` object.
|
||||
right: The second `UsageMetadata` object.
|
||||
|
||||
Returns:
|
||||
The resulting ``UsageMetadata`` after subtraction.
|
||||
The resulting `UsageMetadata` after subtraction.
|
||||
|
||||
"""
|
||||
if not (left or right):
|
||||
|
||||
@@ -48,13 +48,13 @@ class TextAccessor(str):
|
||||
|
||||
Exists to maintain backward compatibility while transitioning from method-based to
|
||||
property-based text access in message objects. In LangChain <v1.0, message text was
|
||||
accessed via ``.text()`` method calls. In v1.0=<, the preferred pattern is property
|
||||
access via ``.text``.
|
||||
accessed via `.text()` method calls. In v1.0=<, the preferred pattern is property
|
||||
access via `.text`.
|
||||
|
||||
Rather than breaking existing code immediately, ``TextAccessor`` allows both
|
||||
Rather than breaking existing code immediately, `TextAccessor` allows both
|
||||
patterns:
|
||||
- Modern property access: ``message.text`` (returns string directly)
|
||||
- Legacy method access: ``message.text()`` (callable, emits deprecation warning)
|
||||
- Modern property access: `message.text` (returns string directly)
|
||||
- Legacy method access: `message.text()` (callable, emits deprecation warning)
|
||||
|
||||
"""
|
||||
|
||||
@@ -67,12 +67,12 @@ class TextAccessor(str):
|
||||
def __call__(self) -> str:
|
||||
"""Enable method-style text access for backward compatibility.
|
||||
|
||||
This method exists solely to support legacy code that calls ``.text()``
|
||||
as a method. New code should use property access (``.text``) instead.
|
||||
This method exists solely to support legacy code that calls `.text()`
|
||||
as a method. New code should use property access (`.text`) instead.
|
||||
|
||||
!!! 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.
|
||||
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:
|
||||
The string content, identical to property access.
|
||||
@@ -92,7 +92,7 @@ class TextAccessor(str):
|
||||
class BaseMessage(Serializable):
|
||||
"""Base abstract message class.
|
||||
|
||||
Messages are the inputs and outputs of a ``ChatModel``.
|
||||
Messages are the inputs and outputs of a `ChatModel`.
|
||||
"""
|
||||
|
||||
content: str | list[str | dict]
|
||||
@@ -161,7 +161,7 @@ class BaseMessage(Serializable):
|
||||
) -> None:
|
||||
"""Initialize `BaseMessage`.
|
||||
|
||||
Specify ``content`` as positional arg or ``content_blocks`` for typing.
|
||||
Specify `content` as positional arg or `content_blocks` for typing.
|
||||
|
||||
Args:
|
||||
content: The string contents of the message.
|
||||
@@ -187,7 +187,7 @@ class BaseMessage(Serializable):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "messages"]``
|
||||
`["langchain", "schema", "messages"]`
|
||||
"""
|
||||
return ["langchain", "schema", "messages"]
|
||||
|
||||
@@ -259,11 +259,11 @@ class BaseMessage(Serializable):
|
||||
def text(self) -> TextAccessor:
|
||||
"""Get the text content of the message as a string.
|
||||
|
||||
Can be used as both property (``message.text``) and method (``message.text()``).
|
||||
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.
|
||||
Use ``.text`` as a property instead. This method will be removed in 2.0.0.
|
||||
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:
|
||||
The text content of the message.
|
||||
@@ -331,8 +331,8 @@ def merge_content(
|
||||
"""Merge multiple message contents.
|
||||
|
||||
Args:
|
||||
first_content: The first ``content``. Can be a string or a list.
|
||||
contents: The other ``content``s. Can be a string or a list.
|
||||
first_content: The first `content`. Can be a string or a list.
|
||||
contents: The other `content`s. Can be a string or a list.
|
||||
|
||||
Returns:
|
||||
The merged content.
|
||||
@@ -388,9 +388,9 @@ class BaseMessageChunk(BaseMessage):
|
||||
|
||||
For example,
|
||||
|
||||
``AIMessageChunk(content="Hello") + AIMessageChunk(content=" World")``
|
||||
`AIMessageChunk(content="Hello") + AIMessageChunk(content=" World")`
|
||||
|
||||
will give ``AIMessageChunk(content="Hello World")``
|
||||
will give `AIMessageChunk(content="Hello World")`
|
||||
|
||||
"""
|
||||
if isinstance(other, BaseMessageChunk):
|
||||
@@ -440,7 +440,7 @@ def message_to_dict(message: BaseMessage) -> dict:
|
||||
|
||||
Returns:
|
||||
Message as a dict. The dict will have a `type` key with the message type
|
||||
and a ``data`` key with the message data as a dict.
|
||||
and a `data` key with the message data as a dict.
|
||||
|
||||
"""
|
||||
return {"type": message.type, "data": message.model_dump()}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Derivations of standard content blocks from provider content.
|
||||
|
||||
`AIMessage` will first attempt to use a provider-specific translator if
|
||||
``model_provider`` is set in `response_metadata` on the message. Consequently, each
|
||||
`model_provider` is set in `response_metadata` on the message. Consequently, each
|
||||
provider translator must handle all possible content response types from the provider,
|
||||
including text.
|
||||
|
||||
@@ -23,13 +23,13 @@ if TYPE_CHECKING:
|
||||
PROVIDER_TRANSLATORS: dict[str, dict[str, Callable[..., list[types.ContentBlock]]]] = {}
|
||||
"""Map model provider names to translator functions.
|
||||
|
||||
The dictionary maps provider names (e.g. ``'openai'``, ``'anthropic'``) to another
|
||||
The dictionary maps provider names (e.g. `'openai'`, `'anthropic'`) to another
|
||||
dictionary with two keys:
|
||||
- ``'translate_content'``: Function to translate `AIMessage` content.
|
||||
- ``'translate_content_chunk'``: Function to translate ``AIMessageChunk`` content.
|
||||
- `'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
|
||||
``model_provider`` is set in `response_metadata`, the corresponding translator
|
||||
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.
|
||||
"""
|
||||
@@ -43,9 +43,9 @@ def register_translator(
|
||||
"""Register content translators for a provider in `PROVIDER_TRANSLATORS`.
|
||||
|
||||
Args:
|
||||
provider: The model provider name (e.g. ``'openai'``, ``'anthropic'``).
|
||||
provider: The model provider name (e.g. `'openai'`, `'anthropic'`).
|
||||
translate_content: Function to translate `AIMessage` content.
|
||||
translate_content_chunk: Function to translate ``AIMessageChunk`` content.
|
||||
translate_content_chunk: Function to translate `AIMessageChunk` content.
|
||||
"""
|
||||
PROVIDER_TRANSLATORS[provider] = {
|
||||
"translate_content": translate_content,
|
||||
@@ -62,7 +62,7 @@ def get_translator(
|
||||
provider: The model provider name.
|
||||
|
||||
Returns:
|
||||
Dictionary with ``'translate_content'`` and ``'translate_content_chunk'``
|
||||
Dictionary with `'translate_content'` and `'translate_content_chunk'`
|
||||
functions, or None if no translator is registered for the provider. In such
|
||||
case, best-effort parsing in `BaseMessage` will be used.
|
||||
"""
|
||||
@@ -72,10 +72,10 @@ def get_translator(
|
||||
def _register_translators() -> None:
|
||||
"""Register all translators in langchain-core.
|
||||
|
||||
A unit test ensures all modules in ``block_translators`` are represented here.
|
||||
A unit test ensures all modules in `block_translators` are represented here.
|
||||
|
||||
For translators implemented outside langchain-core, they can be registered by
|
||||
calling ``register_translator`` from within the integration package.
|
||||
calling `register_translator` from within the integration package.
|
||||
"""
|
||||
from langchain_core.messages.block_translators.anthropic import ( # noqa: PLC0415
|
||||
_register_anthropic_translator,
|
||||
|
||||
@@ -32,11 +32,11 @@ def _convert_to_v1_from_anthropic_input(
|
||||
"""Convert Anthropic format blocks to v1 format.
|
||||
|
||||
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``
|
||||
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.
|
||||
|
||||
If conversion fails, the block is left as a ``'non_standard'`` block.
|
||||
If conversion fails, the block is left as a `'non_standard'` block.
|
||||
|
||||
Args:
|
||||
content: List of content blocks to process.
|
||||
|
||||
@@ -36,11 +36,11 @@ def _convert_to_v1_from_converse_input(
|
||||
"""Convert Bedrock Converse format blocks to v1 format.
|
||||
|
||||
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``
|
||||
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.
|
||||
|
||||
If conversion fails, the block is left as a ``'non_standard'`` block.
|
||||
If conversion fails, the block is left as a `'non_standard'` block.
|
||||
|
||||
Args:
|
||||
content: List of content blocks to process.
|
||||
|
||||
@@ -106,11 +106,11 @@ def _convert_to_v1_from_genai_input(
|
||||
`response_metadata`.
|
||||
|
||||
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``
|
||||
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.
|
||||
|
||||
If conversion fails, the block is left as a ``'non_standard'`` block.
|
||||
If conversion fails, the block is left as a `'non_standard'` block.
|
||||
|
||||
Args:
|
||||
content: List of content blocks to process.
|
||||
|
||||
@@ -11,11 +11,11 @@ def _convert_v0_multimodal_input_to_v1(
|
||||
"""Convert v0 multimodal blocks to v1 format.
|
||||
|
||||
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``
|
||||
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.
|
||||
|
||||
If conversion fails, the block is left as a ``'non_standard'`` block.
|
||||
If conversion fails, the block is left as a `'non_standard'` block.
|
||||
|
||||
Args:
|
||||
content: List of content blocks to process.
|
||||
|
||||
@@ -18,7 +18,7 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
def convert_to_openai_image_block(block: dict[str, Any]) -> dict:
|
||||
"""Convert ``ImageContentBlock`` to format expected by OpenAI Chat Completions."""
|
||||
"""Convert `ImageContentBlock` to format expected by OpenAI Chat Completions."""
|
||||
if "url" in block:
|
||||
return {
|
||||
"type": "image_url",
|
||||
@@ -156,11 +156,11 @@ def _convert_to_v1_from_chat_completions_input(
|
||||
"""Convert OpenAI Chat Completions format blocks to v1 format.
|
||||
|
||||
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``
|
||||
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.
|
||||
|
||||
If conversion fails, the block is left as a ``'non_standard'`` block.
|
||||
If conversion fails, the block is left as a `'non_standard'` block.
|
||||
|
||||
Args:
|
||||
content: List of content blocks to process.
|
||||
@@ -263,7 +263,7 @@ _FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__"
|
||||
|
||||
|
||||
def _convert_from_v03_ai_message(message: AIMessage) -> AIMessage:
|
||||
"""Convert v0 AIMessage into ``output_version="responses/v1"`` format."""
|
||||
"""Convert v0 AIMessage into `output_version="responses/v1"` format."""
|
||||
from langchain_core.messages import AIMessageChunk # noqa: PLC0415
|
||||
|
||||
# Only update ChatOpenAI v0.3 AIMessages
|
||||
|
||||
@@ -31,7 +31,7 @@ class ChatMessageChunk(ChatMessage, BaseMessageChunk):
|
||||
type: Literal["ChatMessageChunk"] = "ChatMessageChunk" # type: ignore[assignment]
|
||||
"""The type of the message (used during serialization).
|
||||
|
||||
Defaults to ``'ChatMessageChunk'``.
|
||||
Defaults to `'ChatMessageChunk'`.
|
||||
|
||||
"""
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
change in future releases.
|
||||
|
||||
This module provides standardized data structures for representing inputs to and
|
||||
outputs from LLMs. The core abstraction is the **Content Block**, a ``TypedDict``.
|
||||
outputs from LLMs. The core abstraction is the **Content Block**, a `TypedDict`.
|
||||
|
||||
**Rationale**
|
||||
|
||||
@@ -20,22 +20,22 @@ blocks into the format required by its API.
|
||||
**Extensibility**
|
||||
|
||||
Data **not yet mapped** to a standard block may be represented using the
|
||||
``NonStandardContentBlock``, which allows for provider-specific data to be included
|
||||
`NonStandardContentBlock`, which allows for provider-specific data to be included
|
||||
without losing the benefits of type checking and validation.
|
||||
|
||||
Furthermore, provider-specific fields **within** a standard block are fully supported
|
||||
by default in the ``extras`` field of each block. This allows for additional metadata
|
||||
by default in the `extras` field of each block. This allows for additional metadata
|
||||
to be included without breaking the standard structure.
|
||||
|
||||
!!! warning
|
||||
Do not heavily rely on the ``extras`` field for provider-specific data! This field
|
||||
Do not heavily rely on the `extras` field for provider-specific data! This field
|
||||
is subject to deprecation in future releases as we move towards PEP 728.
|
||||
|
||||
!!! note
|
||||
Following widespread adoption of [PEP 728](https://peps.python.org/pep-0728/), we
|
||||
will add ``extra_items=Any`` as a param to Content Blocks. This will signify to type
|
||||
will add `extra_items=Any` as a param to Content Blocks. This will signify to type
|
||||
checkers that additional provider-specific fields are allowed outside of the
|
||||
``extras`` field, and that will become the new standard approach to adding
|
||||
`extras` field, and that will become the new standard approach to adding
|
||||
provider-specific metadata.
|
||||
|
||||
??? note
|
||||
@@ -72,7 +72,7 @@ to be included without breaking the standard structure.
|
||||
# Mutating an existing block to add provider-specific fields
|
||||
openai_data = my_block["openai_metadata"] # Type: Any
|
||||
|
||||
PEP 728 is enabled with ``# type: ignore[call-arg]`` comments to suppress
|
||||
PEP 728 is enabled with `# type: ignore[call-arg]` comments to suppress
|
||||
warnings from type checkers that don't yet support it. The functionality works
|
||||
correctly in Python 3.13+ and will be fully supported as the ecosystem catches
|
||||
up.
|
||||
@@ -81,16 +81,16 @@ to be included without breaking the standard structure.
|
||||
|
||||
The module defines several types of content blocks, including:
|
||||
|
||||
- ``TextContentBlock``: Standard text output.
|
||||
- ``Citation``: For annotations that link text output to a source document.
|
||||
- ``ToolCall``: For function calling.
|
||||
- ``ReasoningContentBlock``: To capture a model's thought process.
|
||||
- `TextContentBlock`: Standard text output.
|
||||
- `Citation`: For annotations that link text output to a source document.
|
||||
- `ToolCall`: For function calling.
|
||||
- `ReasoningContentBlock`: To capture a model's thought process.
|
||||
- Multimodal data:
|
||||
- ``ImageContentBlock``
|
||||
- ``AudioContentBlock``
|
||||
- ``VideoContentBlock``
|
||||
- ``PlainTextContentBlock`` (e.g. .txt or .md files)
|
||||
- ``FileContentBlock`` (e.g. PDFs, etc.)
|
||||
- `ImageContentBlock`
|
||||
- `AudioContentBlock`
|
||||
- `VideoContentBlock`
|
||||
- `PlainTextContentBlock` (e.g. .txt or .md files)
|
||||
- `FileContentBlock` (e.g. PDFs, etc.)
|
||||
|
||||
**Example Usage**
|
||||
|
||||
@@ -140,12 +140,12 @@ class Citation(TypedDict):
|
||||
"""Annotation for citing data from a document.
|
||||
|
||||
!!! note
|
||||
``start``/``end`` indices refer to the **response text**,
|
||||
`start`/`end` indices refer to the **response text**,
|
||||
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``).
|
||||
response, not the original document (as specified in the `url`).
|
||||
|
||||
!!! note
|
||||
``create_citation`` may also be used as a factory to create a ``Citation``.
|
||||
`create_citation` may also be used as a factory to create a `Citation`.
|
||||
Benefits include:
|
||||
|
||||
* Automatic ID generation (when not provided)
|
||||
@@ -160,7 +160,7 @@ class Citation(TypedDict):
|
||||
"""Content block identifier. Either:
|
||||
|
||||
- Generated by the provider (e.g., OpenAI's file ID)
|
||||
- Generated by LangChain upon creation (``UUID4`` prefixed with ``'lc_'``))
|
||||
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
|
||||
|
||||
"""
|
||||
|
||||
@@ -174,10 +174,10 @@ class Citation(TypedDict):
|
||||
"""
|
||||
|
||||
start_index: NotRequired[int]
|
||||
"""Start index of the **response text** (``TextContentBlock.text``)."""
|
||||
"""Start index of the **response text** (`TextContentBlock.text`)."""
|
||||
|
||||
end_index: NotRequired[int]
|
||||
"""End index of the **response text** (``TextContentBlock.text``)"""
|
||||
"""End index of the **response text** (`TextContentBlock.text`)"""
|
||||
|
||||
cited_text: NotRequired[str]
|
||||
"""Excerpt of source text being cited."""
|
||||
@@ -203,7 +203,7 @@ class NonStandardAnnotation(TypedDict):
|
||||
|
||||
Either:
|
||||
- Generated by the provider (e.g., OpenAI's file ID)
|
||||
- Generated by LangChain upon creation (``UUID4`` prefixed with ``'lc_'``))
|
||||
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
|
||||
|
||||
"""
|
||||
|
||||
@@ -221,8 +221,8 @@ class TextContentBlock(TypedDict):
|
||||
from a language model or the text of a user message.
|
||||
|
||||
!!! note
|
||||
``create_text_block`` may also be used as a factory to create a
|
||||
``TextContentBlock``. Benefits include:
|
||||
`create_text_block` may also be used as a factory to create a
|
||||
`TextContentBlock`. Benefits include:
|
||||
|
||||
* Automatic ID generation (when not provided)
|
||||
* Required arguments strictly validated at creation time
|
||||
@@ -237,7 +237,7 @@ class TextContentBlock(TypedDict):
|
||||
|
||||
Either:
|
||||
- Generated by the provider (e.g., OpenAI's file ID)
|
||||
- Generated by LangChain upon creation (``UUID4`` prefixed with ``'lc_'``))
|
||||
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
|
||||
|
||||
"""
|
||||
|
||||
@@ -245,7 +245,7 @@ class TextContentBlock(TypedDict):
|
||||
"""Block text."""
|
||||
|
||||
annotations: NotRequired[list[Annotation]]
|
||||
"""``Citation``s and other annotations."""
|
||||
"""`Citation`s and other annotations."""
|
||||
|
||||
index: NotRequired[int | str]
|
||||
"""Index of block in aggregate response. Used during streaming."""
|
||||
@@ -267,8 +267,8 @@ class ToolCall(TypedDict):
|
||||
and an identifier of "123".
|
||||
|
||||
!!! note
|
||||
``create_tool_call`` may also be used as a factory to create a
|
||||
``ToolCall``. Benefits include:
|
||||
`create_tool_call` may also be used as a factory to create a
|
||||
`ToolCall`. Benefits include:
|
||||
|
||||
* Automatic ID generation (when not provided)
|
||||
* Required arguments strictly validated at creation time
|
||||
@@ -303,9 +303,9 @@ class ToolCall(TypedDict):
|
||||
class ToolCallChunk(TypedDict):
|
||||
"""A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunks`` (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunks` (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not `None`.
|
||||
values of `index` are equal and not `None`.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -457,8 +457,8 @@ class ReasoningContentBlock(TypedDict):
|
||||
"""Reasoning output from a LLM.
|
||||
|
||||
!!! note
|
||||
``create_reasoning_block`` may also be used as a factory to create a
|
||||
``ReasoningContentBlock``. Benefits include:
|
||||
`create_reasoning_block` may also be used as a factory to create a
|
||||
`ReasoningContentBlock`. Benefits include:
|
||||
|
||||
* Automatic ID generation (when not provided)
|
||||
* Required arguments strictly validated at creation time
|
||||
@@ -473,7 +473,7 @@ class ReasoningContentBlock(TypedDict):
|
||||
|
||||
Either:
|
||||
- Generated by the provider (e.g., OpenAI's file ID)
|
||||
- Generated by LangChain upon creation (``UUID4`` prefixed with ``'lc_'``))
|
||||
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
|
||||
|
||||
"""
|
||||
|
||||
@@ -481,7 +481,7 @@ class ReasoningContentBlock(TypedDict):
|
||||
"""Reasoning text.
|
||||
|
||||
Either the thought summary or the raw reasoning text itself. This is often parsed
|
||||
from ``<think>`` tags in the model's response.
|
||||
from `<think>` tags in the model's response.
|
||||
|
||||
"""
|
||||
|
||||
@@ -499,8 +499,8 @@ class ImageContentBlock(TypedDict):
|
||||
"""Image data.
|
||||
|
||||
!!! note
|
||||
``create_image_block`` may also be used as a factory to create a
|
||||
``ImageContentBlock``. Benefits include:
|
||||
`create_image_block` may also be used as a factory to create a
|
||||
`ImageContentBlock`. Benefits include:
|
||||
|
||||
* Automatic ID generation (when not provided)
|
||||
* Required arguments strictly validated at creation time
|
||||
@@ -515,7 +515,7 @@ class ImageContentBlock(TypedDict):
|
||||
|
||||
Either:
|
||||
- Generated by the provider (e.g., OpenAI's file ID)
|
||||
- Generated by LangChain upon creation (``UUID4`` prefixed with ``'lc_'``))
|
||||
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
|
||||
|
||||
"""
|
||||
|
||||
@@ -546,8 +546,8 @@ class VideoContentBlock(TypedDict):
|
||||
"""Video data.
|
||||
|
||||
!!! note
|
||||
``create_video_block`` may also be used as a factory to create a
|
||||
``VideoContentBlock``. Benefits include:
|
||||
`create_video_block` may also be used as a factory to create a
|
||||
`VideoContentBlock`. Benefits include:
|
||||
|
||||
* Automatic ID generation (when not provided)
|
||||
* Required arguments strictly validated at creation time
|
||||
@@ -562,7 +562,7 @@ class VideoContentBlock(TypedDict):
|
||||
|
||||
Either:
|
||||
- Generated by the provider (e.g., OpenAI's file ID)
|
||||
- Generated by LangChain upon creation (``UUID4`` prefixed with ``'lc_'``))
|
||||
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
|
||||
|
||||
"""
|
||||
|
||||
@@ -593,8 +593,8 @@ class AudioContentBlock(TypedDict):
|
||||
"""Audio data.
|
||||
|
||||
!!! note
|
||||
``create_audio_block`` may also be used as a factory to create an
|
||||
``AudioContentBlock``. Benefits include:
|
||||
`create_audio_block` may also be used as a factory to create an
|
||||
`AudioContentBlock`. Benefits include:
|
||||
* Automatic ID generation (when not provided)
|
||||
* Required arguments strictly validated at creation time
|
||||
|
||||
@@ -608,7 +608,7 @@ class AudioContentBlock(TypedDict):
|
||||
|
||||
Either:
|
||||
- Generated by the provider (e.g., OpenAI's file ID)
|
||||
- Generated by LangChain upon creation (``UUID4`` prefixed with ``'lc_'``))
|
||||
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
|
||||
|
||||
"""
|
||||
|
||||
@@ -639,18 +639,18 @@ class PlainTextContentBlock(TypedDict):
|
||||
"""Plaintext data (e.g., from a document).
|
||||
|
||||
!!! note
|
||||
A ``PlainTextContentBlock`` existed in ``langchain-core<1.0.0``. Although the
|
||||
A `PlainTextContentBlock` existed in `langchain-core<1.0.0`. Although the
|
||||
name has carried over, the structure has changed significantly. The only shared
|
||||
keys between the old and new versions are `type` and ``text``, though the
|
||||
`type` value has changed from ``'text'`` to ``'text-plain'``.
|
||||
keys between the old and new versions are `type` and `text`, though the
|
||||
`type` value has changed from `'text'` to `'text-plain'`.
|
||||
|
||||
!!! note
|
||||
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
|
||||
``create_plaintext_block`` may also be used as a factory to create a
|
||||
``PlainTextContentBlock``. Benefits include:
|
||||
`create_plaintext_block` may also be used as a factory to create a
|
||||
`PlainTextContentBlock`. Benefits include:
|
||||
|
||||
* Automatic ID generation (when not provided)
|
||||
* Required arguments strictly validated at creation time
|
||||
@@ -665,7 +665,7 @@ class PlainTextContentBlock(TypedDict):
|
||||
|
||||
Either:
|
||||
- Generated by the provider (e.g., OpenAI's file ID)
|
||||
- Generated by LangChain upon creation (``UUID4`` prefixed with ``'lc_'``))
|
||||
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
|
||||
|
||||
"""
|
||||
|
||||
@@ -704,12 +704,12 @@ class FileContentBlock(TypedDict):
|
||||
example, it can be used for PDFs, Word documents, etc.
|
||||
|
||||
If the file is an image, audio, or plaintext, you should use the corresponding
|
||||
content block type (e.g., ``ImageContentBlock``, ``AudioContentBlock``,
|
||||
``PlainTextContentBlock``).
|
||||
content block type (e.g., `ImageContentBlock`, `AudioContentBlock`,
|
||||
`PlainTextContentBlock`).
|
||||
|
||||
!!! note
|
||||
``create_file_block`` may also be used as a factory to create a
|
||||
``FileContentBlock``. Benefits include:
|
||||
`create_file_block` may also be used as a factory to create a
|
||||
`FileContentBlock`. Benefits include:
|
||||
|
||||
* Automatic ID generation (when not provided)
|
||||
* Required arguments strictly validated at creation time
|
||||
@@ -724,7 +724,7 @@ class FileContentBlock(TypedDict):
|
||||
|
||||
Either:
|
||||
- Generated by the provider (e.g., OpenAI's file ID)
|
||||
- Generated by LangChain upon creation (``UUID4`` prefixed with ``'lc_'``))
|
||||
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
|
||||
|
||||
"""
|
||||
|
||||
@@ -764,14 +764,14 @@ class NonStandardContentBlock(TypedDict):
|
||||
The purpose of this block should be to simply hold a provider-specific payload.
|
||||
If a provider's non-standard output includes reasoning and tool calls, it should be
|
||||
the adapter's job to parse that payload and emit the corresponding standard
|
||||
``ReasoningContentBlock`` and ``ToolCalls``.
|
||||
`ReasoningContentBlock` and `ToolCalls`.
|
||||
|
||||
Has no ``extras`` field, as provider-specific data should be included in the
|
||||
``value`` field.
|
||||
Has no `extras` field, as provider-specific data should be included in the
|
||||
`value` field.
|
||||
|
||||
!!! note
|
||||
``create_non_standard_block`` may also be used as a factory to create a
|
||||
``NonStandardContentBlock``. Benefits include:
|
||||
`create_non_standard_block` may also be used as a factory to create a
|
||||
`NonStandardContentBlock`. Benefits include:
|
||||
|
||||
* Automatic ID generation (when not provided)
|
||||
* Required arguments strictly validated at creation time
|
||||
@@ -786,7 +786,7 @@ class NonStandardContentBlock(TypedDict):
|
||||
|
||||
Either:
|
||||
- Generated by the provider (e.g., OpenAI's file ID)
|
||||
- Generated by LangChain upon creation (``UUID4`` prefixed with ``'lc_'``))
|
||||
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
|
||||
|
||||
"""
|
||||
|
||||
@@ -842,7 +842,7 @@ KNOWN_BLOCK_TYPES = {
|
||||
"non_standard",
|
||||
# citation and non_standard_annotation intentionally omitted
|
||||
}
|
||||
"""These are block types known to ``langchain-core>=1.0.0``.
|
||||
"""These are block types known to `langchain-core>=1.0.0`.
|
||||
|
||||
If a block has a type not in this set, it is considered to be provider-specific.
|
||||
"""
|
||||
@@ -923,20 +923,20 @@ def create_text_block(
|
||||
index: int | str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> TextContentBlock:
|
||||
"""Create a ``TextContentBlock``.
|
||||
"""Create a `TextContentBlock`.
|
||||
|
||||
Args:
|
||||
text: The text content of the block.
|
||||
id: Content block identifier. Generated automatically if not provided.
|
||||
annotations: ``Citation``s and other annotations for the text.
|
||||
annotations: `Citation`s and other annotations for the text.
|
||||
index: Index of block in aggregate response. Used during streaming.
|
||||
|
||||
Returns:
|
||||
A properly formatted ``TextContentBlock``.
|
||||
A properly formatted `TextContentBlock`.
|
||||
|
||||
!!! note
|
||||
The `id` is generated automatically if not provided, using a UUID4 format
|
||||
prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID.
|
||||
prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
|
||||
|
||||
"""
|
||||
block = TextContentBlock(
|
||||
@@ -966,7 +966,7 @@ def create_image_block(
|
||||
index: int | str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> ImageContentBlock:
|
||||
"""Create an ``ImageContentBlock``.
|
||||
"""Create an `ImageContentBlock`.
|
||||
|
||||
Args:
|
||||
url: URL of the image.
|
||||
@@ -977,15 +977,15 @@ def create_image_block(
|
||||
index: Index of block in aggregate response. Used during streaming.
|
||||
|
||||
Returns:
|
||||
A properly formatted ``ImageContentBlock``.
|
||||
A properly formatted `ImageContentBlock`.
|
||||
|
||||
Raises:
|
||||
ValueError: If no image source is provided or if ``base64`` is used without
|
||||
``mime_type``.
|
||||
ValueError: If no image source is provided or if `base64` is used without
|
||||
`mime_type`.
|
||||
|
||||
!!! note
|
||||
The `id` is generated automatically if not provided, using a UUID4 format
|
||||
prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID.
|
||||
prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
|
||||
|
||||
"""
|
||||
if not any([url, base64, file_id]):
|
||||
@@ -1022,7 +1022,7 @@ def create_video_block(
|
||||
index: int | str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> VideoContentBlock:
|
||||
"""Create a ``VideoContentBlock``.
|
||||
"""Create a `VideoContentBlock`.
|
||||
|
||||
Args:
|
||||
url: URL of the video.
|
||||
@@ -1033,15 +1033,15 @@ def create_video_block(
|
||||
index: Index of block in aggregate response. Used during streaming.
|
||||
|
||||
Returns:
|
||||
A properly formatted ``VideoContentBlock``.
|
||||
A properly formatted `VideoContentBlock`.
|
||||
|
||||
Raises:
|
||||
ValueError: If no video source is provided or if ``base64`` is used without
|
||||
``mime_type``.
|
||||
ValueError: If no video source is provided or if `base64` is used without
|
||||
`mime_type`.
|
||||
|
||||
!!! note
|
||||
The `id` is generated automatically if not provided, using a UUID4 format
|
||||
prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID.
|
||||
prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
|
||||
|
||||
"""
|
||||
if not any([url, base64, file_id]):
|
||||
@@ -1082,7 +1082,7 @@ def create_audio_block(
|
||||
index: int | str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> AudioContentBlock:
|
||||
"""Create an ``AudioContentBlock``.
|
||||
"""Create an `AudioContentBlock`.
|
||||
|
||||
Args:
|
||||
url: URL of the audio.
|
||||
@@ -1093,15 +1093,15 @@ def create_audio_block(
|
||||
index: Index of block in aggregate response. Used during streaming.
|
||||
|
||||
Returns:
|
||||
A properly formatted ``AudioContentBlock``.
|
||||
A properly formatted `AudioContentBlock`.
|
||||
|
||||
Raises:
|
||||
ValueError: If no audio source is provided or if ``base64`` is used without
|
||||
``mime_type``.
|
||||
ValueError: If no audio source is provided or if `base64` is used without
|
||||
`mime_type`.
|
||||
|
||||
!!! note
|
||||
The `id` is generated automatically if not provided, using a UUID4 format
|
||||
prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID.
|
||||
prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
|
||||
|
||||
"""
|
||||
if not any([url, base64, file_id]):
|
||||
@@ -1142,7 +1142,7 @@ def create_file_block(
|
||||
index: int | str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> FileContentBlock:
|
||||
"""Create a ``FileContentBlock``.
|
||||
"""Create a `FileContentBlock`.
|
||||
|
||||
Args:
|
||||
url: URL of the file.
|
||||
@@ -1153,15 +1153,15 @@ def create_file_block(
|
||||
index: Index of block in aggregate response. Used during streaming.
|
||||
|
||||
Returns:
|
||||
A properly formatted ``FileContentBlock``.
|
||||
A properly formatted `FileContentBlock`.
|
||||
|
||||
Raises:
|
||||
ValueError: If no file source is provided or if ``base64`` is used without
|
||||
``mime_type``.
|
||||
ValueError: If no file source is provided or if `base64` is used without
|
||||
`mime_type`.
|
||||
|
||||
!!! note
|
||||
The `id` is generated automatically if not provided, using a UUID4 format
|
||||
prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID.
|
||||
prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
|
||||
|
||||
"""
|
||||
if not any([url, base64, file_id]):
|
||||
@@ -1203,7 +1203,7 @@ def create_plaintext_block(
|
||||
index: int | str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> PlainTextContentBlock:
|
||||
"""Create a ``PlainTextContentBlock``.
|
||||
"""Create a `PlainTextContentBlock`.
|
||||
|
||||
Args:
|
||||
text: The plaintext content.
|
||||
@@ -1216,11 +1216,11 @@ def create_plaintext_block(
|
||||
index: Index of block in aggregate response. Used during streaming.
|
||||
|
||||
Returns:
|
||||
A properly formatted ``PlainTextContentBlock``.
|
||||
A properly formatted `PlainTextContentBlock`.
|
||||
|
||||
!!! note
|
||||
The `id` is generated automatically if not provided, using a UUID4 format
|
||||
prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID.
|
||||
prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
|
||||
|
||||
"""
|
||||
block = PlainTextContentBlock(
|
||||
@@ -1259,7 +1259,7 @@ def create_tool_call(
|
||||
index: int | str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> ToolCall:
|
||||
"""Create a ``ToolCall``.
|
||||
"""Create a `ToolCall`.
|
||||
|
||||
Args:
|
||||
name: The name of the tool to be called.
|
||||
@@ -1268,11 +1268,11 @@ def create_tool_call(
|
||||
index: Index of block in aggregate response. Used during streaming.
|
||||
|
||||
Returns:
|
||||
A properly formatted ``ToolCall``.
|
||||
A properly formatted `ToolCall`.
|
||||
|
||||
!!! note
|
||||
The `id` is generated automatically if not provided, using a UUID4 format
|
||||
prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID.
|
||||
prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
|
||||
|
||||
"""
|
||||
block = ToolCall(
|
||||
@@ -1298,7 +1298,7 @@ def create_reasoning_block(
|
||||
index: int | str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> ReasoningContentBlock:
|
||||
"""Create a ``ReasoningContentBlock``.
|
||||
"""Create a `ReasoningContentBlock`.
|
||||
|
||||
Args:
|
||||
reasoning: The reasoning text or thought summary.
|
||||
@@ -1306,11 +1306,11 @@ def create_reasoning_block(
|
||||
index: Index of block in aggregate response. Used during streaming.
|
||||
|
||||
Returns:
|
||||
A properly formatted ``ReasoningContentBlock``.
|
||||
A properly formatted `ReasoningContentBlock`.
|
||||
|
||||
!!! note
|
||||
The `id` is generated automatically if not provided, using a UUID4 format
|
||||
prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID.
|
||||
prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
|
||||
|
||||
"""
|
||||
block = ReasoningContentBlock(
|
||||
@@ -1339,7 +1339,7 @@ def create_citation(
|
||||
id: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> Citation:
|
||||
"""Create a ``Citation``.
|
||||
"""Create a `Citation`.
|
||||
|
||||
Args:
|
||||
url: URL of the document source.
|
||||
@@ -1350,11 +1350,11 @@ def create_citation(
|
||||
id: Content block identifier. Generated automatically if not provided.
|
||||
|
||||
Returns:
|
||||
A properly formatted ``Citation``.
|
||||
A properly formatted `Citation`.
|
||||
|
||||
!!! note
|
||||
The `id` is generated automatically if not provided, using a UUID4 format
|
||||
prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID.
|
||||
prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
|
||||
|
||||
"""
|
||||
block = Citation(type="citation", id=ensure_id(id))
|
||||
@@ -1383,7 +1383,7 @@ def create_non_standard_block(
|
||||
id: str | None = None,
|
||||
index: int | str | None = None,
|
||||
) -> NonStandardContentBlock:
|
||||
"""Create a ``NonStandardContentBlock``.
|
||||
"""Create a `NonStandardContentBlock`.
|
||||
|
||||
Args:
|
||||
value: Provider-specific data.
|
||||
@@ -1391,11 +1391,11 @@ def create_non_standard_block(
|
||||
index: Index of block in aggregate response. Used during streaming.
|
||||
|
||||
Returns:
|
||||
A properly formatted ``NonStandardContentBlock``.
|
||||
A properly formatted `NonStandardContentBlock`.
|
||||
|
||||
!!! note
|
||||
The `id` is generated automatically if not provided, using a UUID4 format
|
||||
prefixed with ``'lc_'`` to indicate it is a LangChain-generated ID.
|
||||
prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
|
||||
|
||||
"""
|
||||
block = NonStandardContentBlock(
|
||||
|
||||
@@ -15,7 +15,7 @@ from langchain_core.utils._merge import merge_dicts
|
||||
class FunctionMessage(BaseMessage):
|
||||
"""Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -28,7 +28,7 @@ class FunctionMessage(BaseMessage):
|
||||
"""The name of the function that was executed."""
|
||||
|
||||
type: Literal["function"] = "function"
|
||||
"""The type of the message (used for serialization). Defaults to ``'function'``."""
|
||||
"""The type of the message (used for serialization). Defaults to `'function'`."""
|
||||
|
||||
|
||||
class FunctionMessageChunk(FunctionMessage, BaseMessageChunk):
|
||||
@@ -40,7 +40,7 @@ class FunctionMessageChunk(FunctionMessage, BaseMessageChunk):
|
||||
type: Literal["FunctionMessageChunk"] = "FunctionMessageChunk" # type: ignore[assignment]
|
||||
"""The type of the message (used for serialization).
|
||||
|
||||
Defaults to ``'FunctionMessageChunk'``.
|
||||
Defaults to `'FunctionMessageChunk'`.
|
||||
|
||||
"""
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ class HumanMessage(BaseMessage):
|
||||
type: Literal["human"] = "human"
|
||||
"""The type of the message (used for serialization).
|
||||
|
||||
Defaults to ``'human'``.
|
||||
Defaults to `'human'`.
|
||||
|
||||
"""
|
||||
|
||||
@@ -56,7 +56,7 @@ class HumanMessage(BaseMessage):
|
||||
content_blocks: list[types.ContentBlock] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""Specify ``content`` as positional arg or ``content_blocks`` for typing."""
|
||||
"""Specify `content` as positional arg or `content_blocks` for typing."""
|
||||
if content_blocks is not None:
|
||||
super().__init__(
|
||||
content=cast("str | list[str | dict]", content_blocks),
|
||||
|
||||
@@ -31,7 +31,7 @@ class SystemMessage(BaseMessage):
|
||||
type: Literal["system"] = "system"
|
||||
"""The type of the message (used for serialization).
|
||||
|
||||
Defaults to ``'system'``.
|
||||
Defaults to `'system'`.
|
||||
|
||||
"""
|
||||
|
||||
@@ -56,7 +56,7 @@ class SystemMessage(BaseMessage):
|
||||
content_blocks: list[types.ContentBlock] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""Specify ``content`` as positional arg or ``content_blocks`` for typing."""
|
||||
"""Specify `content` as positional arg or `content_blocks` for typing."""
|
||||
if content_blocks is not None:
|
||||
super().__init__(
|
||||
content=cast("str | list[str | dict]", content_blocks),
|
||||
@@ -75,6 +75,6 @@ class SystemMessageChunk(SystemMessage, BaseMessageChunk):
|
||||
type: Literal["SystemMessageChunk"] = "SystemMessageChunk" # type: ignore[assignment]
|
||||
"""The type of the message (used for serialization).
|
||||
|
||||
Defaults to ``'SystemMessageChunk'``.
|
||||
Defaults to `'SystemMessageChunk'`.
|
||||
|
||||
"""
|
||||
@@ -16,8 +16,8 @@ from langchain_core.utils._merge import merge_dicts, merge_obj
|
||||
class ToolOutputMixin:
|
||||
"""Mixin for objects that tools can return directly.
|
||||
|
||||
If a custom BaseTool is invoked with a ``ToolCall`` and the output of custom code is
|
||||
not an instance of ``ToolOutputMixin``, the output will automatically be coerced to
|
||||
If a custom BaseTool is invoked with a `ToolCall` and the output of custom code is
|
||||
not an instance of `ToolOutputMixin`, the output will automatically be coerced to
|
||||
a string and wrapped in a `ToolMessage`.
|
||||
|
||||
"""
|
||||
@@ -27,9 +27,9 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
|
||||
"""Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -72,7 +72,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
|
||||
type: Literal["tool"] = "tool"
|
||||
"""The type of the message (used for serialization).
|
||||
|
||||
Defaults to ``'tool'``.
|
||||
Defaults to `'tool'`.
|
||||
|
||||
"""
|
||||
|
||||
@@ -167,7 +167,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
|
||||
) -> None:
|
||||
"""Initialize `ToolMessage`.
|
||||
|
||||
Specify ``content`` as positional arg or ``content_blocks`` for typing.
|
||||
Specify `content` as positional arg or `content_blocks` for typing.
|
||||
|
||||
Args:
|
||||
content: The string contents of the message.
|
||||
@@ -224,8 +224,8 @@ class ToolCall(TypedDict):
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
|
||||
"""
|
||||
|
||||
@@ -265,9 +265,9 @@ def tool_call(
|
||||
class ToolCallChunk(TypedDict):
|
||||
"""A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
|
||||
@@ -97,9 +97,9 @@ def get_buffer_string(
|
||||
Args:
|
||||
messages: Messages to be converted to strings.
|
||||
human_prefix: The prefix to prepend to contents of `HumanMessage`s.
|
||||
Default is ``'Human'``.
|
||||
Default is `'Human'`.
|
||||
ai_prefix: The prefix to prepend to contents of `AIMessage`. Default is
|
||||
``'AI'``.
|
||||
`'AI'`.
|
||||
|
||||
Returns:
|
||||
A single string concatenation of all input messages.
|
||||
@@ -178,7 +178,7 @@ def _message_from_dict(message: dict) -> BaseMessage:
|
||||
|
||||
|
||||
def messages_from_dict(messages: Sequence[dict]) -> list[BaseMessage]:
|
||||
"""Convert a sequence of messages from dicts to ``Message`` objects.
|
||||
"""Convert a sequence of messages from dicts to `Message` objects.
|
||||
|
||||
Args:
|
||||
messages: Sequence of messages (as dicts) to convert.
|
||||
@@ -191,7 +191,7 @@ def messages_from_dict(messages: Sequence[dict]) -> list[BaseMessage]:
|
||||
|
||||
|
||||
def message_chunk_to_message(chunk: BaseMessage) -> BaseMessage:
|
||||
"""Convert a message chunk to a ``Message``.
|
||||
"""Convert a message chunk to a `Message`.
|
||||
|
||||
Args:
|
||||
chunk: Message chunk to convert.
|
||||
@@ -224,10 +224,10 @@ def _create_message_from_message_type(
|
||||
id: str | None = None,
|
||||
**additional_kwargs: Any,
|
||||
) -> BaseMessage:
|
||||
"""Create a message from a ``Message`` type and content string.
|
||||
"""Create a message from a `Message` type and content string.
|
||||
|
||||
Args:
|
||||
message_type: (str) the type of the message (e.g., ``'human'``, ``'ai'``, etc.).
|
||||
message_type: (str) the type of the message (e.g., `'human'`, `'ai'`, etc.).
|
||||
content: (str) the content string.
|
||||
name: (str) the name of the message. Default is None.
|
||||
tool_call_id: (str) the tool call id. Default is None.
|
||||
@@ -239,9 +239,9 @@ def _create_message_from_message_type(
|
||||
a message of the appropriate type.
|
||||
|
||||
Raises:
|
||||
ValueError: if the message type is not one of ``'human'``, ``'user'``, ``'ai'``,
|
||||
``'assistant'``, ``'function'``, ``'tool'``, ``'system'``, or
|
||||
``'developer'``.
|
||||
ValueError: if the message type is not one of `'human'`, `'user'`, `'ai'`,
|
||||
`'assistant'`, `'function'`, `'tool'`, `'system'`, or
|
||||
`'developer'`.
|
||||
"""
|
||||
kwargs: dict[str, Any] = {}
|
||||
if name is not None:
|
||||
@@ -307,15 +307,15 @@ def _create_message_from_message_type(
|
||||
|
||||
|
||||
def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage:
|
||||
"""Instantiate a ``Message`` from a variety of message formats.
|
||||
"""Instantiate a `Message` from a variety of message formats.
|
||||
|
||||
The message format can be one of the following:
|
||||
|
||||
- ``BaseMessagePromptTemplate``
|
||||
- `BaseMessagePromptTemplate`
|
||||
- `BaseMessage`
|
||||
- 2-tuple of (role string, template); e.g., (``'human'``, ``'{user_input}'``)
|
||||
- 2-tuple of (role string, template); e.g., (`'human'`, `'{user_input}'`)
|
||||
- dict: a message dict with role and content keys
|
||||
- string: shorthand for (``'human'``, template); e.g., ``'{user_input}'``
|
||||
- string: shorthand for (`'human'`, template); e.g., `'{user_input}'`
|
||||
|
||||
Args:
|
||||
message: a representation of a message in one of the supported formats.
|
||||
@@ -430,11 +430,11 @@ def filter_messages(
|
||||
include_names: Message names to include. Default is None.
|
||||
exclude_names: Messages names to exclude. Default is None.
|
||||
include_types: Message types to include. Can be specified as string names
|
||||
(e.g. ``'system'``, ``'human'``, ``'ai'``, ...) or as `BaseMessage`
|
||||
(e.g. `'system'`, `'human'`, `'ai'`, ...) or as `BaseMessage`
|
||||
classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...).
|
||||
Default is None.
|
||||
exclude_types: Message types to exclude. Can be specified as string names
|
||||
(e.g. ``'system'``, ``'human'``, ``'ai'``, ...) or as `BaseMessage`
|
||||
(e.g. `'system'`, `'human'`, `'ai'`, ...) or as `BaseMessage`
|
||||
classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...).
|
||||
Default is None.
|
||||
include_ids: Message IDs to include. Default is None.
|
||||
@@ -442,17 +442,17 @@ def filter_messages(
|
||||
exclude_tool_calls: Tool call IDs to exclude. Default is None.
|
||||
Can be one of the following:
|
||||
- `True`: all `AIMessage`s with tool calls and all
|
||||
`ToolMessage` objects will be excluded.
|
||||
`ToolMessage` objects will be excluded.
|
||||
- a sequence of tool call IDs to exclude:
|
||||
- `ToolMessage` objects with the corresponding tool call ID will be
|
||||
excluded.
|
||||
- The `tool_calls` in the AIMessage will be updated to exclude
|
||||
matching tool calls. If all `tool_calls` are filtered from an
|
||||
AIMessage, the whole message is excluded.
|
||||
- `ToolMessage` objects with the corresponding tool call ID will be
|
||||
excluded.
|
||||
- The `tool_calls` in the AIMessage will be updated to exclude
|
||||
matching tool calls. If all `tool_calls` are filtered from an
|
||||
AIMessage, the whole message is excluded.
|
||||
|
||||
Returns:
|
||||
A list of Messages that meets at least one of the ``incl_*`` conditions and none
|
||||
of the ``excl_*`` conditions. If not ``incl_*`` conditions are specified then
|
||||
A list of Messages that meets at least one of the `incl_*` conditions and none
|
||||
of the `excl_*` conditions. If not `incl_*` conditions are specified then
|
||||
anything that is not explicitly excluded will be included.
|
||||
|
||||
Raises:
|
||||
@@ -571,7 +571,7 @@ def merge_message_runs(
|
||||
Args:
|
||||
messages: Sequence Message-like objects to merge.
|
||||
chunk_separator: Specify the string to be inserted between message chunks.
|
||||
Defaults to ``'\n'``.
|
||||
Defaults to `'\n'`.
|
||||
|
||||
Returns:
|
||||
list of BaseMessages with consecutive runs of message types merged into single
|
||||
@@ -579,7 +579,7 @@ def merge_message_runs(
|
||||
the merged content is a concatenation of the two strings with a new-line
|
||||
separator.
|
||||
The separator inserted between message chunks can be controlled by specifying
|
||||
any string with ``chunk_separator``. If at least one of the messages has a list
|
||||
any string with `chunk_separator`. If at least one of the messages has a list
|
||||
of content blocks, the merged content is a list of content blocks.
|
||||
|
||||
Example:
|
||||
@@ -706,7 +706,7 @@ def trim_messages(
|
||||
) -> list[BaseMessage]:
|
||||
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
|
||||
`trim_messages` can be used to reduce the size of a chat history to a specified
|
||||
token count or specified message count.
|
||||
|
||||
In either case, if passing the trimmed chat history back into a chat model
|
||||
@@ -714,22 +714,22 @@ def trim_messages(
|
||||
properties:
|
||||
|
||||
1. The resulting chat history should be valid. Most chat models expect that chat
|
||||
history starts with either (1) a `HumanMessage` or (2) a `SystemMessage`
|
||||
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
|
||||
history starts with either (1) a `HumanMessage` or (2) a `SystemMessage`
|
||||
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'``.
|
||||
To achieve this set the `strategy='last'`.
|
||||
3. Usually, the new chat history should include the `SystemMessage` if it
|
||||
was present in the original chat history since the `SystemMessage` includes
|
||||
special instructions to the chat model. The `SystemMessage` is almost always
|
||||
the first message in the history if present. To achieve this set the
|
||||
``include_system=True``.
|
||||
was present in the original chat history since the `SystemMessage` includes
|
||||
special instructions to the chat model. The `SystemMessage` is almost always
|
||||
the first message in the history if present. To achieve this set the
|
||||
`include_system=True`.
|
||||
|
||||
!!! note
|
||||
The examples below show how to configure ``trim_messages`` to achieve a behavior
|
||||
The examples below show how to configure `trim_messages` to achieve a behavior
|
||||
consistent with the above properties.
|
||||
|
||||
Args:
|
||||
@@ -737,49 +737,49 @@ def trim_messages(
|
||||
max_tokens: Max token count of trimmed messages.
|
||||
token_counter: Function or llm for counting tokens in a `BaseMessage` or a
|
||||
list of `BaseMessage`. If a `BaseLanguageModel` is passed in then
|
||||
``BaseLanguageModel.get_num_tokens_from_messages()`` will be used.
|
||||
Set to ``len`` to count the number of **messages** in the chat history.
|
||||
`BaseLanguageModel.get_num_tokens_from_messages()` will be used.
|
||||
Set to `len` to count the number of **messages** in the chat history.
|
||||
|
||||
!!! note
|
||||
Use ``count_tokens_approximately`` to get fast, approximate token
|
||||
Use `count_tokens_approximately` to get fast, approximate token
|
||||
counts.
|
||||
This is recommended for using ``trim_messages`` on the hot path, where
|
||||
This is recommended for using `trim_messages` on the hot path, where
|
||||
exact token counting is not necessary.
|
||||
|
||||
strategy: Strategy for trimming.
|
||||
- ``'first'``: Keep the first ``<= n_count`` tokens of the messages.
|
||||
- ``'last'``: Keep the last ``<= n_count`` tokens of the messages.
|
||||
Default is ``'last'``.
|
||||
- `'first'`: Keep the first `<= n_count` tokens of the messages.
|
||||
- `'last'`: Keep the last `<= n_count` tokens of the messages.
|
||||
Default is `'last'`.
|
||||
allow_partial: Whether to split a message if only part of the message can be
|
||||
included. If ``strategy='last'`` then the last partial contents of a message
|
||||
are included. If ``strategy='first'`` then the first partial contents of a
|
||||
included. If `strategy='last'` then the last partial contents of a message
|
||||
are included. If `strategy='first'` then the first partial contents of a
|
||||
message are included.
|
||||
Default is False.
|
||||
end_on: The message type to end on. If specified then every message after the
|
||||
last occurrence of this type is ignored. If ``strategy='last'`` then this
|
||||
is done before we attempt to get the last ``max_tokens``. If
|
||||
``strategy='first'`` then this is done after we get the first
|
||||
``max_tokens``. Can be specified as string names (e.g. ``'system'``,
|
||||
``'human'``, ``'ai'``, ...) or as `BaseMessage` classes (e.g.
|
||||
last occurrence of this type is ignored. If `strategy='last'` then this
|
||||
is done before we attempt to get the last `max_tokens`. If
|
||||
`strategy='first'` then this is done after we get the first
|
||||
`max_tokens`. Can be specified as string names (e.g. `'system'`,
|
||||
`'human'`, `'ai'`, ...) or as `BaseMessage` classes (e.g.
|
||||
`SystemMessage`, `HumanMessage`, `AIMessage`, ...). Can be a single
|
||||
type or a list of types.
|
||||
Default is None.
|
||||
start_on: The message type to start on. Should only be specified if
|
||||
``strategy='last'``. If specified then every message before
|
||||
`strategy='last'`. If specified then every message before
|
||||
the first occurrence of this type is ignored. This is done after we trim
|
||||
the initial messages to the last ``max_tokens``. Does not
|
||||
apply to a `SystemMessage` at index 0 if ``include_system=True``. Can be
|
||||
specified as string names (e.g. ``'system'``, ``'human'``, ``'ai'``, ...) or
|
||||
the initial messages to the last `max_tokens`. Does not
|
||||
apply to a `SystemMessage` at index 0 if `include_system=True`. Can be
|
||||
specified as string names (e.g. `'system'`, `'human'`, `'ai'`, ...) or
|
||||
as `BaseMessage` classes (e.g. `SystemMessage`, `HumanMessage`,
|
||||
`AIMessage`, ...). Can be a single type or a list of types.
|
||||
Default is None.
|
||||
include_system: Whether to keep the SystemMessage if there is one at index 0.
|
||||
Should only be specified if ``strategy="last"``.
|
||||
Should only be specified if `strategy="last"`.
|
||||
Default is False.
|
||||
text_splitter: Function or ``langchain_text_splitters.TextSplitter`` for
|
||||
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
|
||||
from a partial message will be included. if ``strategy='first'`` then the
|
||||
`allow_partial=True`. If `strategy='last'` then the last split tokens
|
||||
from a partial message will be included. if `strategy='first'` then the
|
||||
first split tokens from a partial message will be included. Token splitter
|
||||
assumes that separators are kept, so that split contents can be directly
|
||||
concatenated to recreate the original text. Defaults to splitting on
|
||||
@@ -790,7 +790,7 @@ def trim_messages(
|
||||
|
||||
Raises:
|
||||
ValueError: if two incompatible arguments are specified or an unrecognized
|
||||
``strategy`` is specified.
|
||||
`strategy` is specified.
|
||||
|
||||
Example:
|
||||
Trim chat history based on token count, keeping the `SystemMessage` if
|
||||
@@ -1042,21 +1042,21 @@ def convert_to_openai_messages(
|
||||
messages: Message-like object or iterable of objects whose contents are
|
||||
in OpenAI, Anthropic, Bedrock Converse, or VertexAI formats.
|
||||
text_format: How to format string or text block contents:
|
||||
- ``'string'``:
|
||||
- `'string'`:
|
||||
If a message has a string content, this is left as a string. If
|
||||
a message has content blocks that are all of type ``'text'``, these
|
||||
a message has content blocks that are all of type `'text'`, these
|
||||
are joined with a newline to make a single string. If a message has
|
||||
content blocks and at least one isn't of type ``'text'``, then
|
||||
content blocks and at least one isn't of type `'text'`, then
|
||||
all blocks are left as dicts.
|
||||
- ``'block'``:
|
||||
- `'block'`:
|
||||
If a message has a string content, this is turned into a list
|
||||
with a single content block of type ``'text'``. If a message has
|
||||
with a single content block of type `'text'`. If a message has
|
||||
content blocks these are left as is.
|
||||
include_id: Whether to include message ids in the openai messages, if they
|
||||
are present in the source messages.
|
||||
|
||||
Raises:
|
||||
ValueError: if an unrecognized ``text_format`` is specified, or if a message
|
||||
ValueError: if an unrecognized `text_format` is specified, or if a message
|
||||
content block is missing expected keys.
|
||||
|
||||
Returns:
|
||||
|
||||
@@ -149,7 +149,7 @@ class CommaSeparatedListOutputParser(ListOutputParser):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "output_parsers", "list"]``
|
||||
`["langchain", "output_parsers", "list"]`
|
||||
"""
|
||||
return ["langchain", "output_parsers", "list"]
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ class StrOutputParser(BaseTransformOutputParser[str]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "output_parser"]``
|
||||
`["langchain", "schema", "output_parser"]`
|
||||
"""
|
||||
return ["langchain", "schema", "output_parser"]
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ When invoking models via the standard runnable methods (e.g. invoke, batch, etc.
|
||||
- LLMs will return regular text strings.
|
||||
|
||||
In addition, users can access the raw output of either LLMs or chat models via
|
||||
callbacks. The ``on_chat_model_end`` and ``on_llm_end`` callbacks will return an
|
||||
callbacks. The `on_chat_model_end` and `on_llm_end` callbacks will return an
|
||||
LLMResult object containing the generated outputs and any additional information
|
||||
returned by the model provider.
|
||||
|
||||
|
||||
@@ -15,10 +15,10 @@ from langchain_core.utils._merge import merge_dicts
|
||||
class ChatGeneration(Generation):
|
||||
"""A single chat generation output.
|
||||
|
||||
A subclass of ``Generation`` that represents the response from a chat model
|
||||
A subclass of `Generation` that represents the response from a chat model
|
||||
that generates chat messages.
|
||||
|
||||
The ``message`` attribute is a structured representation of the chat message.
|
||||
The `message` attribute is a structured representation of the chat message.
|
||||
Most of the time, the message will be of type `AIMessage`.
|
||||
|
||||
Users working with chat models will usually access information via either
|
||||
@@ -70,9 +70,9 @@ class ChatGeneration(Generation):
|
||||
|
||||
|
||||
class ChatGenerationChunk(ChatGeneration):
|
||||
"""``ChatGeneration`` chunk.
|
||||
"""`ChatGeneration` chunk.
|
||||
|
||||
``ChatGeneration`` chunks can be concatenated with other ``ChatGeneration`` chunks.
|
||||
`ChatGeneration` chunks can be concatenated with other `ChatGeneration` chunks.
|
||||
"""
|
||||
|
||||
message: BaseMessageChunk
|
||||
|
||||
@@ -47,7 +47,7 @@ class Generation(Serializable):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "output"]``
|
||||
`["langchain", "schema", "output"]`
|
||||
"""
|
||||
return ["langchain", "schema", "output"]
|
||||
|
||||
@@ -56,16 +56,16 @@ class GenerationChunk(Generation):
|
||||
"""Generation chunk, which can be concatenated with other Generation chunks."""
|
||||
|
||||
def __add__(self, other: GenerationChunk) -> GenerationChunk:
|
||||
"""Concatenate two ``GenerationChunk``s.
|
||||
"""Concatenate two `GenerationChunk`s.
|
||||
|
||||
Args:
|
||||
other: Another ``GenerationChunk`` to concatenate with.
|
||||
other: Another `GenerationChunk` to concatenate with.
|
||||
|
||||
Raises:
|
||||
TypeError: If other is not a ``GenerationChunk``.
|
||||
TypeError: If other is not a `GenerationChunk`.
|
||||
|
||||
Returns:
|
||||
A new ``GenerationChunk`` concatenated from self and other.
|
||||
A new `GenerationChunk` concatenated from self and other.
|
||||
"""
|
||||
if isinstance(other, GenerationChunk):
|
||||
generation_info = merge_dicts(
|
||||
|
||||
@@ -30,8 +30,8 @@ class LLMResult(BaseModel):
|
||||
The second dimension of the list represents different candidate generations for a
|
||||
given prompt.
|
||||
|
||||
- When returned from **an LLM**, the type is ``list[list[Generation]]``.
|
||||
- When returned from a **chat model**, the type is ``list[list[ChatGeneration]]``.
|
||||
- When returned from **an LLM**, the type is `list[list[Generation]]`.
|
||||
- When returned from a **chat model**, the type is `list[list[ChatGeneration]]`.
|
||||
|
||||
ChatGeneration is a subclass of Generation that has a field for a structured chat
|
||||
message.
|
||||
@@ -97,7 +97,7 @@ class LLMResult(BaseModel):
|
||||
other: Another `LLMResult` object to compare against.
|
||||
|
||||
Returns:
|
||||
True if the generations and ``llm_output`` are equal, False otherwise.
|
||||
True if the generations and `llm_output` are equal, False otherwise.
|
||||
"""
|
||||
if not isinstance(other, LLMResult):
|
||||
return NotImplemented
|
||||
|
||||
@@ -40,7 +40,7 @@ class PromptValue(Serializable, ABC):
|
||||
This is used to determine the namespace of the object when serializing.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "prompt"]``
|
||||
`["langchain", "schema", "prompt"]`
|
||||
"""
|
||||
return ["langchain", "schema", "prompt"]
|
||||
|
||||
@@ -67,7 +67,7 @@ class StringPromptValue(PromptValue):
|
||||
This is used to determine the namespace of the object when serializing.
|
||||
|
||||
Returns:
|
||||
``["langchain", "prompts", "base"]``
|
||||
`["langchain", "prompts", "base"]`
|
||||
"""
|
||||
return ["langchain", "prompts", "base"]
|
||||
|
||||
@@ -104,7 +104,7 @@ class ChatPromptValue(PromptValue):
|
||||
This is used to determine the namespace of the object when serializing.
|
||||
|
||||
Returns:
|
||||
``["langchain", "prompts", "chat"]``
|
||||
`["langchain", "prompts", "chat"]`
|
||||
"""
|
||||
return ["langchain", "prompts", "chat"]
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ class BasePromptTemplate(
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "prompt_template"]``
|
||||
`["langchain", "schema", "prompt_template"]`
|
||||
"""
|
||||
return ["langchain", "schema", "prompt_template"]
|
||||
|
||||
|
||||
@@ -238,11 +238,11 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
|
||||
template: a template.
|
||||
template_format: format of the template. Defaults to "f-string".
|
||||
partial_variables: A dictionary of variables that can be used to partially
|
||||
fill in the template. For example, if the template is
|
||||
`"{variable1} {variable2}"`, and `partial_variables` is
|
||||
`{"variable1": "foo"}`, then the final prompt will be
|
||||
`"foo {variable2}"`.
|
||||
Defaults to `None`.
|
||||
fill in the template. For example, if the template is
|
||||
`"{variable1} {variable2}"`, and `partial_variables` is
|
||||
`{"variable1": "foo"}`, then the final prompt will be
|
||||
`"foo {variable2}"`.
|
||||
Defaults to `None`.
|
||||
**kwargs: keyword arguments to pass to the constructor.
|
||||
|
||||
Returns:
|
||||
@@ -685,7 +685,7 @@ class BaseChatPromptTemplate(BasePromptTemplate, ABC):
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for filling in template variables
|
||||
in all the template messages in this chat template.
|
||||
in all the template messages in this chat template.
|
||||
|
||||
Returns:
|
||||
formatted string.
|
||||
@@ -697,7 +697,7 @@ class BaseChatPromptTemplate(BasePromptTemplate, ABC):
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for filling in template variables
|
||||
in all the template messages in this chat template.
|
||||
in all the template messages in this chat template.
|
||||
|
||||
Returns:
|
||||
formatted string.
|
||||
@@ -781,7 +781,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
Examples:
|
||||
!!! warning "Behavior changed in 0.2.24"
|
||||
You can pass any Message-like formats supported by
|
||||
``ChatPromptTemplate.from_messages()`` directly to ``ChatPromptTemplate()``
|
||||
`ChatPromptTemplate.from_messages()` directly to `ChatPromptTemplate()`
|
||||
init.
|
||||
|
||||
.. code-block:: python
|
||||
@@ -902,11 +902,11 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
|
||||
Args:
|
||||
messages: sequence of message representations.
|
||||
A message can be represented using the following formats:
|
||||
(1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
|
||||
(message type, template); e.g., ("human", "{user_input}"),
|
||||
(4) 2-tuple of (message class, template), (5) a string which is
|
||||
shorthand for ("human", template); e.g., "{user_input}".
|
||||
A message can be represented using the following formats:
|
||||
(1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
|
||||
(message type, template); e.g., ("human", "{user_input}"),
|
||||
(4) 2-tuple of (message class, template), (5) a string which is
|
||||
shorthand for ("human", template); e.g., "{user_input}".
|
||||
template_format: format of the template. Defaults to "f-string".
|
||||
input_variables: A list of the names of the variables whose values are
|
||||
required as inputs to the prompt.
|
||||
@@ -977,7 +977,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "prompts", "chat"]``
|
||||
`["langchain", "prompts", "chat"]`
|
||||
"""
|
||||
return ["langchain", "prompts", "chat"]
|
||||
|
||||
@@ -1127,11 +1127,11 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
|
||||
Args:
|
||||
messages: sequence of message representations.
|
||||
A message can be represented using the following formats:
|
||||
(1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
|
||||
(message type, template); e.g., ("human", "{user_input}"),
|
||||
(4) 2-tuple of (message class, template), (5) a string which is
|
||||
shorthand for ("human", template); e.g., "{user_input}".
|
||||
A message can be represented using the following formats:
|
||||
(1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
|
||||
(message type, template); e.g., ("human", "{user_input}"),
|
||||
(4) 2-tuple of (message class, template), (5) a string which is
|
||||
shorthand for ("human", template); e.g., "{user_input}".
|
||||
template_format: format of the template. Defaults to "f-string".
|
||||
|
||||
Returns:
|
||||
@@ -1145,7 +1145,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for filling in template variables
|
||||
in all the template messages in this chat template.
|
||||
in all the template messages in this chat template.
|
||||
|
||||
Raises:
|
||||
ValueError: if messages are of unexpected types.
|
||||
@@ -1173,7 +1173,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
|
||||
Args:
|
||||
**kwargs: keyword arguments to use for filling in template variables
|
||||
in all the template messages in this chat template.
|
||||
in all the template messages in this chat template.
|
||||
|
||||
Returns:
|
||||
list of formatted messages.
|
||||
@@ -1262,7 +1262,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
|
||||
Returns:
|
||||
If index is an int, returns the message at that index.
|
||||
If index is a slice, returns a new ``ChatPromptTemplate``
|
||||
If index is a slice, returns a new `ChatPromptTemplate`
|
||||
containing the messages in that slice.
|
||||
"""
|
||||
if isinstance(index, slice):
|
||||
|
||||
@@ -77,7 +77,7 @@ class DictPromptTemplate(RunnableSerializable[dict, dict]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain_core", "prompts", "dict"]``
|
||||
`["langchain_core", "prompts", "dict"]`
|
||||
"""
|
||||
return ["langchain_core", "prompts", "dict"]
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "prompts", "few_shot_with_templates"]``
|
||||
`["langchain", "prompts", "few_shot_with_templates"]`
|
||||
"""
|
||||
return ["langchain", "prompts", "few_shot_with_templates"]
|
||||
|
||||
|
||||
@@ -26,8 +26,8 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
|
||||
"""Create an image prompt template.
|
||||
|
||||
Raises:
|
||||
ValueError: If the input variables contain ``'url'``, ``'path'``, or
|
||||
``'detail'``.
|
||||
ValueError: If the input variables contain `'url'`, `'path'`, or
|
||||
`'detail'`.
|
||||
"""
|
||||
if "input_variables" not in kwargs:
|
||||
kwargs["input_variables"] = []
|
||||
@@ -52,7 +52,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "prompts", "image"]``
|
||||
`["langchain", "prompts", "image"]`
|
||||
"""
|
||||
return ["langchain", "prompts", "image"]
|
||||
|
||||
@@ -93,7 +93,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
|
||||
Raises:
|
||||
ValueError: If the url is not provided.
|
||||
ValueError: If the url is not a string.
|
||||
ValueError: If ``'path'`` is provided in the template or kwargs.
|
||||
ValueError: If `'path'` is provided in the template or kwargs.
|
||||
|
||||
Example:
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ class BaseMessagePromptTemplate(Serializable, ABC):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "prompts", "chat"]``
|
||||
`["langchain", "prompts", "chat"]`
|
||||
"""
|
||||
return ["langchain", "prompts", "chat"]
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ class PromptTemplate(StringPromptTemplate):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "prompts", "prompt"]``
|
||||
`["langchain", "prompts", "prompt"]`
|
||||
"""
|
||||
return ["langchain", "prompts", "prompt"]
|
||||
|
||||
@@ -144,10 +144,10 @@ class PromptTemplate(StringPromptTemplate):
|
||||
Raises:
|
||||
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.
|
||||
A new `PromptTemplate` that is the combination of the two.
|
||||
"""
|
||||
# Allow for easy combining
|
||||
if isinstance(other, PromptTemplate):
|
||||
|
||||
@@ -276,7 +276,7 @@ class StringPromptTemplate(BasePromptTemplate, ABC):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "prompts", "base"]``
|
||||
`["langchain", "prompts", "base"]`
|
||||
"""
|
||||
return ["langchain", "prompts", "base"]
|
||||
|
||||
|
||||
@@ -65,8 +65,8 @@ class StructuredPrompt(ChatPromptTemplate):
|
||||
def get_lc_namespace(cls) -> list[str]:
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
For example, if the class is ``langchain.llms.openai.OpenAI``, then the
|
||||
namespace is ``["langchain", "llms", "openai"]``
|
||||
For example, if the class is `langchain.llms.openai.OpenAI`, then the
|
||||
namespace is `["langchain", "llms", "openai"]`
|
||||
|
||||
Returns:
|
||||
The namespace of the langchain object.
|
||||
@@ -106,14 +106,14 @@ class StructuredPrompt(ChatPromptTemplate):
|
||||
|
||||
Args:
|
||||
messages: sequence of message representations.
|
||||
A message can be represented using the following formats:
|
||||
(1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
|
||||
(message type, template); e.g., ("human", "{user_input}"),
|
||||
(4) 2-tuple of (message class, template), (5) a string which is
|
||||
shorthand for ("human", template); e.g., "{user_input}"
|
||||
A message can be represented using the following formats:
|
||||
(1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
|
||||
(message type, template); e.g., ("human", "{user_input}"),
|
||||
(4) 2-tuple of (message class, template), (5) a string which is
|
||||
shorthand for ("human", template); e.g., "{user_input}"
|
||||
schema: a dictionary representation of function call, or a Pydantic model.
|
||||
**kwargs: Any additional kwargs to pass through to
|
||||
``ChatModel.with_structured_output(schema, **kwargs)``.
|
||||
`ChatModel.with_structured_output(schema, **kwargs)`.
|
||||
|
||||
Returns:
|
||||
a structured prompt template
|
||||
|
||||
@@ -129,22 +129,22 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
- **`batch`/`abatch`**: Efficiently transforms multiple inputs into outputs.
|
||||
- **`stream`/`astream`**: Streams output from a single input as it's produced.
|
||||
- **`astream_log`**: Streams output and selected intermediate results from an
|
||||
input.
|
||||
input.
|
||||
|
||||
Built-in optimizations:
|
||||
|
||||
- **Batch**: By default, batch runs invoke() in parallel using a thread pool
|
||||
executor. Override to optimize batching.
|
||||
executor. Override to optimize batching.
|
||||
|
||||
- **Async**: Methods with `'a'` suffix are asynchronous. By default, they execute
|
||||
the sync counterpart using asyncio's thread pool.
|
||||
Override for native async.
|
||||
the sync counterpart using asyncio's thread pool.
|
||||
Override for native async.
|
||||
|
||||
All methods accept an optional config argument, which can be used to configure
|
||||
execution, add tags and metadata for tracing and debugging etc.
|
||||
|
||||
Runnables expose schematic information about their input, output and config via
|
||||
the ``input_schema`` property, the ``output_schema`` property and ``config_schema``
|
||||
the `input_schema` property, the `output_schema` property and `config_schema`
|
||||
method.
|
||||
|
||||
LCEL and Composition
|
||||
@@ -155,15 +155,15 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
Any chain constructed this way will automatically have sync, async, batch, and
|
||||
streaming support.
|
||||
|
||||
The main composition primitives are `RunnableSequence` and ``RunnableParallel``.
|
||||
The main composition primitives are `RunnableSequence` and `RunnableParallel`.
|
||||
|
||||
**`RunnableSequence`** invokes a series of runnables sequentially, with
|
||||
one Runnable's output serving as the next's input. Construct using
|
||||
the ``|`` operator or by passing a list of runnables to `RunnableSequence`.
|
||||
the `|` operator or by passing a list of runnables to `RunnableSequence`.
|
||||
|
||||
**``RunnableParallel``** invokes runnables concurrently, providing the same input
|
||||
**`RunnableParallel`** invokes runnables concurrently, providing the same input
|
||||
to each. Construct it using a dict literal within a sequence or by passing a
|
||||
dict to ``RunnableParallel``.
|
||||
dict to `RunnableParallel`.
|
||||
|
||||
|
||||
For example,
|
||||
@@ -818,9 +818,9 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
Args:
|
||||
input: The input to the `Runnable`.
|
||||
config: A config to use when invoking the `Runnable`.
|
||||
The config supports standard keys like ``'tags'``, ``'metadata'`` for
|
||||
tracing purposes, ``'max_concurrency'`` for controlling how much work to
|
||||
do in parallel, and other keys. Please refer to the ``RunnableConfig``
|
||||
The config supports standard keys like `'tags'`, `'metadata'` for
|
||||
tracing purposes, `'max_concurrency'` for controlling how much work to
|
||||
do in parallel, and other keys. Please refer to the `RunnableConfig`
|
||||
for more details. Defaults to `None`.
|
||||
|
||||
Returns:
|
||||
@@ -838,9 +838,9 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
Args:
|
||||
input: The input to the `Runnable`.
|
||||
config: A config to use when invoking the `Runnable`.
|
||||
The config supports standard keys like ``'tags'``, ``'metadata'`` for
|
||||
tracing purposes, ``'max_concurrency'`` for controlling how much work to
|
||||
do in parallel, and other keys. Please refer to the ``RunnableConfig``
|
||||
The config supports standard keys like `'tags'`, `'metadata'` for
|
||||
tracing purposes, `'max_concurrency'` for controlling how much work to
|
||||
do in parallel, and other keys. Please refer to the `RunnableConfig`
|
||||
for more details. Defaults to `None`.
|
||||
|
||||
Returns:
|
||||
@@ -866,10 +866,10 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
Args:
|
||||
inputs: A list of inputs to the `Runnable`.
|
||||
config: A config to use when invoking the `Runnable`. The config supports
|
||||
standard keys like ``'tags'``, ``'metadata'`` for
|
||||
tracing purposes, ``'max_concurrency'`` for controlling how much work
|
||||
standard keys like `'tags'`, `'metadata'` for
|
||||
tracing purposes, `'max_concurrency'` for controlling how much work
|
||||
to do in parallel, and other keys. Please refer to the
|
||||
``RunnableConfig`` for more details. Defaults to `None`.
|
||||
`RunnableConfig` for more details. Defaults to `None`.
|
||||
return_exceptions: Whether to return exceptions instead of raising them.
|
||||
Defaults to `False`.
|
||||
**kwargs: Additional keyword arguments to pass to the `Runnable`.
|
||||
@@ -933,9 +933,9 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
Args:
|
||||
inputs: A list of inputs to the `Runnable`.
|
||||
config: A config to use when invoking the `Runnable`.
|
||||
The config supports standard keys like ``'tags'``, ``'metadata'`` for
|
||||
tracing purposes, ``'max_concurrency'`` for controlling how much work to
|
||||
do in parallel, and other keys. Please refer to the ``RunnableConfig``
|
||||
The config supports standard keys like `'tags'`, `'metadata'` for
|
||||
tracing purposes, `'max_concurrency'` for controlling how much work to
|
||||
do in parallel, and other keys. Please refer to the `RunnableConfig`
|
||||
for more details. Defaults to `None`.
|
||||
return_exceptions: Whether to return exceptions instead of raising them.
|
||||
Defaults to `False`.
|
||||
@@ -990,7 +990,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
return_exceptions: bool = False,
|
||||
**kwargs: Any | None,
|
||||
) -> list[Output]:
|
||||
"""Default implementation runs `ainvoke` in parallel using ``asyncio.gather``.
|
||||
"""Default implementation runs `ainvoke` in parallel using `asyncio.gather`.
|
||||
|
||||
The default implementation of `batch` works well for IO bound runnables.
|
||||
|
||||
@@ -1000,9 +1000,9 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
Args:
|
||||
inputs: A list of inputs to the `Runnable`.
|
||||
config: A config to use when invoking the `Runnable`.
|
||||
The config supports standard keys like ``'tags'``, ``'metadata'`` for
|
||||
tracing purposes, ``'max_concurrency'`` for controlling how much work to
|
||||
do in parallel, and other keys. Please refer to the ``RunnableConfig``
|
||||
The config supports standard keys like `'tags'`, `'metadata'` for
|
||||
tracing purposes, `'max_concurrency'` for controlling how much work to
|
||||
do in parallel, and other keys. Please refer to the `RunnableConfig`
|
||||
for more details. Defaults to `None`.
|
||||
return_exceptions: Whether to return exceptions instead of raising them.
|
||||
Defaults to `False`.
|
||||
@@ -1064,9 +1064,9 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
Args:
|
||||
inputs: A list of inputs to the `Runnable`.
|
||||
config: A config to use when invoking the `Runnable`.
|
||||
The config supports standard keys like ``'tags'``, ``'metadata'`` for
|
||||
tracing purposes, ``'max_concurrency'`` for controlling how much work to
|
||||
do in parallel, and other keys. Please refer to the ``RunnableConfig``
|
||||
The config supports standard keys like `'tags'`, `'metadata'` for
|
||||
tracing purposes, `'max_concurrency'` for controlling how much work to
|
||||
do in parallel, and other keys. Please refer to the `RunnableConfig`
|
||||
for more details. Defaults to `None`.
|
||||
return_exceptions: Whether to return exceptions instead of raising them.
|
||||
Defaults to `False`.
|
||||
@@ -1213,7 +1213,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
input: The input to the `Runnable`.
|
||||
config: The config to use for the `Runnable`.
|
||||
diff: Whether to yield diffs between each step or the current state.
|
||||
with_streamed_output_list: Whether to yield the ``streamed_output`` list.
|
||||
with_streamed_output_list: Whether to yield the `streamed_output` list.
|
||||
include_names: Only include logs with these names.
|
||||
include_types: Only include logs with these types.
|
||||
include_tags: Only include logs with these tags.
|
||||
@@ -1223,7 +1223,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
**kwargs: Additional keyword arguments to pass to the `Runnable`.
|
||||
|
||||
Yields:
|
||||
A ``RunLogPatch`` or ``RunLog`` object.
|
||||
A `RunLogPatch` or `RunLog` object.
|
||||
|
||||
"""
|
||||
stream = LogStreamCallbackHandler(
|
||||
@@ -1271,24 +1271,24 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
about the progress of the `Runnable`, including `StreamEvent` from intermediate
|
||||
results.
|
||||
|
||||
A ``StreamEvent`` is a dictionary with the following schema:
|
||||
A `StreamEvent` is a dictionary with the following schema:
|
||||
|
||||
- ``event``: **str** - Event names are of the format:
|
||||
``on_[runnable_type]_(start|stream|end)``.
|
||||
- `event`: **str** - Event names are of the format:
|
||||
`on_[runnable_type]_(start|stream|end)`.
|
||||
- `name`: **str** - The name of the `Runnable` that generated the event.
|
||||
- ``run_id``: **str** - randomly generated ID associated with the given
|
||||
execution of the `Runnable` that emitted the event. A child `Runnable` that gets
|
||||
invoked as part of the execution of a parent `Runnable` is assigned its own
|
||||
unique ID.
|
||||
- ``parent_ids``: **list[str]** - The IDs of the parent runnables that generated
|
||||
the event. The root `Runnable` will have an empty list. The order of the parent
|
||||
IDs is from the root to the immediate parent. Only available for v2 version of
|
||||
the API. The v1 version of the API will return an empty list.
|
||||
- ``tags``: **list[str] | None** - The tags of the `Runnable` that generated
|
||||
the event.
|
||||
- ``metadata``: **dict[str, Any] | None** - The metadata of the `Runnable` that
|
||||
generated the event.
|
||||
- ``data``: **dict[str, Any]**
|
||||
- `run_id`: **str** - randomly generated ID associated with the given
|
||||
execution of the `Runnable` that emitted the event. A child `Runnable` that gets
|
||||
invoked as part of the execution of a parent `Runnable` is assigned its own
|
||||
unique ID.
|
||||
- `parent_ids`: **list[str]** - The IDs of the parent runnables that generated
|
||||
the event. The root `Runnable` will have an empty list. The order of the parent
|
||||
IDs is from the root to the immediate parent. Only available for v2 version of
|
||||
the API. The v1 version of the API will return an empty list.
|
||||
- `tags`: **list[str] | None** - The tags of the `Runnable` that generated
|
||||
the event.
|
||||
- `metadata`: **dict[str, Any] | None** - The metadata of the `Runnable` that
|
||||
generated the event.
|
||||
- `data`: **dict[str, Any]**
|
||||
|
||||
Below is a table that illustrates some events that might be emitted by various
|
||||
chains. Metadata fields have been omitted from the table for brevity.
|
||||
@@ -1300,35 +1300,35 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| event | name | chunk | input | output |
|
||||
+==========================+==================+=====================================+===================================================+=====================================================+
|
||||
| ``on_chat_model_start`` | [model name] | | ``{"messages": [[SystemMessage, HumanMessage]]}`` | |
|
||||
| `on_chat_model_start` | [model name] | | `{"messages": [[SystemMessage, HumanMessage]]}` | |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_chat_model_stream`` | [model name] | ``AIMessageChunk(content="hello")`` | | |
|
||||
| `on_chat_model_stream` | [model name] | `AIMessageChunk(content="hello")` | | |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_chat_model_end`` | [model name] | | ``{"messages": [[SystemMessage, HumanMessage]]}`` | ``AIMessageChunk(content="hello world")`` |
|
||||
| `on_chat_model_end` | [model name] | | `{"messages": [[SystemMessage, HumanMessage]]}` | `AIMessageChunk(content="hello world")` |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_llm_start`` | [model name] | | ``{'input': 'hello'}`` | |
|
||||
| `on_llm_start` | [model name] | | `{'input': 'hello'}` | |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_llm_stream`` | [model name] | ``'Hello' `` | | |
|
||||
| `on_llm_stream` | [model name] | `'Hello' ` | | |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_llm_end`` | [model name] | | ``'Hello human!'`` | |
|
||||
| `on_llm_end` | [model name] | | `'Hello human!'` | |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_chain_start`` | format_docs | | | |
|
||||
| `on_chain_start` | format_docs | | | |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_chain_stream`` | format_docs | ``'hello world!, goodbye world!'`` | | |
|
||||
| `on_chain_stream` | format_docs | `'hello world!, goodbye world!'` | | |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_chain_end`` | format_docs | | ``[Document(...)]`` | ``'hello world!, goodbye world!'`` |
|
||||
| `on_chain_end` | format_docs | | `[Document(...)]` | `'hello world!, goodbye world!'` |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_tool_start`` | some_tool | | ``{"x": 1, "y": "2"}`` | |
|
||||
| `on_tool_start` | some_tool | | `{"x": 1, "y": "2"}` | |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_tool_end`` | some_tool | | | ``{"x": 1, "y": "2"}`` |
|
||||
| `on_tool_end` | some_tool | | | `{"x": 1, "y": "2"}` |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_retriever_start`` | [retriever name] | | ``{"query": "hello"}`` | |
|
||||
| `on_retriever_start` | [retriever name] | | `{"query": "hello"}` | |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_retriever_end`` | [retriever name] | | ``{"query": "hello"}`` | ``[Document(...), ..]`` |
|
||||
| `on_retriever_end` | [retriever name] | | `{"query": "hello"}` | `[Document(...), ..]` |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_prompt_start`` | [template_name] | | ``{"question": "hello"}`` | |
|
||||
| `on_prompt_start` | [template_name] | | `{"question": "hello"}` | |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
| ``on_prompt_end`` | [template_name] | | ``{"question": "hello"}`` | ``ChatPromptValue(messages: [SystemMessage, ...])`` |
|
||||
| `on_prompt_end` | [template_name] | | `{"question": "hello"}` | `ChatPromptValue(messages: [SystemMessage, ...])` |
|
||||
+--------------------------+------------------+-------------------------------------+---------------------------------------------------+-----------------------------------------------------+
|
||||
|
||||
In addition to the standard events, users can also dispatch custom events (see example below).
|
||||
@@ -1347,7 +1347,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
|
||||
Here are declarations associated with the standard events shown above:
|
||||
|
||||
``format_docs``:
|
||||
`format_docs`:
|
||||
|
||||
```python
|
||||
def format_docs(docs: list[Document]) -> str:
|
||||
@@ -1358,7 +1358,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
format_docs = RunnableLambda(format_docs)
|
||||
```
|
||||
|
||||
``some_tool``:
|
||||
`some_tool`:
|
||||
|
||||
```python
|
||||
@tool
|
||||
@@ -1367,7 +1367,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
return {"x": x, "y": y}
|
||||
```
|
||||
|
||||
``prompt``:
|
||||
`prompt`:
|
||||
|
||||
```python
|
||||
template = ChatPromptTemplate.from_messages(
|
||||
@@ -1447,17 +1447,17 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
|
||||
async for event in slow_thing.astream_events("some_input", version="v2"):
|
||||
print(event)
|
||||
```
|
||||
``
|
||||
|
||||
Args:
|
||||
input: The input to the `Runnable`.
|
||||
config: The config to use for the `Runnable`.
|
||||
version: The version of the schema to use either `'v2'` or `'v1'`.
|
||||
Users should use `'v2'`.
|
||||
`'v1'` is for backwards compatibility and will be deprecated
|
||||
in `0.4.0`.
|
||||
No default will be assigned until the API is stabilized.
|
||||
custom events will only be surfaced in `'v2'`.
|
||||
Users should use `'v2'`.
|
||||
`'v1'` is for backwards compatibility and will be deprecated
|
||||
in `0.4.0`.
|
||||
No default will be assigned until the API is stabilized.
|
||||
custom events will only be surfaced in `'v2'`.
|
||||
include_names: Only include events from `Runnable` objects with matching names.
|
||||
include_types: Only include events from `Runnable` objects with matching types.
|
||||
include_tags: Only include events from `Runnable` objects with matching tags.
|
||||
@@ -1864,8 +1864,8 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
stop_after_attempt: The maximum number of attempts to make before
|
||||
giving up. Defaults to 3.
|
||||
exponential_jitter_params: Parameters for
|
||||
``tenacity.wait_exponential_jitter``. Namely: ``initial``, ``max``,
|
||||
``exp_base``, and ``jitter`` (all float values).
|
||||
`tenacity.wait_exponential_jitter`. Namely: `initial`, `max`,
|
||||
`exp_base`, and `jitter` (all float values).
|
||||
|
||||
Returns:
|
||||
A new Runnable that retries the original Runnable on exceptions.
|
||||
@@ -1950,7 +1950,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
fallbacks: A sequence of runnables to try if the original `Runnable`
|
||||
fails.
|
||||
exceptions_to_handle: A tuple of exception types to handle.
|
||||
Defaults to ``(Exception,)``.
|
||||
Defaults to `(Exception,)`.
|
||||
exception_key: If string is specified then handled exceptions will be passed
|
||||
to fallbacks as part of the input under the specified key.
|
||||
If `None`, exceptions will not be passed to fallbacks.
|
||||
@@ -2025,7 +2025,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
) -> Output:
|
||||
"""Call with config.
|
||||
|
||||
Helper method to transform an ``Input`` value to an ``Output`` value,
|
||||
Helper method to transform an `Input` value to an `Output` value,
|
||||
with callbacks.
|
||||
|
||||
Use this method to implement `invoke` in subclasses.
|
||||
@@ -2076,7 +2076,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
) -> Output:
|
||||
"""Async call with config.
|
||||
|
||||
Helper method to transform an ``Input`` value to an ``Output`` value,
|
||||
Helper method to transform an `Input` value to an `Output` value,
|
||||
with callbacks.
|
||||
|
||||
Use this method to implement `ainvoke` in subclasses.
|
||||
@@ -2123,7 +2123,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
) -> list[Output]:
|
||||
"""Transform a list of inputs to a list of outputs, with callbacks.
|
||||
|
||||
Helper method to transform an ``Input`` value to an ``Output`` value,
|
||||
Helper method to transform an `Input` value to an `Output` value,
|
||||
with callbacks. Use this method to implement `invoke` in subclasses.
|
||||
|
||||
"""
|
||||
@@ -2191,7 +2191,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
) -> list[Output]:
|
||||
"""Transform a list of inputs to a list of outputs, with callbacks.
|
||||
|
||||
Helper method to transform an ``Input`` value to an ``Output`` value,
|
||||
Helper method to transform an `Input` value to an `Output` value,
|
||||
with callbacks.
|
||||
|
||||
Use this method to implement `invoke` in subclasses.
|
||||
@@ -2261,10 +2261,10 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
) -> Iterator[Output]:
|
||||
"""Transform a stream with config.
|
||||
|
||||
Helper method to transform an ``Iterator`` of ``Input`` values into an
|
||||
``Iterator`` of ``Output`` values, with callbacks.
|
||||
Helper method to transform an `Iterator` of `Input` values into an
|
||||
`Iterator` of `Output` values, with callbacks.
|
||||
|
||||
Use this to implement `stream` or ``transform`` in `Runnable` subclasses.
|
||||
Use this to implement `stream` or `transform` in `Runnable` subclasses.
|
||||
|
||||
"""
|
||||
# tee the input so we can iterate over it twice
|
||||
@@ -2358,10 +2358,10 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
) -> AsyncIterator[Output]:
|
||||
"""Transform a stream with config.
|
||||
|
||||
Helper method to transform an Async ``Iterator`` of ``Input`` values into an
|
||||
Async ``Iterator`` of ``Output`` values, with callbacks.
|
||||
Helper method to transform an Async `Iterator` of `Input` values into an
|
||||
Async `Iterator` of `Output` values, with callbacks.
|
||||
|
||||
Use this to implement `astream` or ``atransform`` in `Runnable` subclasses.
|
||||
Use this to implement `astream` or `atransform` in `Runnable` subclasses.
|
||||
|
||||
"""
|
||||
# tee the input so we can iterate over it twice
|
||||
@@ -2454,12 +2454,12 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
) -> BaseTool:
|
||||
"""Create a `BaseTool` from a `Runnable`.
|
||||
|
||||
``as_tool`` will instantiate a `BaseTool` with a name, description, and
|
||||
``args_schema`` from a `Runnable`. Where possible, schemas are inferred
|
||||
from ``runnable.get_input_schema``. Alternatively (e.g., if the
|
||||
`as_tool` will instantiate a `BaseTool` with a name, description, and
|
||||
`args_schema` from a `Runnable`. Where possible, schemas are inferred
|
||||
from `runnable.get_input_schema`. Alternatively (e.g., if the
|
||||
`Runnable` takes a dict as input and the specific dict keys are not typed),
|
||||
the schema can be specified directly with ``args_schema``. You can also
|
||||
pass ``arg_types`` to just specify the required arguments and their types.
|
||||
the schema can be specified directly with `args_schema`. You can also
|
||||
pass `arg_types` to just specify the required arguments and their types.
|
||||
|
||||
Args:
|
||||
args_schema: The schema for the tool. Defaults to `None`.
|
||||
@@ -2491,7 +2491,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
as_tool.invoke({"a": 3, "b": [1, 2]})
|
||||
```
|
||||
|
||||
`dict` input, specifying schema via ``args_schema``:
|
||||
`dict` input, specifying schema via `args_schema`:
|
||||
|
||||
```python
|
||||
from typing import Any
|
||||
@@ -2512,7 +2512,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
as_tool.invoke({"a": 3, "b": [1, 2]})
|
||||
```
|
||||
|
||||
`dict` input, specifying schema via ``arg_types``:
|
||||
`dict` input, specifying schema via `arg_types`:
|
||||
|
||||
```python
|
||||
from typing import Any
|
||||
@@ -2592,7 +2592,7 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
|
||||
"""Configure particular `Runnable` fields at runtime.
|
||||
|
||||
Args:
|
||||
**kwargs: A dictionary of ``ConfigurableField`` instances to configure.
|
||||
**kwargs: A dictionary of `ConfigurableField` instances to configure.
|
||||
|
||||
Raises:
|
||||
ValueError: If a configuration key is not found in the `Runnable`.
|
||||
@@ -2651,11 +2651,11 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
|
||||
"""Configure alternatives for `Runnable` objects that can be set at runtime.
|
||||
|
||||
Args:
|
||||
which: The ``ConfigurableField`` instance that will be used to select the
|
||||
which: The `ConfigurableField` instance that will be used to select the
|
||||
alternative.
|
||||
default_key: The default key to use if no alternative is selected.
|
||||
Defaults to `'default'`.
|
||||
prefix_keys: Whether to prefix the keys with the ``ConfigurableField`` id.
|
||||
prefix_keys: Whether to prefix the keys with the `ConfigurableField` id.
|
||||
Defaults to `False`.
|
||||
**kwargs: A dictionary of keys to `Runnable` instances or callables that
|
||||
return `Runnable` instances.
|
||||
@@ -2789,7 +2789,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
|
||||
as it is used in virtually every chain.
|
||||
|
||||
A `RunnableSequence` can be instantiated directly or more commonly by using the
|
||||
``|`` operator where either the left or right operands (or both) must be a
|
||||
`|` operator where either the left or right operands (or both) must be a
|
||||
`Runnable`.
|
||||
|
||||
Any `RunnableSequence` automatically supports sync, async, batch.
|
||||
@@ -2802,7 +2802,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
|
||||
`RunnableSequence` in order.
|
||||
|
||||
A `RunnableSequence` preserves the streaming properties of its components, so if
|
||||
all components of the sequence implement a ``transform`` method -- which
|
||||
all components of the sequence implement a `transform` method -- which
|
||||
is the method that implements the logic to map a streaming input to a streaming
|
||||
output -- then the sequence will be able to stream input to output!
|
||||
|
||||
@@ -2811,12 +2811,12 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
|
||||
multiple blocking components, streaming begins after the last one.
|
||||
|
||||
!!! note
|
||||
``RunnableLambdas`` do not support ``transform`` by default! So if you need to
|
||||
use a ``RunnableLambdas`` be careful about where you place them in a
|
||||
`RunnableLambdas` do not support `transform` by default! So if you need to
|
||||
use a `RunnableLambdas` be careful about where you place them in a
|
||||
`RunnableSequence` (if you need to use the `stream`/`astream` methods).
|
||||
|
||||
If you need arbitrary logic and need streaming, you can subclass
|
||||
Runnable, and implement ``transform`` for whatever logic you need.
|
||||
Runnable, and implement `transform` for whatever logic you need.
|
||||
|
||||
Here is a simple example that uses simple functions to illustrate the use of
|
||||
`RunnableSequence`:
|
||||
@@ -2920,7 +2920,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "runnable"]``
|
||||
`["langchain", "schema", "runnable"]`
|
||||
"""
|
||||
return ["langchain", "schema", "runnable"]
|
||||
|
||||
@@ -3532,15 +3532,15 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
|
||||
|
||||
Returns a mapping of their outputs.
|
||||
|
||||
``RunnableParallel`` is one of the two main composition primitives for the LCEL,
|
||||
`RunnableParallel` is one of the two main composition primitives for the LCEL,
|
||||
alongside `RunnableSequence`. It invokes `Runnable`s concurrently, providing the
|
||||
same input to each.
|
||||
|
||||
A ``RunnableParallel`` can be instantiated directly or by using a dict literal
|
||||
A `RunnableParallel` can be instantiated directly or by using a dict literal
|
||||
within a sequence.
|
||||
|
||||
Here is a simple example that uses functions to illustrate the use of
|
||||
``RunnableParallel``:
|
||||
`RunnableParallel`:
|
||||
|
||||
```python
|
||||
from langchain_core.runnables import RunnableLambda
|
||||
@@ -3583,7 +3583,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
|
||||
await sequence.abatch([1, 2, 3])
|
||||
```
|
||||
|
||||
``RunnableParallel`` makes it easy to run `Runnable`s in parallel. In the below
|
||||
`RunnableParallel` makes it easy to run `Runnable`s in parallel. In the below
|
||||
example, we simultaneously stream output from two different `Runnable` objects:
|
||||
|
||||
```python
|
||||
@@ -3626,7 +3626,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
|
||||
| Callable[[Input], Any]
|
||||
| Mapping[str, Runnable[Input, Any] | Callable[[Input], Any]],
|
||||
) -> None:
|
||||
"""Create a ``RunnableParallel``.
|
||||
"""Create a `RunnableParallel`.
|
||||
|
||||
Args:
|
||||
steps__: The steps to include. Defaults to `None`.
|
||||
@@ -3651,7 +3651,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "runnable"]``
|
||||
`["langchain", "schema", "runnable"]`
|
||||
"""
|
||||
return ["langchain", "schema", "runnable"]
|
||||
|
||||
@@ -4055,22 +4055,22 @@ RunnableMap = RunnableParallel
|
||||
class RunnableGenerator(Runnable[Input, Output]):
|
||||
"""`Runnable` that runs a generator function.
|
||||
|
||||
``RunnableGenerator``s can be instantiated directly or by using a generator within
|
||||
`RunnableGenerator`s can be instantiated directly or by using a generator within
|
||||
a sequence.
|
||||
|
||||
``RunnableGenerator``s can be used to implement custom behavior, such as custom
|
||||
`RunnableGenerator`s can be used to implement custom behavior, such as custom
|
||||
output parsers, while preserving streaming capabilities. Given a generator function
|
||||
with a signature ``Iterator[A] -> Iterator[B]``, wrapping it in a
|
||||
``RunnableGenerator`` allows it to emit output chunks as soon as they are streamed
|
||||
with a signature `Iterator[A] -> Iterator[B]`, wrapping it in a
|
||||
`RunnableGenerator` allows it to emit output chunks as soon as they are streamed
|
||||
in from the previous step.
|
||||
|
||||
!!! note
|
||||
If a generator function has a ``signature A -> Iterator[B]``, such that it
|
||||
If a generator function has a `signature A -> Iterator[B]`, such that it
|
||||
requires its input from the previous step to be completed before emitting chunks
|
||||
(e.g., most LLMs need the entire prompt available to start generating), it can
|
||||
instead be wrapped in a ``RunnableLambda``.
|
||||
instead be wrapped in a `RunnableLambda`.
|
||||
|
||||
Here is an example to show the basic mechanics of a ``RunnableGenerator``:
|
||||
Here is an example to show the basic mechanics of a `RunnableGenerator`:
|
||||
|
||||
```python
|
||||
from typing import Any, AsyncIterator, Iterator
|
||||
@@ -4100,7 +4100,7 @@ class RunnableGenerator(Runnable[Input, Output]):
|
||||
[p async for p in runnable.astream(None)] # ["Have", " a", " nice", " day"]
|
||||
```
|
||||
|
||||
``RunnableGenerator`` makes it easy to implement custom behavior within a streaming
|
||||
`RunnableGenerator` makes it easy to implement custom behavior within a streaming
|
||||
context. Below we show an example:
|
||||
|
||||
```python
|
||||
@@ -4153,7 +4153,7 @@ class RunnableGenerator(Runnable[Input, Output]):
|
||||
*,
|
||||
name: str | None = None,
|
||||
) -> None:
|
||||
"""Initialize a ``RunnableGenerator``.
|
||||
"""Initialize a `RunnableGenerator`.
|
||||
|
||||
Args:
|
||||
transform: The transform function.
|
||||
@@ -4355,20 +4355,20 @@ class RunnableGenerator(Runnable[Input, Output]):
|
||||
|
||||
|
||||
class RunnableLambda(Runnable[Input, Output]):
|
||||
"""``RunnableLambda`` converts a python callable into a `Runnable`.
|
||||
"""`RunnableLambda` converts a python callable into a `Runnable`.
|
||||
|
||||
Wrapping a callable in a ``RunnableLambda`` makes the callable usable
|
||||
Wrapping a callable in a `RunnableLambda` makes the callable usable
|
||||
within either a sync or async context.
|
||||
|
||||
``RunnableLambda`` can be composed as any other `Runnable` and provides
|
||||
`RunnableLambda` can be composed as any other `Runnable` and provides
|
||||
seamless integration with LangChain tracing.
|
||||
|
||||
``RunnableLambda`` is best suited for code that does not need to support
|
||||
`RunnableLambda` is best suited for code that does not need to support
|
||||
streaming. If you need to support streaming (i.e., be able to operate
|
||||
on chunks of inputs and yield chunks of outputs), use ``RunnableGenerator``
|
||||
on chunks of inputs and yield chunks of outputs), use `RunnableGenerator`
|
||||
instead.
|
||||
|
||||
Note that if a ``RunnableLambda`` returns an instance of `Runnable`, that
|
||||
Note that if a `RunnableLambda` returns an instance of `Runnable`, that
|
||||
instance is invoked (or streamed) during execution.
|
||||
|
||||
Examples:
|
||||
@@ -4427,7 +4427,7 @@ class RunnableLambda(Runnable[Input, Output]):
|
||||
| None = None,
|
||||
name: str | None = None,
|
||||
) -> None:
|
||||
"""Create a ``RunnableLambda`` from a callable, and async callable or both.
|
||||
"""Create a `RunnableLambda` from a callable, and async callable or both.
|
||||
|
||||
Accepts both sync and async variants to allow providing efficient
|
||||
implementations for sync and async execution.
|
||||
@@ -4439,8 +4439,8 @@ class RunnableLambda(Runnable[Input, Output]):
|
||||
name: The name of the `Runnable`. Defaults to `None`.
|
||||
|
||||
Raises:
|
||||
TypeError: If the ``func`` is not a callable type.
|
||||
TypeError: If both ``func`` and ``afunc`` are provided.
|
||||
TypeError: If the `func` is not a callable type.
|
||||
TypeError: If both `func` and `afunc` are provided.
|
||||
|
||||
"""
|
||||
if afunc is not None:
|
||||
@@ -5100,10 +5100,10 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
|
||||
|
||||
`Runnable` that calls another `Runnable` for each element of the input sequence.
|
||||
|
||||
Use only if creating a new ``RunnableEach`` subclass with different `__init__`
|
||||
Use only if creating a new `RunnableEach` subclass with different `__init__`
|
||||
args.
|
||||
|
||||
See documentation for ``RunnableEach`` for more details.
|
||||
See documentation for `RunnableEach` for more details.
|
||||
|
||||
"""
|
||||
|
||||
@@ -5180,7 +5180,7 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "runnable"]``
|
||||
`["langchain", "schema", "runnable"]`
|
||||
"""
|
||||
return ["langchain", "schema", "runnable"]
|
||||
|
||||
@@ -5243,7 +5243,7 @@ class RunnableEach(RunnableEachBase[Input, Output]):
|
||||
|
||||
It allows you to call multiple inputs with the bounded `Runnable`.
|
||||
|
||||
``RunnableEach`` makes it easy to run multiple inputs for the `Runnable`.
|
||||
`RunnableEach` makes it easy to run multiple inputs for the `Runnable`.
|
||||
In the below example, we associate and run three inputs
|
||||
with a `Runnable`:
|
||||
|
||||
@@ -5356,10 +5356,10 @@ class RunnableEach(RunnableEachBase[Input, Output]):
|
||||
class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[no-redef]
|
||||
"""`Runnable` that delegates calls to another `Runnable` with a set of kwargs.
|
||||
|
||||
Use only if creating a new ``RunnableBinding`` subclass with different `__init__`
|
||||
Use only if creating a new `RunnableBinding` subclass with different `__init__`
|
||||
args.
|
||||
|
||||
See documentation for ``RunnableBinding`` for more details.
|
||||
See documentation for `RunnableBinding` for more details.
|
||||
|
||||
"""
|
||||
|
||||
@@ -5387,13 +5387,13 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[
|
||||
custom_input_type: Any | None = None
|
||||
"""Override the input type of the underlying `Runnable` with a custom type.
|
||||
|
||||
The type can be a pydantic model, or a type annotation (e.g., ``list[str]``).
|
||||
The type can be a pydantic model, or a type annotation (e.g., `list[str]`).
|
||||
"""
|
||||
# Union[Type[Output], BaseModel] + things like list[str]
|
||||
custom_output_type: Any | None = None
|
||||
"""Override the output type of the underlying `Runnable` with a custom type.
|
||||
|
||||
The type can be a pydantic model, or a type annotation (e.g., ``list[str]``).
|
||||
The type can be a pydantic model, or a type annotation (e.g., `list[str]`).
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(
|
||||
@@ -5412,14 +5412,14 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[
|
||||
custom_output_type: type[Output] | BaseModel | None = None,
|
||||
**other_kwargs: Any,
|
||||
) -> None:
|
||||
"""Create a ``RunnableBinding`` from a `Runnable` and kwargs.
|
||||
"""Create a `RunnableBinding` from a `Runnable` and kwargs.
|
||||
|
||||
Args:
|
||||
bound: The underlying `Runnable` that this `Runnable` delegates calls
|
||||
to.
|
||||
kwargs: optional kwargs to pass to the underlying `Runnable`, when running
|
||||
the underlying `Runnable` (e.g., via `invoke`, `batch`,
|
||||
``transform``, or `stream` or async variants)
|
||||
`transform`, or `stream` or async variants)
|
||||
Defaults to `None`.
|
||||
config: optional config to bind to the underlying `Runnable`.
|
||||
Defaults to `None`.
|
||||
@@ -5503,7 +5503,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "runnable"]``
|
||||
`["langchain", "schema", "runnable"]`
|
||||
"""
|
||||
return ["langchain", "schema", "runnable"]
|
||||
|
||||
@@ -5758,25 +5758,25 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[
|
||||
class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-redef]
|
||||
"""Wrap a `Runnable` with additional functionality.
|
||||
|
||||
A ``RunnableBinding`` can be thought of as a "runnable decorator" that
|
||||
A `RunnableBinding` can be thought of as a "runnable decorator" that
|
||||
preserves the essential features of `Runnable`; i.e., batching, streaming,
|
||||
and async support, while adding additional functionality.
|
||||
|
||||
Any class that inherits from `Runnable` can be bound to a ``RunnableBinding``.
|
||||
Runnables expose a standard set of methods for creating ``RunnableBindings``
|
||||
or sub-classes of ``RunnableBindings`` (e.g., ``RunnableRetry``,
|
||||
``RunnableWithFallbacks``) that add additional functionality.
|
||||
Any class that inherits from `Runnable` can be bound to a `RunnableBinding`.
|
||||
Runnables expose a standard set of methods for creating `RunnableBindings`
|
||||
or sub-classes of `RunnableBindings` (e.g., `RunnableRetry`,
|
||||
`RunnableWithFallbacks`) that add additional functionality.
|
||||
|
||||
These methods include:
|
||||
|
||||
- ``bind``: Bind kwargs to pass to the underlying `Runnable` when running it.
|
||||
- ``with_config``: Bind config to pass to the underlying `Runnable` when running
|
||||
it.
|
||||
- ``with_listeners``: Bind lifecycle listeners to the underlying `Runnable`.
|
||||
- ``with_types``: Override the input and output types of the underlying
|
||||
`Runnable`.
|
||||
- ``with_retry``: Bind a retry policy to the underlying `Runnable`.
|
||||
- ``with_fallbacks``: Bind a fallback policy to the underlying `Runnable`.
|
||||
- `bind`: Bind kwargs to pass to the underlying `Runnable` when running it.
|
||||
- `with_config`: Bind config to pass to the underlying `Runnable` when running
|
||||
it.
|
||||
- `with_listeners`: Bind lifecycle listeners to the underlying `Runnable`.
|
||||
- `with_types`: Override the input and output types of the underlying
|
||||
`Runnable`.
|
||||
- `with_retry`: Bind a retry policy to the underlying `Runnable`.
|
||||
- `with_fallbacks`: Bind a fallback policy to the underlying `Runnable`.
|
||||
|
||||
Example:
|
||||
`bind`: Bind kwargs to pass to the underlying `Runnable` when running it.
|
||||
@@ -5793,7 +5793,7 @@ class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-re
|
||||
runnable_binding = model.bind(stop=["-"])
|
||||
runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
|
||||
```
|
||||
Can also be done by instantiating a ``RunnableBinding`` directly (not
|
||||
Can also be done by instantiating a `RunnableBinding` directly (not
|
||||
recommended):
|
||||
|
||||
```python
|
||||
@@ -6062,7 +6062,7 @@ def chain(
|
||||
Any runnables called by the function will be traced as dependencies.
|
||||
|
||||
Args:
|
||||
func: A ``Callable``.
|
||||
func: A `Callable`.
|
||||
|
||||
Returns:
|
||||
A `Runnable`.
|
||||
|
||||
@@ -149,7 +149,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "runnable"]``
|
||||
`["langchain", "schema", "runnable"]`
|
||||
"""
|
||||
return ["langchain", "schema", "runnable"]
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "runnable"]``
|
||||
`["langchain", "schema", "runnable"]`
|
||||
"""
|
||||
return ["langchain", "schema", "runnable"]
|
||||
|
||||
|
||||
@@ -47,8 +47,8 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
|
||||
of a chain of Runnables. Fallbacks are tried in order until one succeeds or
|
||||
all fail.
|
||||
|
||||
While you can instantiate a ``RunnableWithFallbacks`` directly, it is usually
|
||||
more convenient to use the ``with_fallbacks`` method on a Runnable.
|
||||
While you can instantiate a `RunnableWithFallbacks` directly, it is usually
|
||||
more convenient to use the `with_fallbacks` method on a Runnable.
|
||||
|
||||
Example:
|
||||
```python
|
||||
@@ -146,7 +146,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "runnable"]``
|
||||
`["langchain", "schema", "runnable"]`
|
||||
"""
|
||||
return ["langchain", "schema", "runnable"]
|
||||
|
||||
|
||||
@@ -62,8 +62,8 @@ class AsciiCanvas:
|
||||
"""Create an ASCII canvas.
|
||||
|
||||
Args:
|
||||
cols: number of columns in the canvas. Should be ``> 1``.
|
||||
lines: number of lines in the canvas. Should be ``> 1``.
|
||||
cols: number of columns in the canvas. Should be `> 1`.
|
||||
lines: number of lines in the canvas. Should be `> 1`.
|
||||
|
||||
Raises:
|
||||
ValueError: if canvas dimensions are invalid.
|
||||
@@ -90,9 +90,9 @@ class AsciiCanvas:
|
||||
"""Create a point on ASCII canvas.
|
||||
|
||||
Args:
|
||||
x: x coordinate. Should be ``>= 0`` and ``<`` number of columns in
|
||||
x: x coordinate. Should be `>= 0` and `<` number of columns in
|
||||
the canvas.
|
||||
y: y coordinate. Should be ``>= 0`` an ``<`` number of lines in the
|
||||
y: y coordinate. Should be `>= 0` an `<` number of lines in the
|
||||
canvas.
|
||||
char: character to place in the specified point on the
|
||||
canvas.
|
||||
|
||||
@@ -15,7 +15,7 @@ except ImportError:
|
||||
class PngDrawer:
|
||||
"""Helper class to draw a state graph into a PNG file.
|
||||
|
||||
It requires ``graphviz`` and ``pygraphviz`` to be installed.
|
||||
It requires `graphviz` and `pygraphviz` to be installed.
|
||||
|
||||
Example:
|
||||
```python
|
||||
@@ -126,10 +126,10 @@ class PngDrawer:
|
||||
output_path: The path to save the PNG. If `None`, PNG bytes are returned.
|
||||
|
||||
Raises:
|
||||
ImportError: If ``pygraphviz`` is not installed.
|
||||
ImportError: If `pygraphviz` is not installed.
|
||||
|
||||
Returns:
|
||||
The PNG bytes if ``output_path`` is None, else None.
|
||||
The PNG bytes if `output_path` is None, else None.
|
||||
"""
|
||||
if not _HAS_PYGRAPHVIZ:
|
||||
msg = "Install pygraphviz to draw graphs: `pip install pygraphviz`."
|
||||
|
||||
@@ -57,17 +57,17 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
|
||||
In this case, the invocation would look like this:
|
||||
|
||||
`with_history.invoke(..., config={"configurable": {"session_id": "bar"}})`
|
||||
; e.g., ``{"configurable": {"session_id": "<SESSION_ID>"}}``.
|
||||
; e.g., `{"configurable": {"session_id": "<SESSION_ID>"}}`.
|
||||
|
||||
The configuration can be customized by passing in a list of
|
||||
``ConfigurableFieldSpec`` objects to the ``history_factory_config`` parameter (see
|
||||
`ConfigurableFieldSpec` objects to the `history_factory_config` parameter (see
|
||||
example below).
|
||||
|
||||
In the examples, we will use a chat message history with an in-memory
|
||||
implementation to make it easy to experiment and see the results.
|
||||
|
||||
For production use cases, you will want to use a persistent implementation
|
||||
of chat message history, such as ``RedisChatMessageHistory``.
|
||||
of chat message history, such as `RedisChatMessageHistory`.
|
||||
|
||||
Example: Chat message history with an in-memory implementation for testing.
|
||||
|
||||
@@ -224,7 +224,7 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
|
||||
|
||||
get_session_history: GetSessionHistoryCallable
|
||||
"""Function that returns a new BaseChatMessageHistory.
|
||||
This function should either take a single positional argument ``session_id`` of type
|
||||
This function should either take a single positional argument `session_id` of type
|
||||
string and return a corresponding chat message history instance"""
|
||||
input_messages_key: str | None = None
|
||||
"""Must be specified if the base runnable accepts a dict as input.
|
||||
@@ -237,7 +237,7 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
|
||||
separate key for historical messages."""
|
||||
history_factory_config: Sequence[ConfigurableFieldSpec]
|
||||
"""Configure fields that should be passed to the chat history factory.
|
||||
See ``ConfigurableFieldSpec`` for more details."""
|
||||
See `ConfigurableFieldSpec` for more details."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -263,8 +263,8 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
|
||||
1. A list of `BaseMessage`
|
||||
2. A dict with one key for all messages
|
||||
3. A dict with one key for the current input string/message(s) and
|
||||
a separate key for historical messages. If the input key points
|
||||
to a string, it will be treated as a `HumanMessage` in history.
|
||||
a separate key for historical messages. If the input key points
|
||||
to a string, it will be treated as a `HumanMessage` in history.
|
||||
|
||||
Must return as output one of:
|
||||
|
||||
@@ -302,11 +302,11 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
|
||||
history_messages_key: Must be specified if the base runnable accepts a dict
|
||||
as input and expects a separate key for historical messages.
|
||||
history_factory_config: Configure fields that should be passed to the
|
||||
chat history factory. See ``ConfigurableFieldSpec`` for more details.
|
||||
chat history factory. See `ConfigurableFieldSpec` for more details.
|
||||
Specifying these allows you to pass multiple config keys
|
||||
into the get_session_history factory.
|
||||
**kwargs: Arbitrary additional kwargs to pass to parent class
|
||||
``RunnableBindingBase`` init.
|
||||
`RunnableBindingBase` init.
|
||||
|
||||
"""
|
||||
history_chain: Runnable = RunnableLambda(
|
||||
|
||||
@@ -188,7 +188,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "runnable"]``
|
||||
`["langchain", "schema", "runnable"]`
|
||||
"""
|
||||
return ["langchain", "schema", "runnable"]
|
||||
|
||||
@@ -395,7 +395,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
|
||||
"""Create a RunnableAssign.
|
||||
|
||||
Args:
|
||||
mapper: A ``RunnableParallel`` instance that will be used to transform the
|
||||
mapper: A `RunnableParallel` instance that will be used to transform the
|
||||
input dictionary.
|
||||
"""
|
||||
super().__init__(mapper=mapper, **kwargs)
|
||||
@@ -412,7 +412,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "runnable"]``
|
||||
`["langchain", "schema", "runnable"]`
|
||||
"""
|
||||
return ["langchain", "schema", "runnable"]
|
||||
|
||||
@@ -717,7 +717,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "runnable"]``
|
||||
`["langchain", "schema", "runnable"]`
|
||||
"""
|
||||
return ["langchain", "schema", "runnable"]
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ U = TypeVar("U")
|
||||
|
||||
|
||||
class ExponentialJitterParams(TypedDict, total=False):
|
||||
"""Parameters for ``tenacity.wait_exponential_jitter``."""
|
||||
"""Parameters for `tenacity.wait_exponential_jitter`."""
|
||||
|
||||
initial: float
|
||||
"""Initial wait."""
|
||||
@@ -125,8 +125,8 @@ class RunnableRetry(RunnableBindingBase[Input, Output]): # type: ignore[no-rede
|
||||
"""Whether to add jitter to the exponential backoff."""
|
||||
|
||||
exponential_jitter_params: ExponentialJitterParams | None = None
|
||||
"""Parameters for ``tenacity.wait_exponential_jitter``. Namely: ``initial``,
|
||||
``max``, ``exp_base``, and ``jitter`` (all float values).
|
||||
"""Parameters for `tenacity.wait_exponential_jitter`. Namely: `initial`,
|
||||
`max`, `exp_base`, and `jitter` (all float values).
|
||||
"""
|
||||
|
||||
max_attempt_number: int = 3
|
||||
|
||||
@@ -99,7 +99,7 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
|
||||
"""Get the namespace of the langchain object.
|
||||
|
||||
Returns:
|
||||
``["langchain", "schema", "runnable"]``
|
||||
`["langchain", "schema", "runnable"]`
|
||||
"""
|
||||
return ["langchain", "schema", "runnable"]
|
||||
|
||||
|
||||
@@ -120,10 +120,10 @@ def accepts_context(callable: Callable[..., Any]) -> bool: # noqa: A002
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def asyncio_accepts_context() -> bool:
|
||||
"""Cache the result of checking if asyncio.create_task accepts a ``context`` arg.
|
||||
"""Cache the result of checking if asyncio.create_task accepts a `context` arg.
|
||||
|
||||
Returns:
|
||||
True if ``asyncio.create_task`` accepts a context argument, False otherwise.
|
||||
True if `asyncio.create_task` accepts a context argument, False otherwise.
|
||||
"""
|
||||
return accepts_context(asyncio.create_task)
|
||||
|
||||
|
||||
@@ -294,7 +294,7 @@ def create_schema_from_function(
|
||||
Defaults to FILTERED_ARGS.
|
||||
parse_docstring: Whether to parse the function's docstring for descriptions
|
||||
for each argument. Defaults to `False`.
|
||||
error_on_invalid_docstring: if ``parse_docstring`` is provided, configure
|
||||
error_on_invalid_docstring: if `parse_docstring` is provided, configure
|
||||
whether to raise ValueError on invalid Google Style docstrings.
|
||||
Defaults to `False`.
|
||||
include_injected: Whether to include injected arguments in the schema.
|
||||
@@ -492,7 +492,7 @@ class ChildTool(BaseTool):
|
||||
"""Initialize the tool.
|
||||
|
||||
Raises:
|
||||
TypeError: If ``args_schema`` is not a subclass of pydantic `BaseModel` or
|
||||
TypeError: If `args_schema` is not a subclass of pydantic `BaseModel` or
|
||||
dict.
|
||||
"""
|
||||
if (
|
||||
@@ -616,7 +616,7 @@ class ChildTool(BaseTool):
|
||||
The parsed and validated input.
|
||||
|
||||
Raises:
|
||||
ValueError: If string input is provided with JSON schema ``args_schema``.
|
||||
ValueError: If string input is provided with JSON schema `args_schema`.
|
||||
ValueError: If InjectedToolCallId is required but `tool_call_id` is not
|
||||
provided.
|
||||
TypeError: If args_schema is not a Pydantic `BaseModel` or dict.
|
||||
|
||||
@@ -91,11 +91,11 @@ def tool(
|
||||
description: Optional description for the tool.
|
||||
Precedence for the tool description value is as follows:
|
||||
|
||||
- ``description`` argument
|
||||
(used even if docstring and/or ``args_schema`` are provided)
|
||||
- `description` argument
|
||||
(used even if docstring and/or `args_schema` are provided)
|
||||
- tool function docstring
|
||||
(used even if ``args_schema`` is provided)
|
||||
- ``args_schema`` description
|
||||
(used even if `args_schema` is provided)
|
||||
- `args_schema` description
|
||||
(used only if `description` / docstring are not provided)
|
||||
*args: Extra positional arguments. Must be empty.
|
||||
return_direct: Whether to return directly from the tool rather
|
||||
@@ -111,10 +111,10 @@ def tool(
|
||||
"content_and_artifact" then the output is expected to be a two-tuple
|
||||
corresponding to the (content, artifact) of a ToolMessage.
|
||||
Defaults to "content".
|
||||
parse_docstring: if ``infer_schema`` and ``parse_docstring``, will attempt to
|
||||
parse_docstring: if `infer_schema` and `parse_docstring`, will attempt to
|
||||
parse parameter descriptions from Google Style function docstrings.
|
||||
Defaults to `False`.
|
||||
error_on_invalid_docstring: if ``parse_docstring`` is provided, configure
|
||||
error_on_invalid_docstring: if `parse_docstring` is provided, configure
|
||||
whether to raise ValueError on invalid Google Style docstrings.
|
||||
Defaults to `True`.
|
||||
|
||||
@@ -122,11 +122,11 @@ def tool(
|
||||
ValueError: If too many positional arguments are provided.
|
||||
ValueError: If a runnable is provided without a string name.
|
||||
ValueError: If the first argument is not a string or callable with
|
||||
a ``__name__`` attribute.
|
||||
a `__name__` attribute.
|
||||
ValueError: If the function does not have a docstring and description
|
||||
is not provided and ``infer_schema`` is False.
|
||||
ValueError: If ``parse_docstring`` is True and the function has an invalid
|
||||
Google-style docstring and ``error_on_invalid_docstring`` is True.
|
||||
is not provided and `infer_schema` is False.
|
||||
ValueError: If `parse_docstring` is True and the function has an invalid
|
||||
Google-style docstring and `error_on_invalid_docstring` is True.
|
||||
ValueError: If a Runnable is provided that does not have an object schema.
|
||||
|
||||
Returns:
|
||||
@@ -194,7 +194,7 @@ def tool(
|
||||
"required": ["bar", "baz"],
|
||||
}
|
||||
|
||||
Note that parsing by default will raise ``ValueError`` if the docstring
|
||||
Note that parsing by default will raise `ValueError` if the docstring
|
||||
is considered invalid. A docstring is considered invalid if it contains
|
||||
arguments not in the function signature, or is unable to be parsed into
|
||||
a summary and "Args:" blocks. Examples below:
|
||||
|
||||
@@ -158,10 +158,10 @@ class StructuredTool(BaseTool):
|
||||
"content_and_artifact" then the output is expected to be a two-tuple
|
||||
corresponding to the (content, artifact) of a ToolMessage.
|
||||
Defaults to "content".
|
||||
parse_docstring: if ``infer_schema`` and ``parse_docstring``, will attempt
|
||||
parse_docstring: if `infer_schema` and `parse_docstring`, will attempt
|
||||
to parse parameter descriptions from Google Style function docstrings.
|
||||
Defaults to `False`.
|
||||
error_on_invalid_docstring: if ``parse_docstring`` is provided, configure
|
||||
error_on_invalid_docstring: if `parse_docstring` is provided, configure
|
||||
whether to raise ValueError on invalid Google Style docstrings.
|
||||
Defaults to `False`.
|
||||
**kwargs: Additional arguments to pass to the tool
|
||||
@@ -173,7 +173,7 @@ class StructuredTool(BaseTool):
|
||||
ValueError: If the function is not provided.
|
||||
ValueError: If the function does not have a docstring and description
|
||||
is not provided.
|
||||
TypeError: If the ``args_schema`` is not a `BaseModel` or dict.
|
||||
TypeError: If the `args_schema` is not a `BaseModel` or dict.
|
||||
|
||||
Examples:
|
||||
|
||||
|
||||
@@ -473,7 +473,7 @@ class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHand
|
||||
For both chat models and non-chat models (legacy LLMs).
|
||||
|
||||
Raises:
|
||||
ValueError: If the run type is not ``'llm'`` or ``'chat_model'``.
|
||||
ValueError: If the run type is not `'llm'` or `'chat_model'`.
|
||||
"""
|
||||
run_info = self.run_map.pop(run_id)
|
||||
inputs_ = run_info.get("inputs")
|
||||
|
||||
@@ -111,16 +111,16 @@ class RunLogPatch:
|
||||
self.ops = list(ops)
|
||||
|
||||
def __add__(self, other: RunLogPatch | Any) -> RunLog:
|
||||
"""Combine two ``RunLogPatch`` instances.
|
||||
"""Combine two `RunLogPatch` instances.
|
||||
|
||||
Args:
|
||||
other: The other ``RunLogPatch`` to combine with.
|
||||
other: The other `RunLogPatch` to combine with.
|
||||
|
||||
Raises:
|
||||
TypeError: If the other object is not a ``RunLogPatch``.
|
||||
TypeError: If the other object is not a `RunLogPatch`.
|
||||
|
||||
Returns:
|
||||
A new ``RunLog`` representing the combination of the two.
|
||||
A new `RunLog` representing the combination of the two.
|
||||
"""
|
||||
if type(other) is RunLogPatch:
|
||||
ops = self.ops + other.ops
|
||||
@@ -159,16 +159,16 @@ class RunLog(RunLogPatch):
|
||||
self.state = state
|
||||
|
||||
def __add__(self, other: RunLogPatch | Any) -> RunLog:
|
||||
"""Combine two ``RunLog``s.
|
||||
"""Combine two `RunLog`s.
|
||||
|
||||
Args:
|
||||
other: The other ``RunLog`` or ``RunLogPatch`` to combine with.
|
||||
other: The other `RunLog` or `RunLogPatch` to combine with.
|
||||
|
||||
Raises:
|
||||
TypeError: If the other object is not a ``RunLog`` or ``RunLogPatch``.
|
||||
TypeError: If the other object is not a `RunLog` or `RunLogPatch`.
|
||||
|
||||
Returns:
|
||||
A new ``RunLog`` representing the combination of the two.
|
||||
A new `RunLog` representing the combination of the two.
|
||||
"""
|
||||
if type(other) is RunLogPatch:
|
||||
ops = self.ops + other.ops
|
||||
@@ -184,13 +184,13 @@ class RunLog(RunLogPatch):
|
||||
|
||||
@override
|
||||
def __eq__(self, other: object) -> bool:
|
||||
"""Check if two ``RunLog``s are equal.
|
||||
"""Check if two `RunLog`s are equal.
|
||||
|
||||
Args:
|
||||
other: The other ``RunLog`` to compare to.
|
||||
other: The other `RunLog` to compare to.
|
||||
|
||||
Returns:
|
||||
True if the ``RunLog``s are equal, False otherwise.
|
||||
True if the `RunLog`s are equal, False otherwise.
|
||||
"""
|
||||
# First compare that the state is the same
|
||||
if not isinstance(other, RunLog):
|
||||
@@ -666,7 +666,7 @@ async def _astream_log_implementation(
|
||||
ValueError: If the callbacks in the config are of an unexpected type.
|
||||
|
||||
Yields:
|
||||
The run log patches or states, depending on the value of ``diff``.
|
||||
The run log patches or states, depending on the value of `diff`.
|
||||
"""
|
||||
# Assign the stream handler to the config
|
||||
config = ensure_config(config)
|
||||
|
||||
@@ -18,10 +18,10 @@ from langchain_core._api import deprecated
|
||||
|
||||
@deprecated("0.1.0", alternative="Use string instead.", removal="1.0")
|
||||
def RunTypeEnum() -> type[RunTypeEnumDep]: # noqa: N802
|
||||
"""``RunTypeEnum``.
|
||||
"""`RunTypeEnum`.
|
||||
|
||||
Returns:
|
||||
The ``RunTypeEnum`` class.
|
||||
The `RunTypeEnum` class.
|
||||
"""
|
||||
warnings.warn(
|
||||
"RunTypeEnum is deprecated. Please directly use a string instead"
|
||||
|
||||
@@ -107,7 +107,7 @@ async def tee_peer(
|
||||
"""An individual iterator of a `tee`.
|
||||
|
||||
This function is a generator that yields items from the shared iterator
|
||||
``iterator``. It buffers items until the least advanced iterator has
|
||||
`iterator`. It buffers items until the least advanced iterator has
|
||||
yielded them as well. The buffer is shared with all other peers.
|
||||
|
||||
Args:
|
||||
@@ -153,14 +153,14 @@ async def tee_peer(
|
||||
|
||||
|
||||
class Tee(Generic[T]):
|
||||
"""Create ``n`` separate asynchronous iterators over ``iterable``.
|
||||
"""Create `n` separate asynchronous iterators over `iterable`.
|
||||
|
||||
This splits a single ``iterable`` into multiple iterators, each providing
|
||||
This splits a single `iterable` into multiple iterators, each providing
|
||||
the same items in the same order.
|
||||
All child iterators may advance separately but share the same items
|
||||
from ``iterable`` -- when the most advanced iterator retrieves an item,
|
||||
from `iterable` -- when the most advanced iterator retrieves an item,
|
||||
it is buffered until the least advanced iterator has yielded it as well.
|
||||
A ``tee`` works lazily and can handle an infinite ``iterable``, provided
|
||||
A `tee` works lazily and can handle an infinite `iterable`, provided
|
||||
that all iterators advance.
|
||||
|
||||
.. code-block:: python
|
||||
@@ -173,18 +173,18 @@ class Tee(Generic[T]):
|
||||
Unlike `itertools.tee`, `.tee` returns a custom type instead
|
||||
of a :py`tuple`. Like a tuple, it can be indexed, iterated and unpacked
|
||||
to get the child iterators. In addition, its `.tee.aclose` method
|
||||
immediately closes all children, and it can be used in an ``async with`` context
|
||||
immediately closes all children, and it can be used in an `async with` context
|
||||
for the same effect.
|
||||
|
||||
If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*
|
||||
provide these items. Also, ``tee`` must internally buffer each item until the
|
||||
If `iterable` is an iterator and read elsewhere, `tee` will *not*
|
||||
provide these items. Also, `tee` must internally buffer each item until the
|
||||
last iterator has yielded it; if the most and least advanced iterator differ
|
||||
by most data, using a :py`list` is more efficient (but not lazy).
|
||||
|
||||
If the underlying iterable is concurrency safe (``anext`` may be awaited
|
||||
If the underlying iterable is concurrency safe (`anext` may be awaited
|
||||
concurrently) the resulting iterators are concurrency safe as well. Otherwise,
|
||||
the iterators are safe if there is only ever one single "most advanced" iterator.
|
||||
To enforce sequential use of ``anext``, provide a ``lock``
|
||||
To enforce sequential use of `anext`, provide a `lock`
|
||||
- e.g. an :py`asyncio.Lock` instance in an :py:mod:`asyncio` application -
|
||||
and access is automatically synchronised.
|
||||
|
||||
@@ -197,7 +197,7 @@ class Tee(Generic[T]):
|
||||
*,
|
||||
lock: AbstractAsyncContextManager[Any] | None = None,
|
||||
):
|
||||
"""Create a ``tee``.
|
||||
"""Create a `tee`.
|
||||
|
||||
Args:
|
||||
iterable: The iterable to split.
|
||||
@@ -269,7 +269,7 @@ atee = Tee
|
||||
|
||||
|
||||
class aclosing(AbstractAsyncContextManager): # noqa: N801
|
||||
"""Async context manager to wrap an AsyncGenerator that has a ``aclose()`` method.
|
||||
"""Async context manager to wrap an AsyncGenerator that has a `aclose()` method.
|
||||
|
||||
Code like this:
|
||||
|
||||
|
||||
@@ -409,7 +409,7 @@ def convert_to_openai_function(
|
||||
tool, or an Amazon Bedrock Converse format tool.
|
||||
strict:
|
||||
If `True`, model output is guaranteed to exactly match the JSON Schema
|
||||
provided in the function definition. If `None`, ``strict`` argument will not
|
||||
provided in the function definition. If `None`, `strict` argument will not
|
||||
be included in function definition.
|
||||
|
||||
Returns:
|
||||
@@ -420,7 +420,7 @@ def convert_to_openai_function(
|
||||
ValueError: If function is not in a supported format.
|
||||
|
||||
!!! warning "Behavior changed in 0.2.29"
|
||||
``strict`` arg added.
|
||||
`strict` arg added.
|
||||
|
||||
!!! warning "Behavior changed in 0.3.13"
|
||||
Support for Anthropic format tools added.
|
||||
@@ -539,7 +539,7 @@ def convert_to_openai_tool(
|
||||
tool, or an Amazon Bedrock Converse format tool.
|
||||
strict:
|
||||
If `True`, model output is guaranteed to exactly match the JSON Schema
|
||||
provided in the function definition. If `None`, ``strict`` argument will not
|
||||
provided in the function definition. If `None`, `strict` argument will not
|
||||
be included in tool definition.
|
||||
|
||||
Returns:
|
||||
@@ -547,7 +547,7 @@ def convert_to_openai_tool(
|
||||
OpenAI tool-calling API.
|
||||
|
||||
!!! warning "Behavior changed in 0.2.29"
|
||||
``strict`` arg added.
|
||||
`strict` arg added.
|
||||
|
||||
!!! warning "Behavior changed in 0.3.13"
|
||||
Support for Anthropic format tools added.
|
||||
@@ -602,7 +602,7 @@ def convert_to_json_schema(
|
||||
Args:
|
||||
schema: The schema to convert.
|
||||
strict: If `True`, model output is guaranteed to exactly match the JSON Schema
|
||||
provided in the function definition. If `None`, ``strict`` argument will not
|
||||
provided in the function definition. If `None`, `strict` argument will not
|
||||
be included in function definition.
|
||||
|
||||
Raises:
|
||||
@@ -652,9 +652,9 @@ def tool_example_to_messages(
|
||||
1. `HumanMessage`: contains the content from which content should be extracted.
|
||||
2. `AIMessage`: contains the extracted information from the model
|
||||
3. `ToolMessage`: contains confirmation to the model that the model requested a
|
||||
tool correctly.
|
||||
tool correctly.
|
||||
|
||||
If ``ai_response`` is specified, there will be a final `AIMessage` with that
|
||||
If `ai_response` is specified, there will be a final `AIMessage` with that
|
||||
response.
|
||||
|
||||
The `ToolMessage` is required because some chat models are hyper-optimized for
|
||||
|
||||
@@ -43,7 +43,7 @@ def tee_peer(
|
||||
"""An individual iterator of a `.tee`.
|
||||
|
||||
This function is a generator that yields items from the shared iterator
|
||||
``iterator``. It buffers items until the least advanced iterator has
|
||||
`iterator`. It buffers items until the least advanced iterator has
|
||||
yielded them as well. The buffer is shared with all other peers.
|
||||
|
||||
Args:
|
||||
@@ -89,14 +89,14 @@ def tee_peer(
|
||||
|
||||
|
||||
class Tee(Generic[T]):
|
||||
"""Create ``n`` separate asynchronous iterators over ``iterable``.
|
||||
"""Create `n` separate asynchronous iterators over `iterable`.
|
||||
|
||||
This splits a single ``iterable`` into multiple iterators, each providing
|
||||
This splits a single `iterable` into multiple iterators, each providing
|
||||
the same items in the same order.
|
||||
All child iterators may advance separately but share the same items
|
||||
from ``iterable`` -- when the most advanced iterator retrieves an item,
|
||||
from `iterable` -- when the most advanced iterator retrieves an item,
|
||||
it is buffered until the least advanced iterator has yielded it as well.
|
||||
A ``tee`` works lazily and can handle an infinite ``iterable``, provided
|
||||
A `tee` works lazily and can handle an infinite `iterable`, provided
|
||||
that all iterators advance.
|
||||
|
||||
.. code-block:: python
|
||||
@@ -109,18 +109,18 @@ class Tee(Generic[T]):
|
||||
Unlike `itertools.tee`, `.tee` returns a custom type instead
|
||||
of a :py`tuple`. Like a tuple, it can be indexed, iterated and unpacked
|
||||
to get the child iterators. In addition, its `.tee.aclose` method
|
||||
immediately closes all children, and it can be used in an ``async with`` context
|
||||
immediately closes all children, and it can be used in an `async with` context
|
||||
for the same effect.
|
||||
|
||||
If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*
|
||||
provide these items. Also, ``tee`` must internally buffer each item until the
|
||||
If `iterable` is an iterator and read elsewhere, `tee` will *not*
|
||||
provide these items. Also, `tee` must internally buffer each item until the
|
||||
last iterator has yielded it; if the most and least advanced iterator differ
|
||||
by most data, using a :py`list` is more efficient (but not lazy).
|
||||
|
||||
If the underlying iterable is concurrency safe (``anext`` may be awaited
|
||||
If the underlying iterable is concurrency safe (`anext` may be awaited
|
||||
concurrently) the resulting iterators are concurrency safe as well. Otherwise,
|
||||
the iterators are safe if there is only ever one single "most advanced" iterator.
|
||||
To enforce sequential use of ``anext``, provide a ``lock``
|
||||
To enforce sequential use of `anext`, provide a `lock`
|
||||
- e.g. an :py`asyncio.Lock` instance in an :py:mod:`asyncio` application -
|
||||
and access is automatically synchronised.
|
||||
|
||||
@@ -133,7 +133,7 @@ class Tee(Generic[T]):
|
||||
*,
|
||||
lock: AbstractContextManager[Any] | None = None,
|
||||
):
|
||||
"""Create a ``tee``.
|
||||
"""Create a `tee`.
|
||||
|
||||
Args:
|
||||
iterable: The iterable to split.
|
||||
|
||||
@@ -329,7 +329,7 @@ def tokenize(
|
||||
|
||||
|
||||
def _html_escape(string: str) -> str:
|
||||
"""Return the HTML-escaped string with these characters escaped: ``" & < >``."""
|
||||
"""Return the HTML-escaped string with these characters escaped: `" & < >`."""
|
||||
html_codes = {
|
||||
'"': """,
|
||||
"<": "<",
|
||||
|
||||
@@ -499,7 +499,7 @@ Used for:
|
||||
def ensure_id(id_val: str | None) -> str:
|
||||
"""Ensure the ID is a valid string, generating a new UUID if not provided.
|
||||
|
||||
Auto-generated UUIDs are prefixed by ``'lc_'`` to indicate they are
|
||||
Auto-generated UUIDs are prefixed by `'lc_'` to indicate they are
|
||||
LangChain-generated IDs.
|
||||
|
||||
Args:
|
||||
|
||||
@@ -11,7 +11,7 @@ def test_all_providers_registered() -> None:
|
||||
|
||||
If this test fails, it is likely that a block translator is implemented but not
|
||||
registered on import. Check that the provider is included in
|
||||
``langchain_core.messages.block_translators.__init__._register_translators``.
|
||||
`langchain_core.messages.block_translators.__init__._register_translators`.
|
||||
"""
|
||||
package_path = (
|
||||
Path(__file__).parents[4] / "langchain_core" / "messages" / "block_translators"
|
||||
@@ -20,7 +20,7 @@ def test_all_providers_registered() -> None:
|
||||
for module_info in pkgutil.iter_modules([str(package_path)]):
|
||||
module_name = module_info.name
|
||||
|
||||
# Skip the __init__ module, any private modules, and ``langchain_v0``, which is
|
||||
# Skip the __init__ module, any private modules, and `langchain_v0`, which is
|
||||
# only used to parse v0 multimodal inputs.
|
||||
if module_name.startswith("_") or module_name == "langchain_v0":
|
||||
continue
|
||||
|
||||
@@ -385,7 +385,7 @@
|
||||
'description': '''
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -991,8 +991,8 @@
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
''',
|
||||
'properties': dict({
|
||||
'args': dict({
|
||||
@@ -1032,9 +1032,9 @@
|
||||
'description': '''
|
||||
A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -1114,9 +1114,9 @@
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -1811,7 +1811,7 @@
|
||||
'description': '''
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -2417,8 +2417,8 @@
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
''',
|
||||
'properties': dict({
|
||||
'args': dict({
|
||||
@@ -2458,9 +2458,9 @@
|
||||
'description': '''
|
||||
A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -2540,9 +2540,9 @@
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
||||
@@ -809,7 +809,7 @@
|
||||
'description': '''
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -1415,8 +1415,8 @@
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
''',
|
||||
'properties': dict({
|
||||
'args': dict({
|
||||
@@ -1456,9 +1456,9 @@
|
||||
'description': '''
|
||||
A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -1538,9 +1538,9 @@
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
||||
@@ -2336,7 +2336,7 @@
|
||||
'description': '''
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -2935,8 +2935,8 @@
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
''',
|
||||
'properties': dict({
|
||||
'args': dict({
|
||||
@@ -2975,9 +2975,9 @@
|
||||
'description': '''
|
||||
A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -3056,9 +3056,9 @@
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -3805,7 +3805,7 @@
|
||||
'description': '''
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -4423,8 +4423,8 @@
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
''',
|
||||
'properties': dict({
|
||||
'args': dict({
|
||||
@@ -4463,9 +4463,9 @@
|
||||
'description': '''
|
||||
A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -4544,9 +4544,9 @@
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -5305,7 +5305,7 @@
|
||||
'description': '''
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -5923,8 +5923,8 @@
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
''',
|
||||
'properties': dict({
|
||||
'args': dict({
|
||||
@@ -5963,9 +5963,9 @@
|
||||
'description': '''
|
||||
A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -6044,9 +6044,9 @@
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -6680,7 +6680,7 @@
|
||||
'description': '''
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -7279,8 +7279,8 @@
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
''',
|
||||
'properties': dict({
|
||||
'args': dict({
|
||||
@@ -7319,9 +7319,9 @@
|
||||
'description': '''
|
||||
A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -7400,9 +7400,9 @@
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -8191,7 +8191,7 @@
|
||||
'description': '''
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -8809,8 +8809,8 @@
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
''',
|
||||
'properties': dict({
|
||||
'args': dict({
|
||||
@@ -8849,9 +8849,9 @@
|
||||
'description': '''
|
||||
A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -8930,9 +8930,9 @@
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -9611,7 +9611,7 @@
|
||||
'description': '''
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -10210,8 +10210,8 @@
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
''',
|
||||
'properties': dict({
|
||||
'args': dict({
|
||||
@@ -10250,9 +10250,9 @@
|
||||
'description': '''
|
||||
A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -10331,9 +10331,9 @@
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -11030,7 +11030,7 @@
|
||||
'description': '''
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -11659,8 +11659,8 @@
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
''',
|
||||
'properties': dict({
|
||||
'args': dict({
|
||||
@@ -11699,9 +11699,9 @@
|
||||
'description': '''
|
||||
A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -11780,9 +11780,9 @@
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -12491,7 +12491,7 @@
|
||||
'description': '''
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
``FunctionMessage`` are an older version of the `ToolMessage` schema, and
|
||||
`FunctionMessage` are an older version of the `ToolMessage` schema, and
|
||||
do not contain the `tool_call_id` field.
|
||||
|
||||
The `tool_call_id` field is used to associate the tool call request with the
|
||||
@@ -13109,8 +13109,8 @@
|
||||
|
||||
{"name": "foo", "args": {"a": 1}, "id": "123"}
|
||||
|
||||
This represents a request to call the tool named ``'foo'`` with arguments
|
||||
``{"a": 1}`` and an identifier of ``'123'``.
|
||||
This represents a request to call the tool named `'foo'` with arguments
|
||||
`{"a": 1}` and an identifier of `'123'`.
|
||||
''',
|
||||
'properties': dict({
|
||||
'args': dict({
|
||||
@@ -13149,9 +13149,9 @@
|
||||
'description': '''
|
||||
A chunk of a tool call (e.g., as part of a stream).
|
||||
|
||||
When merging ``ToolCallChunk``s (e.g., via ``AIMessageChunk.__add__``),
|
||||
When merging `ToolCallChunk`s (e.g., via `AIMessageChunk.__add__`),
|
||||
all string attributes are concatenated. Chunks are only merged if their
|
||||
values of ``index`` are equal and not None.
|
||||
values of `index` are equal and not None.
|
||||
|
||||
Example:
|
||||
|
||||
@@ -13230,9 +13230,9 @@
|
||||
Message for passing the result of executing a tool back to a model.
|
||||
|
||||
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
|
||||
is encoded inside the ``content`` field.
|
||||
is encoded inside the `content` field.
|
||||
|
||||
Example: A `ToolMessage` representing a result of ``42`` from a tool call with id
|
||||
Example: A `ToolMessage` representing a result of `42` from a tool call with id
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
||||
@@ -344,7 +344,7 @@ def create_openai_functions_agent(
|
||||
Prompt:
|
||||
|
||||
The agent prompt must have an `agent_scratchpad` key that is a
|
||||
``MessagesPlaceholder``. Intermediate agent actions and tool output
|
||||
`MessagesPlaceholder`. Intermediate agent actions and tool output
|
||||
messages will be passed in here.
|
||||
|
||||
Here's an example:
|
||||
|
||||
@@ -73,7 +73,7 @@ def create_openai_tools_agent(
|
||||
Prompt:
|
||||
|
||||
The agent prompt must have an `agent_scratchpad` key that is a
|
||||
``MessagesPlaceholder``. Intermediate agent actions and tool output
|
||||
`MessagesPlaceholder`. Intermediate agent actions and tool output
|
||||
messages will be passed in here.
|
||||
|
||||
Here's an example:
|
||||
|
||||
@@ -48,8 +48,8 @@ class XMLAgentOutputParser(AgentOutputParser):
|
||||
|
||||
!!! note
|
||||
Minimal escaping allows tool names containing XML tags to be safely represented.
|
||||
For example, a tool named ``search<tool>nested</tool>`` would be escaped as
|
||||
``search[[tool]]nested[[/tool]]`` in the XML and automatically unescaped during
|
||||
For example, a tool named `search<tool>nested</tool>` would be escaped as
|
||||
`search[[tool]]nested[[/tool]]` in the XML and automatically unescaped during
|
||||
parsing.
|
||||
|
||||
Raises:
|
||||
|
||||
@@ -86,7 +86,7 @@ def create_tool_calling_agent(
|
||||
Prompt:
|
||||
|
||||
The agent prompt must have an `agent_scratchpad` key that is a
|
||||
``MessagesPlaceholder``. Intermediate agent actions and tool output
|
||||
`MessagesPlaceholder`. Intermediate agent actions and tool output
|
||||
messages will be passed in here.
|
||||
|
||||
"""
|
||||
|
||||
@@ -189,8 +189,8 @@ class AnalyzeDocumentChain(Chain):
|
||||
This class is deprecated. See below for alternative implementations which
|
||||
supports async and streaming modes of operation.
|
||||
|
||||
If the underlying combine documents chain takes one ``input_documents`` argument
|
||||
(e.g., chains generated by ``load_summarize_chain``):
|
||||
If the underlying combine documents chain takes one `input_documents` argument
|
||||
(e.g., chains generated by `load_summarize_chain`):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -198,8 +198,8 @@ class AnalyzeDocumentChain(Chain):
|
||||
|
||||
summarize_document_chain = split_text | chain
|
||||
|
||||
If the underlying chain takes additional arguments (e.g., ``load_qa_chain``, which
|
||||
takes an additional ``question`` argument), we can use the following:
|
||||
If the underlying chain takes additional arguments (e.g., `load_qa_chain`, which
|
||||
takes an additional `question` argument), we can use the following:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -212,8 +212,8 @@ class AnalyzeDocumentChain(Chain):
|
||||
input_documents=itemgetter("input_document") | split_text,
|
||||
) | chain.pick("output_text")
|
||||
|
||||
To additionally return the input parameters, as ``AnalyzeDocumentChain`` does,
|
||||
we can wrap this construction with ``RunnablePassthrough``:
|
||||
To additionally return the input parameters, as `AnalyzeDocumentChain` does,
|
||||
we can wrap this construction with `RunnablePassthrough`:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
||||
@@ -31,8 +31,8 @@ class MapRerankDocumentsChain(BaseCombineDocumentsChain):
|
||||
r"""Combining documents by mapping a chain over them, then reranking results.
|
||||
|
||||
This algorithm calls an LLMChain on each input document. The LLMChain is expected
|
||||
to have an OutputParser that parses the result into both an answer (``answer_key``)
|
||||
and a score (``rank_key``). The answer with the highest score is then returned.
|
||||
to have an OutputParser that parses the result into both an answer (`answer_key`)
|
||||
and a score (`rank_key`). The answer with the highest score is then returned.
|
||||
|
||||
Example:
|
||||
.. code-block:: python
|
||||
|
||||
@@ -19,18 +19,18 @@ from langchain_classic.memory.buffer import ConversationBufferMemory
|
||||
class ConversationChain(LLMChain):
|
||||
"""Chain to have a conversation and load context from memory.
|
||||
|
||||
This class is deprecated in favor of ``RunnableWithMessageHistory``. Please refer
|
||||
This class is deprecated in favor of `RunnableWithMessageHistory`. Please refer
|
||||
to this tutorial for more detail: https://python.langchain.com/docs/tutorials/chatbot/
|
||||
|
||||
``RunnableWithMessageHistory`` offers several benefits, including:
|
||||
`RunnableWithMessageHistory` offers several benefits, including:
|
||||
|
||||
- Stream, batch, and async support;
|
||||
- More flexible memory handling, including the ability to manage memory
|
||||
outside the chain;
|
||||
outside the chain;
|
||||
- Support for multiple threads.
|
||||
|
||||
Below is a minimal implementation, analogous to using ``ConversationChain`` with
|
||||
the default ``ConversationBufferMemory``:
|
||||
Below is a minimal implementation, analogous to using `ConversationChain` with
|
||||
the default `ConversationBufferMemory`:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -56,7 +56,7 @@ class ConversationChain(LLMChain):
|
||||
config={"configurable": {"session_id": "1"}},
|
||||
) # session_id determines thread
|
||||
|
||||
Memory objects can also be incorporated into the ``get_session_history`` callable:
|
||||
Memory objects can also be incorporated into the `get_session_history` callable:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
||||
@@ -389,7 +389,7 @@ class ConversationalRetrievalChain(BaseConversationalRetrievalChain):
|
||||
max_tokens_limit: int | None = None
|
||||
"""If set, enforces that the documents returned are less than this limit.
|
||||
|
||||
This is only enforced if ``combine_docs_chain`` is of type StuffDocumentsChain.
|
||||
This is only enforced if `combine_docs_chain` is of type StuffDocumentsChain.
|
||||
"""
|
||||
|
||||
def _reduce_tokens_below_limit(self, docs: list[Document]) -> list[Document]:
|
||||
|
||||
@@ -17,7 +17,7 @@ class OpenAIModerationChain(Chain):
|
||||
"""Pass input through a moderation endpoint.
|
||||
|
||||
To use, you should have the `openai` python package installed, and the
|
||||
environment variable ``OPENAI_API_KEY`` set with your API key.
|
||||
environment variable `OPENAI_API_KEY` set with your API key.
|
||||
|
||||
Any parameters that are valid to be passed to the openai.create call can be passed
|
||||
in, even if not explicitly saved on this class.
|
||||
|
||||
@@ -84,9 +84,9 @@ def init_chat_model(
|
||||
to see what parameters are supported by the model.
|
||||
|
||||
Args:
|
||||
model: The name of the model, e.g. ``'o3-mini'``, ``'claude-3-5-sonnet-latest'``. You can
|
||||
model: The name of the model, e.g. `'o3-mini'`, `'claude-3-5-sonnet-latest'`. You can
|
||||
also specify model and model provider in a single argument using
|
||||
``'{model_provider}:{model}'`` format, e.g. ``'openai:o1'``.
|
||||
`'{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:
|
||||
@@ -134,19 +134,19 @@ def init_chat_model(
|
||||
|
||||
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")``.
|
||||
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
|
||||
***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.
|
||||
`configurable_fields=(...)` explicitly.
|
||||
|
||||
config_prefix: If ``'config_prefix'`` is a non-empty string then model will be
|
||||
config_prefix: If `'config_prefix'` is a non-empty string then model will be
|
||||
configurable at runtime via the
|
||||
``config["configurable"]["{config_prefix}_{param}"]`` keys. If
|
||||
``'config_prefix'`` is an empty string then model will be configurable via
|
||||
``config["configurable"]["{param}"]``.
|
||||
`config["configurable"]["{config_prefix}_{param}"]` keys. If
|
||||
`'config_prefix'` is an empty string then model will be configurable via
|
||||
`config["configurable"]["{param}"]`.
|
||||
temperature: Model temperature.
|
||||
max_tokens: Max output tokens.
|
||||
timeout: The maximum time (in seconds) to wait for a response from the model
|
||||
@@ -154,10 +154,10 @@ def init_chat_model(
|
||||
max_retries: The maximum number of attempts the system will make to resend a
|
||||
request if it fails due to issues like network timeouts or rate limits.
|
||||
base_url: The URL of the API endpoint where requests are sent.
|
||||
rate_limiter: A ``BaseRateLimiter`` to space out requests to avoid exceeding
|
||||
rate_limiter: A `BaseRateLimiter` to space out requests to avoid exceeding
|
||||
rate limits.
|
||||
kwargs: Additional model-specific keyword args to pass to
|
||||
``<<selected ChatModel>>.__init__(model=model_name, **kwargs)``.
|
||||
`<<selected ChatModel>>.__init__(model=model_name, **kwargs)`.
|
||||
|
||||
Returns:
|
||||
A BaseChatModel corresponding to the model_name and model_provider specified if
|
||||
@@ -289,7 +289,7 @@ def init_chat_model(
|
||||
!!! version-added "Added in version 0.2.7"
|
||||
|
||||
!!! warning "Behavior changed in 0.2.8"
|
||||
Support for `configurable_fields` and ``config_prefix`` added.
|
||||
Support for `configurable_fields` and `config_prefix` added.
|
||||
|
||||
!!! warning "Behavior changed in 0.2.12"
|
||||
Support for Ollama via langchain-ollama package added
|
||||
|
||||
@@ -46,10 +46,10 @@ def _make_default_key_encoder(namespace: str, algorithm: str) -> Callable[[str],
|
||||
Args:
|
||||
namespace: Prefix that segregates keys from different embedding models.
|
||||
algorithm:
|
||||
* ``'sha1'`` - fast but not collision-resistant
|
||||
* ``'blake2b'`` - cryptographically strong, faster than SHA-1
|
||||
* ``'sha256'`` - cryptographically strong, slower than SHA-1
|
||||
* ``'sha512'`` - cryptographically strong, slower than SHA-1
|
||||
* `'sha1'` - fast but not collision-resistant
|
||||
* `'blake2b'` - cryptographically strong, faster than SHA-1
|
||||
* `'sha256'` - cryptographically strong, slower than SHA-1
|
||||
* `'sha512'` - cryptographically strong, slower than SHA-1
|
||||
|
||||
Returns:
|
||||
A function that encodes a key using the specified algorithm.
|
||||
@@ -242,7 +242,7 @@ class CacheBackedEmbeddings(Embeddings):
|
||||
"""Embed query text.
|
||||
|
||||
By default, this method does not cache queries. To enable caching, set the
|
||||
``cache_query`` parameter to `True` when initializing the embedder.
|
||||
`cache_query` parameter to `True` when initializing the embedder.
|
||||
|
||||
Args:
|
||||
text: The text to embed.
|
||||
@@ -265,7 +265,7 @@ class CacheBackedEmbeddings(Embeddings):
|
||||
"""Embed query text.
|
||||
|
||||
By default, this method does not cache queries. To enable caching, set the
|
||||
``cache_query`` parameter to `True` when initializing the embedder.
|
||||
`cache_query` parameter to `True` when initializing the embedder.
|
||||
|
||||
Args:
|
||||
text: The text to embed.
|
||||
|
||||
@@ -42,7 +42,7 @@ class LLMListwiseRerank(BaseDocumentCompressor):
|
||||
|
||||
Adapted from: https://arxiv.org/pdf/2305.02156.pdf
|
||||
|
||||
``LLMListwiseRerank`` uses a language model to rerank a list of documents based on
|
||||
`LLMListwiseRerank` uses a language model to rerank a list of documents based on
|
||||
their relevance to a query.
|
||||
|
||||
**NOTE**: requires that underlying model implement `with_structured_output`.
|
||||
|
||||
@@ -10,7 +10,7 @@ see the [LangSmith documentation](https://docs.smith.langchain.com/).
|
||||
LangSmith helps you evaluate Chains and other language model application components
|
||||
using a number of LangChain evaluators.
|
||||
An example of this is shown below, assuming you've created a LangSmith dataset
|
||||
called ``<my_dataset_name>``:
|
||||
called `<my_dataset_name>`:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
||||
@@ -43,13 +43,13 @@ For more information on the LangSmith API, see the
|
||||
|
||||
**Attributes**
|
||||
|
||||
- ``arun_on_dataset``: Asynchronous function to evaluate a chain or other LangChain
|
||||
component over a dataset.
|
||||
- ``run_on_dataset``: Function to evaluate a chain or other LangChain component over a
|
||||
dataset.
|
||||
- ``RunEvalConfig``: Class representing the configuration for running evaluation.
|
||||
- ``StringRunEvaluatorChain``: Class representing a string run evaluator chain.
|
||||
- ``InputFormatError``: Exception raised when the input format is incorrect.
|
||||
- `arun_on_dataset`: Asynchronous function to evaluate a chain or other LangChain
|
||||
component over a dataset.
|
||||
- `run_on_dataset`: Function to evaluate a chain or other LangChain component over a
|
||||
dataset.
|
||||
- `RunEvalConfig`: Class representing the configuration for running evaluation.
|
||||
- `StringRunEvaluatorChain`: Class representing a string run evaluator chain.
|
||||
- `InputFormatError`: Exception raised when the input format is incorrect.
|
||||
|
||||
"""
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ Example Docs
|
||||
|
||||
The sample docs directory contains the following files:
|
||||
|
||||
- ``example-10k.html`` - A 10-K SEC filing in HTML format
|
||||
- ``layout-parser-paper.pdf`` - A PDF copy of the layout parser paper
|
||||
- ``factbook.xml``/``factbook.xsl`` - Example XML/XLS files that you
|
||||
- `example-10k.html` - A 10-K SEC filing in HTML format
|
||||
- `layout-parser-paper.pdf` - A PDF copy of the layout parser paper
|
||||
- `factbook.xml`/`factbook.xsl` - Example XML/XLS files that you
|
||||
can use to test stylesheets
|
||||
|
||||
These documents can be used to test out the parsers in the library. In
|
||||
@@ -16,7 +16,7 @@ XBRL 10-K
|
||||
^^^^^^^^^
|
||||
|
||||
You can get an example 10-K in inline XBRL format using the following
|
||||
``curl``. Note, you need to have the user agent set in the header or the
|
||||
`curl`. Note, you need to have the user agent set in the header or the
|
||||
SEC site will reject your request.
|
||||
|
||||
.. code:: bash
|
||||
|
||||
@@ -197,8 +197,8 @@ def test_configurable_with_default() -> None:
|
||||
|
||||
Verifies that a configurable chat model initialized with default parameters:
|
||||
- Has access to all standard runnable methods (`invoke`, `stream`, etc.)
|
||||
- Provides immediate access to non-configurable methods (e.g. ``get_num_tokens``)
|
||||
- Supports model switching through runtime configuration using ``config_prefix``
|
||||
- Provides immediate access to non-configurable methods (e.g. `get_num_tokens`)
|
||||
- Supports model switching through runtime configuration using `config_prefix`
|
||||
- Maintains proper model identity and attributes when reconfigured
|
||||
- Can be used in chains with different model providers via configuration
|
||||
|
||||
|
||||
@@ -58,20 +58,20 @@ class GenericFakeChatModel(BaseChatModel):
|
||||
"""A generic fake chat model that can be used to test the chat model interface.
|
||||
|
||||
* Chat model should be usable in both sync and async tests
|
||||
* Invokes ``on_llm_new_token`` to allow for testing of callback related code for new
|
||||
tokens.
|
||||
* Invokes `on_llm_new_token` to allow for testing of callback related code for new
|
||||
tokens.
|
||||
* Includes logic to break messages into message chunk to facilitate testing of
|
||||
streaming.
|
||||
streaming.
|
||||
"""
|
||||
|
||||
messages: Iterator[AIMessage]
|
||||
"""Get an iterator over messages.
|
||||
|
||||
This can be expanded to accept other types like ``Callables`` / dicts / strings
|
||||
This can be expanded to accept other types like `Callables` / dicts / strings
|
||||
to make the interface more generic if needed.
|
||||
|
||||
!!! note
|
||||
If you want to pass a list, you can use ``iter`` to convert it to an iterator.
|
||||
If you want to pass a list, you can use `iter` to convert it to an iterator.
|
||||
|
||||
!!! warning
|
||||
Streaming is not implemented yet. We should try to implement it in the future by
|
||||
|
||||
@@ -438,12 +438,12 @@ def create_agent( # noqa: PLR0915
|
||||
]:
|
||||
"""Creates an agent graph that calls tools in a loop until a stopping condition is met.
|
||||
|
||||
For more details on using ``create_agent``,
|
||||
For more details on using `create_agent`,
|
||||
visit [Agents](https://docs.langchain.com/oss/python/langchain/agents) documentation.
|
||||
|
||||
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"`), a chat model instance (e.g., `ChatOpenAI()`).
|
||||
tools: A list of tools, dicts, or callables. 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. If provided as a string,
|
||||
@@ -753,7 +753,7 @@ 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``
|
||||
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
|
||||
|
||||
@@ -180,8 +180,8 @@ class ContextEditingMiddleware(AgentMiddleware):
|
||||
"""Middleware that automatically prunes tool results to manage context size.
|
||||
|
||||
The middleware applies a sequence of edits when the total input token count
|
||||
exceeds configured thresholds. Currently the ``ClearToolUsesEdit`` strategy is
|
||||
supported, aligning with Anthropic's ``clear_tool_uses_20250919`` behaviour.
|
||||
exceeds configured thresholds. Currently the `ClearToolUsesEdit` strategy is
|
||||
supported, aligning with Anthropic's `clear_tool_uses_20250919` behaviour.
|
||||
"""
|
||||
|
||||
edits: list[ContextEdit]
|
||||
|
||||
@@ -165,12 +165,12 @@ class HumanInTheLoopMiddleware(AgentMiddleware):
|
||||
|
||||
* `True` indicates all actions are allowed: accept, edit, and respond.
|
||||
* `False` indicates that the tool is auto-approved.
|
||||
* ``ToolConfig`` indicates the specific actions allowed for this tool.
|
||||
The ToolConfig can include a ``description`` field (str or callable) for
|
||||
custom formatting of the interrupt description.
|
||||
* `ToolConfig` indicates the specific actions allowed for this tool.
|
||||
The ToolConfig can include a `description` field (str or callable) for
|
||||
custom formatting of the interrupt description.
|
||||
description_prefix: The prefix to use when constructing action requests.
|
||||
This is used to provide context about the tool call and the action being requested.
|
||||
Not used if a tool has a ``description`` in its ToolConfig.
|
||||
Not used if a tool has a `description` in its ToolConfig.
|
||||
"""
|
||||
super().__init__()
|
||||
resolved_tool_configs: dict[str, ToolConfig] = {}
|
||||
|
||||
@@ -417,17 +417,17 @@ class PIIMiddleware(AgentMiddleware):
|
||||
MAC addresses, and URLs in both user input and agent output.
|
||||
|
||||
Built-in PII types:
|
||||
- ``email``: Email addresses
|
||||
- ``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)
|
||||
- `email`: Email addresses
|
||||
- `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)
|
||||
|
||||
Strategies:
|
||||
- ``block``: Raise an exception when PII is detected
|
||||
- ``redact``: Replace PII with ``[REDACTED_TYPE]`` placeholders
|
||||
- ``mask``: Partially mask PII (e.g., ``****-****-****-1234`` for credit card)
|
||||
- ``hash``: Replace PII with deterministic hash (e.g., ``<email_hash:a1b2c3d4>``)
|
||||
- `block`: Raise an exception when PII is detected
|
||||
- `redact`: Replace PII with `[REDACTED_TYPE]` placeholders
|
||||
- `mask`: Partially mask PII (e.g., `****-****-****-1234` for credit card)
|
||||
- `hash`: Replace PII with deterministic hash (e.g., `<email_hash:a1b2c3d4>`)
|
||||
|
||||
Strategy Selection Guide:
|
||||
|
||||
@@ -487,19 +487,19 @@ class PIIMiddleware(AgentMiddleware):
|
||||
|
||||
Args:
|
||||
pii_type: Type of PII to detect. Can be a built-in type
|
||||
(``email``, ``credit_card``, ``ip``, ``mac_address``, ``url``)
|
||||
(`email`, `credit_card`, `ip`, `mac_address`, `url`)
|
||||
or a custom type name.
|
||||
strategy: How to handle detected PII:
|
||||
|
||||
* ``block``: Raise PIIDetectionError when PII is detected
|
||||
* ``redact``: Replace with ``[REDACTED_TYPE]`` placeholders
|
||||
* ``mask``: Partially mask PII (show last few characters)
|
||||
* ``hash``: Replace with deterministic hash (format: ``<type_hash:digest>``)
|
||||
* `block`: Raise PIIDetectionError when PII is detected
|
||||
* `redact`: Replace with `[REDACTED_TYPE]` placeholders
|
||||
* `mask`: Partially mask PII (show last few characters)
|
||||
* `hash`: Replace with deterministic hash (format: `<type_hash:digest>`)
|
||||
|
||||
detector: Custom detector function or regex pattern.
|
||||
|
||||
* If ``Callable``: Function that takes content string and returns
|
||||
list of PIIMatch objects
|
||||
* If `Callable`: Function that takes content string and returns
|
||||
list of PIIMatch objects
|
||||
* If `str`: Regex pattern to match PII
|
||||
* If `None`: Uses built-in detector for the pii_type
|
||||
|
||||
|
||||
@@ -146,9 +146,9 @@ class PlanningMiddleware(AgentMiddleware):
|
||||
|
||||
Args:
|
||||
system_prompt: Custom system prompt to guide the agent on using the todo tool.
|
||||
If not provided, uses the default ``WRITE_TODOS_SYSTEM_PROMPT``.
|
||||
If not provided, uses the default `WRITE_TODOS_SYSTEM_PROMPT`.
|
||||
tool_description: Custom description for the write_todos tool.
|
||||
If not provided, uses the default ``WRITE_TODOS_TOOL_DESCRIPTION``.
|
||||
If not provided, uses the default `WRITE_TODOS_TOOL_DESCRIPTION`.
|
||||
"""
|
||||
|
||||
state_schema = PlanningState
|
||||
|
||||
@@ -128,21 +128,21 @@ def init_chat_model(
|
||||
|
||||
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")``.
|
||||
not specified, then defaults to `("model", "model_provider")`.
|
||||
|
||||
***Security Note***: Setting ``configurable_fields="any"`` means fields like
|
||||
**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.
|
||||
`configurable_fields=(...)` explicitly.
|
||||
|
||||
config_prefix: If config_prefix is a non-empty string then model will be
|
||||
configurable at runtime via the
|
||||
``config["configurable"]["{config_prefix}_{param}"]`` keys. If
|
||||
`config["configurable"]["{config_prefix}_{param}"]` keys. If
|
||||
config_prefix is an empty string then model will be configurable via
|
||||
``config["configurable"]["{param}"]``.
|
||||
`config["configurable"]["{param}"]`.
|
||||
kwargs: Additional model-specific keyword args to pass to
|
||||
``<<selected ChatModel>>.__init__(model=model_name, **kwargs)``. Examples
|
||||
`<<selected ChatModel>>.__init__(model=model_name, **kwargs)`. Examples
|
||||
include:
|
||||
* temperature: Model temperature.
|
||||
* max_tokens: Max output tokens.
|
||||
@@ -151,7 +151,7 @@ def init_chat_model(
|
||||
* max_retries: The maximum number of attempts the system will make to resend a
|
||||
request if it fails due to issues like network timeouts or rate limits.
|
||||
* base_url: The URL of the API endpoint where requests are sent.
|
||||
* rate_limiter: A ``BaseRateLimiter`` to space out requests to avoid exceeding
|
||||
* rate_limiter: A `BaseRateLimiter` to space out requests to avoid exceeding
|
||||
rate limits.
|
||||
|
||||
Returns:
|
||||
@@ -272,7 +272,7 @@ def init_chat_model(
|
||||
!!! version-added "Added in version 0.2.7"
|
||||
|
||||
!!! warning "Behavior changed in 0.2.8"
|
||||
Support for `configurable_fields` and ``config_prefix`` added.
|
||||
Support for `configurable_fields` and `config_prefix` added.
|
||||
|
||||
!!! warning "Behavior changed in 0.2.12"
|
||||
Support for Ollama via langchain-ollama package added
|
||||
|
||||
@@ -49,10 +49,10 @@ def _make_default_key_encoder(namespace: str, algorithm: str) -> Callable[[str],
|
||||
Args:
|
||||
namespace: Prefix that segregates keys from different embedding models.
|
||||
algorithm:
|
||||
* ``'sha1'`` - fast but not collision-resistant
|
||||
* ``'blake2b'`` - cryptographically strong, faster than SHA-1
|
||||
* ``'sha256'`` - cryptographically strong, slower than SHA-1
|
||||
* ``'sha512'`` - cryptographically strong, slower than SHA-1
|
||||
* `'sha1'` - fast but not collision-resistant
|
||||
* `'blake2b'` - cryptographically strong, faster than SHA-1
|
||||
* `'sha256'` - cryptographically strong, slower than SHA-1
|
||||
* `'sha512'` - cryptographically strong, slower than SHA-1
|
||||
|
||||
Returns:
|
||||
A function that encodes a key using the specified algorithm.
|
||||
@@ -235,7 +235,7 @@ class CacheBackedEmbeddings(Embeddings):
|
||||
"""Embed query text.
|
||||
|
||||
By default, this method does not cache queries. To enable caching, set the
|
||||
``cache_query`` parameter to `True` when initializing the embedder.
|
||||
`cache_query` parameter to `True` when initializing the embedder.
|
||||
|
||||
Args:
|
||||
text: The text to embed.
|
||||
@@ -258,7 +258,7 @@ class CacheBackedEmbeddings(Embeddings):
|
||||
"""Embed query text.
|
||||
|
||||
By default, this method does not cache queries. To enable caching, set the
|
||||
``cache_query`` parameter to `True` when initializing the embedder.
|
||||
`cache_query` parameter to `True` when initializing the embedder.
|
||||
|
||||
Args:
|
||||
text: The text to embed.
|
||||
|
||||
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user