style: more work for refs (#33508)

Largely:
- Remove explicit `"Default is x"` since new refs show default inferred
from sig
- Inline code (useful for eventual parsing)
- Fix code block rendering (indentations)
This commit is contained in:
Mason Daugherty authored and GitHub committed 2025-10-15 18:46:55 -04:00
1 parent d0f8f00e7e
commit 26e0a00c4c
162 files changed
+1017 -1135

No files matched your search

+2
View File
@@ -163,9 +163,11 @@ def send_email(to: str, msg: str, *, priority: str = "normal") -> bool:
**Documentation Guidelines:**
- Types go in function signatures, NOT in docstrings
- If a default is present, DO NOT repeat it in the docstring unless there is post-processing or it is set conditionally.
- Focus on "why" rather than "what" in descriptions
- Document all parameters, return values, and exceptions
- Keep descriptions concise but clear
- Ensure American English spelling (e.g., "behavior", not "behaviour")
📌 *Tip:* Keep descriptions concise but clear. Only document return values if non-obvious.
+2
View File
@@ -163,9 +163,11 @@ def send_email(to: str, msg: str, *, priority: str = "normal") -> bool:
**Documentation Guidelines:**
- Types go in function signatures, NOT in docstrings
- If a default is present, DO NOT repeat it in the docstring unless there is post-processing or it is set conditionally.
- Focus on "why" rather than "what" in descriptions
- Document all parameters, return values, and exceptions
- Keep descriptions concise but clear
- Ensure American English spelling (e.g., "behavior", not "behaviour")
📌 *Tip:* Keep descriptions concise but clear. Only document return values if non-obvious.
+3 -3
View File
@@ -84,7 +84,7 @@ class AgentAction(Serializable):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "agent"]`
@@ -112,7 +112,7 @@ class AgentActionMessageLog(AgentAction):
if (tool, tool_input) cannot be used to fully recreate the LLM
prediction, and you need that LLM prediction (for future agent iteration).
Compared to `log`, this is useful when the underlying LLM is a
ChatModel (and therefore returns messages rather than a string)."""
chat model (and therefore returns messages rather than a string)."""
# Ignoring type because we're overriding the type from AgentAction.
# And this is the correct thing to do in this case.
# The type literal is used for serialization purposes.
@@ -161,7 +161,7 @@ class AgentFinish(Serializable):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "agent"]`
+44 -48
View File
@@ -1,18 +1,15 @@
"""Cache classes.
"""`caches` provides an optional caching layer for language models.
!!! warning
Beta Feature!
This is a beta feature! Please be wary of deploying experimental code to production
unless you've taken appropriate precautions.
**Cache** provides an optional caching layer for LLMs.
A cache is useful for two reasons:
Cache is useful for two reasons:
- It can save you money by reducing the number of API calls you make to the LLM
1. It can save you money by reducing the number of API calls you make to the LLM
provider if you're often requesting the same completion multiple times.
- It can speed up your application by reducing the number of API calls you make
to the LLM provider.
Cache directly competes with Memory. See documentation for Pros and Cons.
2. It can speed up your application by reducing the number of API calls you make to the
LLM provider.
"""
from __future__ import annotations
@@ -34,8 +31,8 @@ class BaseCache(ABC):
The cache interface consists of the following methods:
- lookup: Look up a value based on a prompt and llm_string.
- update: Update the cache based on a prompt and llm_string.
- lookup: Look up a value based on a prompt and `llm_string`.
- update: Update the cache based on a prompt and `llm_string`.
- clear: Clear the cache.
In addition, the cache interface provides an async version of each method.
@@ -47,14 +44,14 @@ class BaseCache(ABC):
@abstractmethod
def lookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None:
"""Look up based on prompt and llm_string.
"""Look up based on `prompt` and `llm_string`.
A cache implementation is expected to generate a key from the 2-tuple
of prompt and llm_string (e.g., by concatenating them with a delimiter).
Args:
prompt: a string representation of the prompt.
In the case of a Chat model, the prompt is a non-trivial
prompt: A string representation of the prompt.
In the case of a chat model, the prompt is a non-trivial
serialization of the prompt into the language model.
llm_string: A string representation of the LLM configuration.
This is used to capture the invocation parameters of the LLM
@@ -63,27 +60,27 @@ class BaseCache(ABC):
representation.
Returns:
On a cache miss, return None. On a cache hit, return the cached value.
The cached value is a list of Generations (or subclasses).
On a cache miss, return `None`. On a cache hit, return the cached value.
The cached value is a list of `Generation` (or subclasses).
"""
@abstractmethod
def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:
"""Update cache based on prompt and llm_string.
"""Update cache based on `prompt` and `llm_string`.
The prompt and llm_string are used to generate a key for the cache.
The key should match that of the lookup method.
Args:
prompt: a string representation of the prompt.
In the case of a Chat model, the prompt is a non-trivial
prompt: A string representation of the prompt.
In the case of a chat model, the prompt is a non-trivial
serialization of the prompt into the language model.
llm_string: A string representation of the LLM configuration.
This is used to capture the invocation parameters of the LLM
(e.g., model name, temperature, stop tokens, max tokens, etc.).
These invocation parameters are serialized into a string
representation.
return_val: The value to be cached. The value is a list of Generations
return_val: The value to be cached. The value is a list of `Generation`
(or subclasses).
"""
@@ -92,14 +89,14 @@ class BaseCache(ABC):
"""Clear cache that can take additional keyword arguments."""
async def alookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None:
"""Async look up based on prompt and llm_string.
"""Async look up based on `prompt` and `llm_string`.
A cache implementation is expected to generate a key from the 2-tuple
of prompt and llm_string (e.g., by concatenating them with a delimiter).
Args:
prompt: a string representation of the prompt.
In the case of a Chat model, the prompt is a non-trivial
prompt: A string representation of the prompt.
In the case of a chat model, the prompt is a non-trivial
serialization of the prompt into the language model.
llm_string: A string representation of the LLM configuration.
This is used to capture the invocation parameters of the LLM
@@ -108,29 +105,29 @@ class BaseCache(ABC):
representation.
Returns:
On a cache miss, return None. On a cache hit, return the cached value.
The cached value is a list of Generations (or subclasses).
On a cache miss, return `None`. On a cache hit, return the cached value.
The cached value is a list of `Generation` (or subclasses).
"""
return await run_in_executor(None, self.lookup, prompt, llm_string)
async def aupdate(
self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE
) -> None:
"""Async update cache based on prompt and llm_string.
"""Async update cache based on `prompt` and `llm_string`.
The prompt and llm_string are used to generate a key for the cache.
The key should match that of the look up method.
Args:
prompt: a string representation of the prompt.
In the case of a Chat model, the prompt is a non-trivial
prompt: A string representation of the prompt.
In the case of a chat model, the prompt is a non-trivial
serialization of the prompt into the language model.
llm_string: A string representation of the LLM configuration.
This is used to capture the invocation parameters of the LLM
(e.g., model name, temperature, stop tokens, max tokens, etc.).
These invocation parameters are serialized into a string
representation.
return_val: The value to be cached. The value is a list of Generations
return_val: The value to be cached. The value is a list of `Generation`
(or subclasses).
"""
return await run_in_executor(None, self.update, prompt, llm_string, return_val)
@@ -150,10 +147,9 @@ class InMemoryCache(BaseCache):
maxsize: The maximum number of items to store in the cache.
If `None`, the cache has no maximum size.
If the cache exceeds the maximum size, the oldest items are removed.
Default is None.
Raises:
ValueError: If maxsize is less than or equal to 0.
ValueError: If `maxsize` is less than or equal to `0`.
"""
self._cache: dict[tuple[str, str], RETURN_VAL_TYPE] = {}
if maxsize is not None and maxsize <= 0:
@@ -162,28 +158,28 @@ class InMemoryCache(BaseCache):
self._maxsize = maxsize
def lookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None:
"""Look up based on prompt and llm_string.
"""Look up based on `prompt` and `llm_string`.
Args:
prompt: a string representation of the prompt.
In the case of a Chat model, the prompt is a non-trivial
prompt: A string representation of the prompt.
In the case of a chat model, the prompt is a non-trivial
serialization of the prompt into the language model.
llm_string: A string representation of the LLM configuration.
Returns:
On a cache miss, return None. On a cache hit, return the cached value.
On a cache miss, return `None`. On a cache hit, return the cached value.
"""
return self._cache.get((prompt, llm_string), None)
def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:
"""Update cache based on prompt and llm_string.
"""Update cache based on `prompt` and `llm_string`.
Args:
prompt: a string representation of the prompt.
In the case of a Chat model, the prompt is a non-trivial
prompt: A string representation of the prompt.
In the case of a chat model, the prompt is a non-trivial
serialization of the prompt into the language model.
llm_string: A string representation of the LLM configuration.
return_val: The value to be cached. The value is a list of Generations
return_val: The value to be cached. The value is a list of `Generation`
(or subclasses).
"""
if self._maxsize is not None and len(self._cache) == self._maxsize:
@@ -196,30 +192,30 @@ class InMemoryCache(BaseCache):
self._cache = {}
async def alookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None:
"""Async look up based on prompt and llm_string.
"""Async look up based on `prompt` and `llm_string`.
Args:
prompt: a string representation of the prompt.
In the case of a Chat model, the prompt is a non-trivial
prompt: A string representation of the prompt.
In the case of a chat model, the prompt is a non-trivial
serialization of the prompt into the language model.
llm_string: A string representation of the LLM configuration.
Returns:
On a cache miss, return None. On a cache hit, return the cached value.
On a cache miss, return `None`. On a cache hit, return the cached value.
"""
return self.lookup(prompt, llm_string)
async def aupdate(
self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE
) -> None:
"""Async update cache based on prompt and llm_string.
"""Async update cache based on `prompt` and `llm_string`.
Args:
prompt: a string representation of the prompt.
In the case of a Chat model, the prompt is a non-trivial
prompt: A string representation of the prompt.
In the case of a chat model, the prompt is a non-trivial
serialization of the prompt into the language model.
llm_string: A string representation of the LLM configuration.
return_val: The value to be cached. The value is a list of Generations
return_val: The value to be cached. The value is a list of `Generation`
(or subclasses).
"""
self.update(prompt, llm_string, return_val)
+5 -5
View File
@@ -1001,7 +1001,7 @@ class BaseCallbackManager(CallbackManagerMixin):
Args:
handler: The handler to add.
inherit: Whether to inherit the handler. Default is True.
inherit: Whether to inherit the handler.
"""
if handler not in self.handlers:
self.handlers.append(handler)
@@ -1028,7 +1028,7 @@ class BaseCallbackManager(CallbackManagerMixin):
Args:
handlers: The handlers to set.
inherit: Whether to inherit the handlers. Default is True.
inherit: Whether to inherit the handlers.
"""
self.handlers = []
self.inheritable_handlers = []
@@ -1044,7 +1044,7 @@ class BaseCallbackManager(CallbackManagerMixin):
Args:
handler: The handler to set.
inherit: Whether to inherit the handler. Default is True.
inherit: Whether to inherit the handler.
"""
self.set_handlers([handler], inherit=inherit)
@@ -1057,7 +1057,7 @@ class BaseCallbackManager(CallbackManagerMixin):
Args:
tags: The tags to add.
inherit: Whether to inherit the tags. Default is True.
inherit: Whether to inherit the tags.
"""
for tag in tags:
if tag in self.tags:
@@ -1087,7 +1087,7 @@ class BaseCallbackManager(CallbackManagerMixin):
Args:
metadata: The metadata to add.
inherit: Whether to inherit the metadata. Default is True.
inherit: Whether to inherit the metadata.
"""
self.metadata.update(metadata)
if inherit:
+2 -2
View File
@@ -132,7 +132,7 @@ class FileCallbackHandler(BaseCallbackHandler):
Args:
text: The text to write to the file.
color: Optional color for the text. Defaults to `self.color`.
end: String appended after the text. Defaults to `""`.
end: String appended after the text.
file: Optional file to write to. Defaults to `self.file`.
Raises:
@@ -239,7 +239,7 @@ class FileCallbackHandler(BaseCallbackHandler):
text: The text to write.
color: Color override for this specific output. If `None`, uses
`self.color`.
end: String appended after the text. Defaults to `""`.
end: String appended after the text.
**kwargs: Additional keyword arguments.
"""
+1 -1
View File
@@ -104,7 +104,7 @@ class StdOutCallbackHandler(BaseCallbackHandler):
Args:
text: The text to print.
color: The color to use for the text.
end: The end character to use. Defaults to "".
end: The end character to use.
**kwargs: Additional keyword arguments.
"""
print_text(text, color=color or self.color, end=end)
+2 -2
View File
@@ -152,8 +152,8 @@ class BaseChatMessageHistory(ABC):
message: A BaseMessage object to store.
Raises:
NotImplementedError: If the sub-class has not implemented an efficient
add_messages method.
`NotImplementedError`: If the sub-class has not implemented an efficient
`add_messages` method.
"""
if type(self).add_messages != BaseChatMessageHistory.add_messages:
# This means that the sub-class has implemented an efficient add_messages
@@ -35,38 +35,38 @@ class BaseLoader(ABC): # noqa: B024
# Sub-classes should not implement this method directly. Instead, they
# should implement the lazy load method.
def load(self) -> list[Document]:
"""Load data into Document objects.
"""Load data into `Document` objects.
Returns:
the documents.
The documents.
"""
return list(self.lazy_load())
async def aload(self) -> list[Document]:
"""Load data into Document objects.
"""Load data into `Document` objects.
Returns:
the documents.
The documents.
"""
return [document async for document in self.alazy_load()]
def load_and_split(
self, text_splitter: TextSplitter | None = None
) -> list[Document]:
"""Load Documents and split into chunks. Chunks are returned as Documents.
"""Load Documents and split into chunks. Chunks are returned as `Document`.
Do not override this method. It should be considered to be deprecated!
Args:
text_splitter: TextSplitter instance to use for splitting documents.
Defaults to RecursiveCharacterTextSplitter.
text_splitter: `TextSplitter` instance to use for splitting documents.
Defaults to `RecursiveCharacterTextSplitter`.
Raises:
ImportError: If langchain-text-splitters is not installed
and no text_splitter is provided.
ImportError: If `langchain-text-splitters` is not installed
and no `text_splitter` is provided.
Returns:
List of Documents.
List of `Document`.
"""
if text_splitter is None:
if not _HAS_TEXT_SPLITTERS:
@@ -86,10 +86,10 @@ class BaseLoader(ABC): # noqa: B024
# Attention: This method will be upgraded into an abstractmethod once it's
# implemented in all the existing subclasses.
def lazy_load(self) -> Iterator[Document]:
"""A lazy loader for Documents.
"""A lazy loader for `Document`.
Yields:
the documents.
The `Document` objects.
"""
if type(self).load != BaseLoader.load:
return iter(self.load())
@@ -97,10 +97,10 @@ class BaseLoader(ABC): # noqa: B024
raise NotImplementedError(msg)
async def alazy_load(self) -> AsyncIterator[Document]:
"""A lazy loader for Documents.
"""A lazy loader for `Document`.
Yields:
the documents.
The `Document` objects.
"""
iterator = await run_in_executor(None, self.lazy_load)
done = object()
@@ -115,7 +115,7 @@ class BaseBlobParser(ABC):
"""Abstract interface for blob parsers.
A blob parser provides a way to parse raw data stored in a blob into one
or more documents.
or more `Document` objects.
The parser can be composed with blob loaders, making it easy to reuse
a parser independent of how the blob was originally loaded.
@@ -128,25 +128,25 @@ class BaseBlobParser(ABC):
Subclasses are required to implement this method.
Args:
blob: Blob instance
blob: `Blob` instance
Returns:
Generator of documents
Generator of `Document` objects
"""
def parse(self, blob: Blob) -> list[Document]:
"""Eagerly parse the blob into a document or documents.
"""Eagerly parse the blob into a `Document` or `Document` objects.
This is a convenience method for interactive development environment.
Production applications should favor the lazy_parse method instead.
Production applications should favor the `lazy_parse` method instead.
Subclasses should generally not over-ride this parse method.
Args:
blob: Blob instance
blob: `Blob` instance
Returns:
List of documents
List of `Document` objects
"""
return list(self.lazy_parse(blob))
@@ -76,8 +76,8 @@ class LangSmithLoader(BaseLoader):
splits: A list of dataset splits, which are
divisions of your dataset such as 'train', 'test', or 'validation'.
Returns examples only from the specified splits.
inline_s3_urls: Whether to inline S3 URLs. Defaults to `True`.
offset: The offset to start from. Defaults to 0.
inline_s3_urls: Whether to inline S3 URLs.
offset: The offset to start from.
limit: The maximum number of examples to return.
metadata: Metadata to filter by.
filter: A structured filter string to apply to the examples.
+40 -40
View File
@@ -57,51 +57,51 @@ class Blob(BaseMedia):
Example: Initialize a blob from in-memory data
```python
from langchain_core.documents import Blob
```python
from langchain_core.documents import Blob
blob = Blob.from_data("Hello, world!")
blob = Blob.from_data("Hello, world!")
# Read the blob as a string
print(blob.as_string())
# Read the blob as a string
print(blob.as_string())
# Read the blob as bytes
print(blob.as_bytes())
# Read the blob as bytes
print(blob.as_bytes())
# Read the blob as a byte stream
with blob.as_bytes_io() as f:
print(f.read())
```
# Read the blob as a byte stream
with blob.as_bytes_io() as f:
print(f.read())
```
Example: Load from memory and specify mime-type and metadata
```python
from langchain_core.documents import Blob
```python
from langchain_core.documents import Blob
blob = Blob.from_data(
data="Hello, world!",
mime_type="text/plain",
metadata={"source": "https://example.com"},
)
```
blob = Blob.from_data(
data="Hello, world!",
mime_type="text/plain",
metadata={"source": "https://example.com"},
)
```
Example: Load the blob from a file
```python
from langchain_core.documents import Blob
```python
from langchain_core.documents import Blob
blob = Blob.from_path("path/to/file.txt")
blob = Blob.from_path("path/to/file.txt")
# Read the blob as a string
print(blob.as_string())
# Read the blob as a string
print(blob.as_string())
# Read the blob as bytes
print(blob.as_bytes())
# Read the blob as bytes
print(blob.as_bytes())
# Read the blob as a byte stream
with blob.as_bytes_io() as f:
print(f.read())
```
# Read the blob as a byte stream
with blob.as_bytes_io() as f:
print(f.read())
```
"""
data: bytes | str | None = None
@@ -111,7 +111,7 @@ class Blob(BaseMedia):
encoding: str = "utf-8"
"""Encoding to use if decoding the bytes into a string.
Use utf-8 as default encoding, if decoding to string.
Use `utf-8` as default encoding, if decoding to string.
"""
path: PathLike | None = None
"""Location where the original content was found."""
@@ -127,7 +127,7 @@ class Blob(BaseMedia):
If a path is associated with the blob, it will default to the path location.
Unless explicitly set via a metadata field called "source", in which
Unless explicitly set via a metadata field called `"source"`, in which
case that value will be used instead.
"""
if self.metadata and "source" in self.metadata:
@@ -184,7 +184,7 @@ class Blob(BaseMedia):
"""Read data as a byte stream.
Raises:
NotImplementedError: If the blob cannot be represented as a byte stream.
`NotImplementedError`: If the blob cannot be represented as a byte stream.
Yields:
The data as a byte stream.
@@ -211,11 +211,11 @@ class Blob(BaseMedia):
"""Load the blob from a path like object.
Args:
path: path like object to file to be read
path: Path-like object to file to be read
encoding: Encoding to use if decoding the bytes into a string
mime_type: if provided, will be set as the mime-type of the data
mime_type: If provided, will be set as the mime-type of the data
guess_type: If `True`, the mimetype will be guessed from the file extension,
if a mime-type was not provided
if a mime-type was not provided
metadata: Metadata to associate with the blob
Returns:
@@ -248,10 +248,10 @@ class Blob(BaseMedia):
"""Initialize the blob from in-memory data.
Args:
data: the in-memory data associated with the blob
data: The in-memory data associated with the blob
encoding: Encoding to use if decoding the bytes into a string
mime_type: if provided, will be set as the mime-type of the data
path: if provided, will be set as the source from which the data came
mime_type: If provided, will be set as the mime-type of the data
path: If provided, will be set as the source from which the data came
metadata: Metadata to associate with the blob
Returns:
@@ -303,7 +303,7 @@ class Document(BaseMedia):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
["langchain", "schema", "document"]
+4 -2
View File
@@ -18,7 +18,8 @@ class FakeEmbeddings(Embeddings, BaseModel):
This embedding model creates embeddings by sampling from a normal distribution.
Do not use this outside of testing, as it is not a real embedding model.
!!! warning
Do not use this outside of testing, as it is not a real embedding model.
Instantiate:
```python
@@ -72,7 +73,8 @@ class DeterministicFakeEmbedding(Embeddings, BaseModel):
This embedding model creates embeddings by sampling from a normal distribution
with a seed based on the hash of the text.
Do not use this outside of testing, as it is not a real embedding model.
!!! warning
Do not use this outside of testing, as it is not a real embedding model.
Instantiate:
```python
@@ -154,7 +154,7 @@ class SemanticSimilarityExampleSelector(_VectorStoreExampleSelector):
examples: List of examples to use in the prompt.
embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
vectorstore_cls: A vector store DB interface class, e.g. FAISS.
k: Number of examples to select. Default is 4.
k: Number of examples to select.
input_keys: If provided, the search is based on the input variables
instead of all variables.
example_keys: If provided, keys to filter examples to.
@@ -198,7 +198,7 @@ class SemanticSimilarityExampleSelector(_VectorStoreExampleSelector):
examples: List of examples to use in the prompt.
embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
vectorstore_cls: A vector store DB interface class, e.g. FAISS.
k: Number of examples to select. Default is 4.
k: Number of examples to select.
input_keys: If provided, the search is based on the input variables
instead of all variables.
example_keys: If provided, keys to filter examples to.
@@ -285,9 +285,8 @@ class MaxMarginalRelevanceExampleSelector(_VectorStoreExampleSelector):
examples: List of examples to use in the prompt.
embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
vectorstore_cls: A vector store DB interface class, e.g. FAISS.
k: Number of examples to select. Default is 4.
k: Number of examples to select.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Default is 20.
input_keys: If provided, the search is based on the input variables
instead of all variables.
example_keys: If provided, keys to filter examples to.
@@ -333,9 +332,8 @@ class MaxMarginalRelevanceExampleSelector(_VectorStoreExampleSelector):
examples: List of examples to use in the prompt.
embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
vectorstore_cls: A vector store DB interface class, e.g. FAISS.
k: Number of examples to select. Default is 4.
k: Number of examples to select.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Default is 20.
input_keys: If provided, the search is based on the input variables
instead of all variables.
example_keys: If provided, keys to filter examples to.
+3 -4
View File
@@ -16,7 +16,7 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818
"""Exception that output parsers should raise to signify a parsing error.
This exists to differentiate parsing errors from other code or execution errors
that also may arise inside the output parser. OutputParserExceptions will be
that also may arise inside the output parser. `OutputParserException` will be
available to catch and handle in ways to fix the parsing error, while other
errors will be raised.
"""
@@ -28,7 +28,7 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818
llm_output: str | None = None,
send_to_llm: bool = False, # noqa: FBT001,FBT002
):
"""Create an OutputParserException.
"""Create an `OutputParserException`.
Args:
error: The error that's being re-raised or an error message.
@@ -37,11 +37,10 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818
llm_output: String model output which is error-ing.
send_to_llm: Whether to send the observation and llm_output back to an Agent
after an OutputParserException has been raised.
after an `OutputParserException` has been raised.
This gives the underlying model driving the agent the context that the
previous output was improperly structured, in the hopes that it will
update the output to the correct format.
Defaults to `False`.
Raises:
ValueError: If `send_to_llm` is True but either observation or
+8 -14
View File
@@ -326,8 +326,8 @@ def index(
record_manager: Timestamped set to keep track of which documents were
updated.
vector_store: VectorStore or DocumentIndex to index the documents into.
batch_size: Batch size to use when indexing. Default is 100.
cleanup: How to handle clean up of documents. Default is None.
batch_size: Batch size to use when indexing.
cleanup: How to handle clean up of documents.
- incremental: Cleans up all documents that haven't been updated AND
that are associated with source ids that were seen during indexing.
@@ -342,15 +342,12 @@ def index(
source ids that were seen during indexing.
- None: Do not delete any documents.
source_id_key: Optional key that helps identify the original source
of the document. Default is None.
of the document.
cleanup_batch_size: Batch size to use when cleaning up documents.
Default is 1_000.
force_update: Force update documents even if they are present in the
record manager. Useful if you are re-indexing with updated embeddings.
Default is False.
key_encoder: Hashing algorithm to use for hashing the document content and
metadata. Default is "sha1".
Other options include "blake2b", "sha256", and "sha512".
metadata. Options include "blake2b", "sha256", and "sha512".
!!! version-added "Added in version 0.3.66"
@@ -667,8 +664,8 @@ async def aindex(
record_manager: Timestamped set to keep track of which documents were
updated.
vector_store: VectorStore or DocumentIndex to index the documents into.
batch_size: Batch size to use when indexing. Default is 100.
cleanup: How to handle clean up of documents. Default is None.
batch_size: Batch size to use when indexing.
cleanup: How to handle clean up of documents.
- incremental: Cleans up all documents that haven't been updated AND
that are associated with source ids that were seen during indexing.
@@ -683,15 +680,12 @@ async def aindex(
source ids that were seen during indexing.
- None: Do not delete any documents.
source_id_key: Optional key that helps identify the original source
of the document. Default is None.
of the document.
cleanup_batch_size: Batch size to use when cleaning up documents.
Default is 1_000.
force_update: Force update documents even if they are present in the
record manager. Useful if you are re-indexing with updated embeddings.
Default is False.
key_encoder: Hashing algorithm to use for hashing the document content and
metadata. Default is "sha1".
Other options include "blake2b", "sha256", and "sha512".
metadata. Options include "blake2b", "sha256", and "sha512".
!!! version-added "Added in version 0.3.66"
@@ -89,7 +89,8 @@ class ParsedDataUri(TypedDict):
def _parse_data_uri(uri: str) -> ParsedDataUri | None:
"""Parse a data URI into its components.
If parsing fails, return None. If either MIME type or data is missing, return None.
If parsing fails, return `None`. If either MIME type or data is missing, return
`None`.
Example:
```python
@@ -1525,8 +1525,8 @@ class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
with keys `'raw'`, `'parsed'`, and `'parsing_error'`.
Raises:
ValueError: If there are any unsupported `kwargs`.
NotImplementedError: If the model does not implement
`ValueError`: If there are any unsupported `kwargs`.
`NotImplementedError`: If the model does not implement
`with_structured_output()`.
Returns:
@@ -1,4 +1,4 @@
"""Fake ChatModel for testing purposes."""
"""Fake chat model for testing purposes."""
import asyncio
import re
@@ -19,7 +19,7 @@ from langchain_core.runnables import RunnableConfig
class FakeMessagesListChatModel(BaseChatModel):
"""Fake `ChatModel` for testing purposes."""
"""Fake chat model for testing purposes."""
responses: list[BaseMessage]
"""List of responses to **cycle** through in order."""
@@ -57,7 +57,7 @@ class FakeListChatModelError(Exception):
class FakeListChatModel(SimpleChatModel):
"""Fake ChatModel for testing purposes."""
"""Fake chat model for testing purposes."""
responses: list[str]
"""List of responses to **cycle** through in order."""
@@ -74,8 +74,8 @@ def create_base_retry_decorator(
Args:
error_types: List of error types to retry on.
max_retries: Number of retries. Default is 1.
run_manager: Callback manager for the run. Default is None.
max_retries: Number of retries.
run_manager: Callback manager for the run.
Returns:
A retry decorator.
@@ -153,7 +153,7 @@ def get_prompts(
Args:
params: Dictionary of parameters.
prompts: List of prompts.
cache: Cache object. Default is None.
cache: Cache object.
Returns:
A tuple of existing prompts, llm_string, missing prompt indexes,
@@ -189,7 +189,7 @@ async def aget_prompts(
Args:
params: Dictionary of parameters.
prompts: List of prompts.
cache: Cache object. Default is None.
cache: Cache object.
Returns:
A tuple of existing prompts, llm_string, missing prompt indexes,
+3 -4
View File
@@ -42,10 +42,9 @@ def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:
Args:
obj: The object to dump.
pretty: Whether to pretty print the json. If true, the json will be
indented with 2 spaces (if no indent is provided as part of kwargs).
Default is False.
**kwargs: Additional arguments to pass to json.dumps
pretty: Whether to pretty print the json. If `True`, the json will be
indented with 2 spaces (if no indent is provided as part of `kwargs`).
**kwargs: Additional arguments to pass to `json.dumps`
Returns:
A json string representation of the object.
+3 -12
View File
@@ -67,12 +67,9 @@ class Reviver:
valid_namespaces: A list of additional namespaces (modules)
to allow to be deserialized.
secrets_from_env: Whether to load secrets from the environment.
Defaults to `True`.
additional_import_mappings: A dictionary of additional namespace mappings
You can use this to override default mappings or add new mappings.
ignore_unserializable_fields: Whether to ignore unserializable fields.
Defaults to `False`.
"""
self.secrets_from_env = secrets_from_env
self.secrets_map = secrets_map or {}
@@ -103,10 +100,10 @@ class Reviver:
The revived value.
Raises:
ValueError: If the namespace is invalid.
ValueError: If trying to deserialize something that cannot
`ValueError`: If the namespace is invalid.
`ValueError`: If trying to deserialize something that cannot
be deserialized in the current version of langchain-core.
NotImplementedError: If the object is not implemented and
`NotImplementedError`: If the object is not implemented and
`ignore_unserializable_fields` is False.
"""
if (
@@ -204,12 +201,9 @@ def loads(
valid_namespaces: A list of additional namespaces (modules)
to allow to be deserialized.
secrets_from_env: Whether to load secrets from the environment.
Defaults to `True`.
additional_import_mappings: A dictionary of additional namespace mappings
You can use this to override default mappings or add new mappings.
ignore_unserializable_fields: Whether to ignore unserializable fields.
Defaults to `False`.
Returns:
Revived LangChain objects.
@@ -249,12 +243,9 @@ def load(
valid_namespaces: A list of additional namespaces (modules)
to allow to be deserialized.
secrets_from_env: Whether to load secrets from the environment.
Defaults to `True`.
additional_import_mappings: A dictionary of additional namespace mappings
You can use this to override default mappings or add new mappings.
ignore_unserializable_fields: Whether to ignore unserializable fields.
Defaults to `False`.
Returns:
Revived LangChain objects.
@@ -96,7 +96,7 @@ class Serializable(BaseModel, ABC):
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.
- `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.
@@ -127,10 +127,10 @@ class Serializable(BaseModel, ABC):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
For example, if the class is `langchain.llms.openai.OpenAI`, then the
namespace is ["langchain", "llms", "openai"]
namespace is `["langchain", "llms", "openai"]`
Returns:
The namespace.
+6 -11
View File
@@ -148,7 +148,7 @@ class UsageMetadata(TypedDict):
class AIMessage(BaseMessage):
"""Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -168,7 +168,7 @@ class AIMessage(BaseMessage):
"""
type: Literal["ai"] = "ai"
"""The type of the message (used for deserialization). Defaults to "ai"."""
"""The type of the message (used for deserialization)."""
@overload
def __init__(
@@ -191,7 +191,7 @@ class AIMessage(BaseMessage):
content_blocks: list[types.ContentBlock] | None = None,
**kwargs: Any,
) -> None:
"""Initialize `AIMessage`.
"""Initializes an `AIMessage`.
Specify `content` as positional arg or `content_blocks` for typing.
@@ -335,7 +335,6 @@ class AIMessage(BaseMessage):
Args:
html: Whether to return an HTML-formatted string.
Defaults to `False`.
Returns:
A pretty representation of the message.
@@ -378,17 +377,13 @@ class AIMessageChunk(AIMessage, BaseMessageChunk):
# to make sure that the chunk variant can be discriminated from the
# non-chunk variant.
type: Literal["AIMessageChunk"] = "AIMessageChunk" # type: ignore[assignment]
"""The type of the message (used for deserialization).
Defaults to `AIMessageChunk`.
"""
"""The type of the message (used for deserialization)."""
tool_call_chunks: list[ToolCallChunk] = []
"""If provided, tool call chunks associated with the message."""
chunk_position: Literal["last"] | None = None
"""Optional span represented by an aggregated AIMessageChunk.
"""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`.
@@ -553,7 +548,7 @@ class AIMessageChunk(AIMessage, BaseMessageChunk):
@model_validator(mode="after")
def init_server_tool_calls(self) -> Self:
"""Parse server_tool_call_chunks."""
"""Parse `server_tool_call_chunks`."""
if (
self.chunk_position == "last"
and self.response_metadata.get("output_version") == "v1"
+5 -5
View File
@@ -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 chat model.
"""
content: str | list[str | dict]
@@ -159,7 +159,7 @@ class BaseMessage(Serializable):
content_blocks: list[types.ContentBlock] | None = None,
**kwargs: Any,
) -> None:
"""Initialize `BaseMessage`.
"""Initialize a `BaseMessage`.
Specify `content` as positional arg or `content_blocks` for typing.
@@ -184,7 +184,7 @@ class BaseMessage(Serializable):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "messages"]`
@@ -307,7 +307,7 @@ class BaseMessage(Serializable):
Args:
html: Whether to format the message as HTML. If `True`, the message will be
formatted with HTML tags. Default is False.
formatted with HTML tags.
Returns:
A pretty representation of the message.
@@ -464,7 +464,7 @@ def get_msg_title_repr(title: str, *, bold: bool = False) -> str:
Args:
title: The title.
bold: Whether to bold the title. Default is False.
bold: Whether to bold the title.
Returns:
The title representation.
+2 -6
View File
@@ -19,7 +19,7 @@ class ChatMessage(BaseMessage):
"""The speaker / role of the Message."""
type: Literal["chat"] = "chat"
"""The type of the message (used during serialization). Defaults to "chat"."""
"""The type of the message (used during serialization)."""
class ChatMessageChunk(ChatMessage, BaseMessageChunk):
@@ -29,11 +29,7 @@ class ChatMessageChunk(ChatMessage, BaseMessageChunk):
# to make sure that the chunk variant can be discriminated from the
# non-chunk variant.
type: Literal["ChatMessageChunk"] = "ChatMessageChunk" # type: ignore[assignment]
"""The type of the message (used during serialization).
Defaults to `'ChatMessageChunk'`.
"""
"""The type of the message (used during serialization)."""
@override
def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
+12 -1
View File
@@ -156,7 +156,9 @@ class Citation(TypedDict):
"""Type of the content block. Used for discrimination."""
id: NotRequired[str]
"""Content block identifier. Either:
"""Content block identifier.
Either:
- Generated by the provider (e.g., OpenAI's file ID)
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
@@ -201,6 +203,7 @@ class NonStandardAnnotation(TypedDict):
"""Content block identifier.
Either:
- Generated by the provider (e.g., OpenAI's file ID)
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
@@ -235,6 +238,7 @@ class TextContentBlock(TypedDict):
"""Content block identifier.
Either:
- Generated by the provider (e.g., OpenAI's file ID)
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
@@ -468,6 +472,7 @@ class ReasoningContentBlock(TypedDict):
"""Content block identifier.
Either:
- Generated by the provider (e.g., OpenAI's file ID)
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
@@ -510,6 +515,7 @@ class ImageContentBlock(TypedDict):
"""Content block identifier.
Either:
- Generated by the provider (e.g., OpenAI's file ID)
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
@@ -557,6 +563,7 @@ class VideoContentBlock(TypedDict):
"""Content block identifier.
Either:
- Generated by the provider (e.g., OpenAI's file ID)
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
@@ -603,6 +610,7 @@ class AudioContentBlock(TypedDict):
"""Content block identifier.
Either:
- Generated by the provider (e.g., OpenAI's file ID)
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
@@ -660,6 +668,7 @@ class PlainTextContentBlock(TypedDict):
"""Content block identifier.
Either:
- Generated by the provider (e.g., OpenAI's file ID)
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
@@ -719,6 +728,7 @@ class FileContentBlock(TypedDict):
"""Content block identifier.
Either:
- Generated by the provider (e.g., OpenAI's file ID)
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
@@ -781,6 +791,7 @@ class NonStandardContentBlock(TypedDict):
"""Content block identifier.
Either:
- Generated by the provider (e.g., OpenAI's file ID)
- Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
@@ -19,7 +19,7 @@ class FunctionMessage(BaseMessage):
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
"""
@@ -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)."""
class FunctionMessageChunk(FunctionMessage, BaseMessageChunk):
@@ -38,11 +38,7 @@ class FunctionMessageChunk(FunctionMessage, BaseMessageChunk):
# to make sure that the chunk variant can be discriminated from the
# non-chunk variant.
type: Literal["FunctionMessageChunk"] = "FunctionMessageChunk" # type: ignore[assignment]
"""The type of the message (used for serialization).
Defaults to `'FunctionMessageChunk'`.
"""
"""The type of the message (used for serialization)."""
@override
def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
+2 -7
View File
@@ -27,11 +27,7 @@ class HumanMessage(BaseMessage):
"""
type: Literal["human"] = "human"
"""The type of the message (used for serialization).
Defaults to `'human'`.
"""
"""The type of the message (used for serialization)."""
@overload
def __init__(
@@ -71,5 +67,4 @@ class HumanMessageChunk(HumanMessage, BaseMessageChunk):
# to make sure that the chunk variant can be discriminated from the
# non-chunk variant.
type: Literal["HumanMessageChunk"] = "HumanMessageChunk" # type: ignore[assignment]
"""The type of the message (used for serialization).
Defaults to "HumanMessageChunk"."""
"""The type of the message (used for serialization)."""
@@ -9,7 +9,7 @@ class RemoveMessage(BaseMessage):
"""Message responsible for deleting other messages."""
type: Literal["remove"] = "remove"
"""The type of the message (used for serialization). Defaults to "remove"."""
"""The type of the message (used for serialization)."""
def __init__(
self,
+2 -10
View File
@@ -27,11 +27,7 @@ class SystemMessage(BaseMessage):
"""
type: Literal["system"] = "system"
"""The type of the message (used for serialization).
Defaults to `'system'`.
"""
"""The type of the message (used for serialization)."""
@overload
def __init__(
@@ -71,8 +67,4 @@ class SystemMessageChunk(SystemMessage, BaseMessageChunk):
# to make sure that the chunk variant can be discriminated from the
# non-chunk variant.
type: Literal["SystemMessageChunk"] = "SystemMessageChunk" # type: ignore[assignment]
"""The type of the message (used for serialization).
Defaults to `'SystemMessageChunk'`.
"""
"""The type of the message (used for serialization)."""
+3 -7
View File
@@ -60,7 +60,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
"""
@@ -69,11 +69,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
"""Tool call that this message is responding to."""
type: Literal["tool"] = "tool"
"""The type of the message (used for serialization).
Defaults to `'tool'`.
"""
"""The type of the message (used for serialization)."""
artifact: Any = None
"""Artifact of the Tool execution which is not meant to be sent to the model.
@@ -164,7 +160,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
content_blocks: list[types.ContentBlock] | None = None,
**kwargs: Any,
) -> None:
"""Initialize `ToolMessage`.
"""Initialize a `ToolMessage`.
Specify `content` as positional arg or `content_blocks` for typing.
+20 -26
View File
@@ -96,9 +96,7 @@ 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'`.
ai_prefix: The prefix to prepend to contents of `AIMessage`. Default is
`'AI'`.
ai_prefix: The prefix to prepend to contents of `AIMessage`.
Returns:
A single string concatenation of all input messages.
@@ -227,10 +225,10 @@ def _create_message_from_message_type(
Args:
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.
tool_calls: (list[dict[str, Any]]) the tool calls. Default is None.
id: (str) the id of the message. Default is None.
name: (str) the name of the message.
tool_call_id: (str) the tool call id.
tool_calls: (list[dict[str, Any]]) the tool calls.
id: (str) the id of the message.
additional_kwargs: (dict[str, Any]) additional keyword arguments.
Returns:
@@ -319,11 +317,11 @@ def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage:
message: a representation of a message in one of the supported formats.
Returns:
an instance of a message or a message template.
An instance of a message or a message template.
Raises:
NotImplementedError: if the message type is not supported.
ValueError: if the message dict does not contain the required keys.
`NotImplementedError`: if the message type is not supported.
`ValueError`: if the message dict does not contain the required keys.
"""
if isinstance(message, BaseMessage):
@@ -425,19 +423,19 @@ def filter_messages(
Args:
messages: Sequence Message-like objects to filter.
include_names: Message names to include. Default is None.
exclude_names: Messages names to exclude. Default is None.
include_names: Message names to include.
exclude_names: Messages names to exclude.
include_types: Message types to include. Can be specified as string names
(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`
classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...).
Default is None.
include_ids: Message IDs to include. Default is None.
exclude_ids: Message IDs to exclude. Default is None.
exclude_tool_calls: Tool call IDs to exclude. Default is None.
include_ids: Message IDs to include.
exclude_ids: Message IDs to exclude.
exclude_tool_calls: Tool call IDs to exclude.
Can be one of the following:
- `True`: all `AIMessage`s with tool calls and all
`ToolMessage` objects will be excluded.
@@ -568,7 +566,6 @@ 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'`.
Returns:
list of BaseMessages with consecutive runs of message types merged into single
@@ -745,12 +742,10 @@ def trim_messages(
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'`.
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
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
@@ -759,7 +754,7 @@ def trim_messages(
`'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
the first occurrence of this type is ignored. This is done after we trim
@@ -768,10 +763,9 @@ def trim_messages(
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"`.
Default is False.
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
@@ -1683,11 +1677,11 @@ def count_tokens_approximately(
Args:
messages: List of messages to count tokens for.
chars_per_token: Number of characters per token to use for the approximation.
Default is 4 (one token corresponds to ~4 chars for common English text).
One token corresponds to ~4 chars for common English text.
You can also specify float values for more fine-grained control.
[See more here](https://platform.openai.com/tokenizer).
extra_tokens_per_message: Number of extra tokens to add per message.
Default is 3 (special tokens, including beginning/end of message).
extra_tokens_per_message: Number of extra tokens to add per message, e.g.
special tokens, including beginning/end of message.
You can also specify float values for more fine-grained control.
[See more here](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb).
count_name: Whether to include message names in the count.
+24 -24
View File
@@ -31,13 +31,13 @@ class BaseLLMOutputParser(ABC, Generic[T]):
@abstractmethod
def parse_result(self, result: list[Generation], *, partial: bool = False) -> T:
"""Parse a list of candidate model Generations into a specific format.
"""Parse a list of candidate model `Generation` objects into a specific format.
Args:
result: A list of Generations to be parsed. The Generations are assumed
to be different candidate outputs for a single model input.
result: A list of `Generation` to be parsed. The `Generation` objects are
assumed to be different candidate outputs for a single model input.
partial: Whether to parse the output as a partial result. This is useful
for parsers that can parse partial results. Default is False.
for parsers that can parse partial results.
Returns:
Structured output.
@@ -46,17 +46,17 @@ class BaseLLMOutputParser(ABC, Generic[T]):
async def aparse_result(
self, result: list[Generation], *, partial: bool = False
) -> T:
"""Async parse a list of candidate model Generations into a specific format.
"""Async parse a list of candidate model `Generation` objects into a specific format.
Args:
result: A list of Generations to be parsed. The Generations are assumed
result: A list of `Generation` to be parsed. The Generations are assumed
to be different candidate outputs for a single model input.
partial: Whether to parse the output as a partial result. This is useful
for parsers that can parse partial results. Default is False.
for parsers that can parse partial results.
Returns:
Structured output.
"""
""" # noqa: E501
return await run_in_executor(None, self.parse_result, result, partial=partial)
@@ -172,7 +172,7 @@ class BaseOutputParser(
This property is inferred from the first type argument of the class.
Raises:
TypeError: If the class doesn't have an inferable OutputType.
TypeError: If the class doesn't have an inferable `OutputType`.
"""
for base in self.__class__.mro():
if hasattr(base, "__pydantic_generic_metadata__"):
@@ -234,16 +234,16 @@ class BaseOutputParser(
@override
def parse_result(self, result: list[Generation], *, partial: bool = False) -> T:
"""Parse a list of candidate model Generations into a specific format.
"""Parse a list of candidate model `Generation` objects into a specific format.
The return value is parsed from only the first Generation in the result, which
is assumed to be the highest-likelihood Generation.
The return value is parsed from only the first `Generation` in the result, which
is assumed to be the highest-likelihood `Generation`.
Args:
result: A list of Generations to be parsed. The Generations are assumed
to be different candidate outputs for a single model input.
result: A list of `Generation` to be parsed. The `Generation` objects are
assumed to be different candidate outputs for a single model input.
partial: Whether to parse the output as a partial result. This is useful
for parsers that can parse partial results. Default is False.
for parsers that can parse partial results.
Returns:
Structured output.
@@ -264,20 +264,20 @@ class BaseOutputParser(
async def aparse_result(
self, result: list[Generation], *, partial: bool = False
) -> T:
"""Async parse a list of candidate model Generations into a specific format.
"""Async parse a list of candidate model `Generation` objects into a specific format.
The return value is parsed from only the first Generation in the result, which
is assumed to be the highest-likelihood Generation.
The return value is parsed from only the first `Generation` in the result, which
is assumed to be the highest-likelihood `Generation`.
Args:
result: A list of Generations to be parsed. The Generations are assumed
to be different candidate outputs for a single model input.
result: A list of `Generation` to be parsed. The `Generation` objects are
assumed to be different candidate outputs for a single model input.
partial: Whether to parse the output as a partial result. This is useful
for parsers that can parse partial results. Default is False.
for parsers that can parse partial results.
Returns:
Structured output.
"""
""" # noqa: E501
return await run_in_executor(None, self.parse_result, result, partial=partial)
async def aparse(self, text: str) -> T:
@@ -299,13 +299,13 @@ class BaseOutputParser(
) -> Any:
"""Parse the output of an LLM call with the input prompt for context.
The prompt is largely provided in the event the OutputParser wants
The prompt is largely provided in the event the `OutputParser` wants
to retry or fix the output in some way, and needs information from
the prompt to do so.
Args:
completion: String output of a language model.
prompt: Input PromptValue.
prompt: Input `PromptValue`.
Returns:
Structured output.
@@ -62,7 +62,6 @@ class JsonOutputParser(BaseCumulativeTransformOutputParser[Any]):
If `True`, the output will be a JSON object containing
all the keys that have been returned so far.
If `False`, the output will be the full JSON object.
Default is False.
Returns:
The parsed JSON object.
@@ -146,7 +146,7 @@ class CommaSeparatedListOutputParser(ListOutputParser):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "output_parsers", "list"]`
@@ -31,10 +31,9 @@ def parse_tool_call(
Args:
raw_tool_call: The raw tool call to parse.
partial: Whether to parse partial JSON. Default is False.
partial: Whether to parse partial JSON.
strict: Whether to allow non-JSON-compliant strings.
Default is False.
return_id: Whether to return the tool call id. Default is True.
return_id: Whether to return the tool call id.
Returns:
The parsed tool call.
@@ -105,10 +104,9 @@ def parse_tool_calls(
Args:
raw_tool_calls: The raw tool calls to parse.
partial: Whether to parse partial JSON. Default is False.
partial: Whether to parse partial JSON.
strict: Whether to allow non-JSON-compliant strings.
Default is False.
return_id: Whether to return the tool call id. Default is True.
return_id: Whether to return the tool call id.
Returns:
The parsed tool calls.
@@ -165,7 +163,6 @@ class JsonOutputToolsParser(BaseCumulativeTransformOutputParser[Any]):
If `True`, the output will be a JSON object containing
all the keys that have been returned so far.
If `False`, the output will be the full JSON object.
Default is False.
Returns:
The parsed tool calls.
@@ -229,7 +226,6 @@ class JsonOutputKeyToolsParser(JsonOutputToolsParser):
If `True`, the output will be a JSON object containing
all the keys that have been returned so far.
If `False`, the output will be the full JSON object.
Default is False.
Raises:
OutputParserException: If the generation is not a chat generation.
@@ -313,7 +309,6 @@ class PydanticToolsParser(JsonOutputToolsParser):
If `True`, the output will be a JSON object containing
all the keys that have been returned so far.
If `False`, the output will be the full JSON object.
Default is False.
Returns:
The parsed Pydantic objects.
@@ -19,7 +19,7 @@ class StrOutputParser(BaseTransformOutputParser[str]):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "output_parser"]`
@@ -44,7 +44,7 @@ class Generation(Serializable):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "output"]`
+7 -7
View File
@@ -24,8 +24,8 @@ from langchain_core.messages import (
class PromptValue(Serializable, ABC):
"""Base abstract class for inputs to any language model.
PromptValues can be converted to both LLM (pure text-generation) inputs and
ChatModel inputs.
`PromptValues` can be converted to both LLM (pure text-generation) inputs and
chat model inputs.
"""
@classmethod
@@ -35,7 +35,7 @@ class PromptValue(Serializable, ABC):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
This is used to determine the namespace of the object when serializing.
@@ -62,7 +62,7 @@ class StringPromptValue(PromptValue):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
This is used to determine the namespace of the object when serializing.
@@ -99,7 +99,7 @@ class ChatPromptValue(PromptValue):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
This is used to determine the namespace of the object when serializing.
@@ -113,11 +113,11 @@ class ImageURL(TypedDict, total=False):
"""Image URL."""
detail: Literal["auto", "low", "high"]
"""Specifies the detail level of the image. Defaults to `'auto'`.
"""Specifies the detail level of the image.
Can be `'auto'`, `'low'`, or `'high'`.
This follows OpenAI's Chat Completion API's image URL format.
"""
url: str
+4 -4
View File
@@ -96,7 +96,7 @@ class BasePromptTemplate(
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "prompt_template"]`
@@ -343,9 +343,9 @@ class BasePromptTemplate(
file_path: Path to directory to save prompt to.
Raises:
ValueError: If the prompt has partial variables.
ValueError: If the file path is not json or yaml.
NotImplementedError: If the prompt type is not implemented.
`ValueError`: If the prompt has partial variables.
`ValueError`: If the file path is not json or yaml.
`NotImplementedError`: If the prompt type is not implemented.
Example:
```python
+12 -13
View File
@@ -147,7 +147,6 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
optional: If `True` format_messages can be called with no arguments and will
return an empty list. If `False` then a named argument with name
`variable_name` must be passed in, even if the value is an empty list.
Defaults to `False`.]
"""
# mypy can't detect the init which is defined in the parent class
# b/c these are BaseModel classes.
@@ -195,7 +194,7 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
"""Human-readable representation.
Args:
html: Whether to format as HTML. Defaults to `False`.
html: Whether to format as HTML.
Returns:
Human-readable representation.
@@ -235,7 +234,7 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
Args:
template: a template.
template_format: format of the template. Defaults to "f-string".
template_format: format of the template.
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
@@ -330,7 +329,7 @@ class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
"""Human-readable representation.
Args:
html: Whether to format as HTML. Defaults to `False`.
html: Whether to format as HTML.
Returns:
Human-readable representation.
@@ -412,7 +411,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
Args:
template: a template.
template_format: format of the template.
Options are: 'f-string', 'mustache', 'jinja2'. Defaults to "f-string".
Options are: 'f-string', 'mustache', 'jinja2'.
partial_variables: A dictionary of variables that can be used too partially.
**kwargs: keyword arguments to pass to the constructor.
@@ -637,7 +636,7 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
"""Human-readable representation.
Args:
html: Whether to format as HTML. Defaults to `False`.
html: Whether to format as HTML.
Returns:
Human-readable representation.
@@ -750,7 +749,7 @@ class BaseChatPromptTemplate(BasePromptTemplate, ABC):
"""Human-readable representation.
Args:
html: Whether to format as HTML. Defaults to `False`.
html: Whether to format as HTML.
Returns:
Human-readable representation.
@@ -905,7 +904,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
(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".
template_format: format of the template.
input_variables: A list of the names of the variables whose values are
required as inputs to the prompt.
optional_variables: A list of the names of the variables for placeholder
@@ -971,7 +970,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "prompts", "chat"]`
@@ -1128,7 +1127,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
(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".
template_format: format of the template.
Returns:
a chat prompt template.
@@ -1287,7 +1286,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
"""Human-readable representation.
Args:
html: Whether to format as HTML. Defaults to `False`.
html: Whether to format as HTML.
Returns:
Human-readable representation.
@@ -1306,7 +1305,7 @@ def _create_template_from_message_type(
Args:
message_type: str the type of the message template (e.g., "human", "ai", etc.)
template: str the template string.
template_format: format of the template. Defaults to "f-string".
template_format: format of the template.
Returns:
a message prompt template of the appropriate type.
@@ -1383,7 +1382,7 @@ def _convert_to_message_template(
Args:
message: a representation of a message in one of the supported formats.
template_format: format of the template. Defaults to "f-string".
template_format: format of the template.
Returns:
an instance of a message or a message template.
+2 -2
View File
@@ -74,7 +74,7 @@ class DictPromptTemplate(RunnableSerializable[dict, dict]):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain_core", "prompts", "dict"]`
@@ -85,7 +85,7 @@ class DictPromptTemplate(RunnableSerializable[dict, dict]):
"""Human-readable representation.
Args:
html: Whether to format as HTML. Defaults to `False`.
html: Whether to format as HTML.
Returns:
Human-readable representation.
@@ -46,7 +46,7 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "prompts", "few_shot_with_templates"]`
+1 -1
View File
@@ -49,7 +49,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "prompts", "image"]`
+2 -2
View File
@@ -23,7 +23,7 @@ class BaseMessagePromptTemplate(Serializable, ABC):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "prompts", "chat"]`
@@ -68,7 +68,7 @@ class BaseMessagePromptTemplate(Serializable, ABC):
"""Human-readable representation.
Args:
html: Whether to format as HTML. Defaults to `False`.
html: Whether to format as HTML.
Returns:
Human-readable representation.
+9 -10
View File
@@ -66,7 +66,7 @@ class PromptTemplate(StringPromptTemplate):
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "prompts", "prompt"]`
@@ -140,9 +140,9 @@ class PromptTemplate(StringPromptTemplate):
"""Override the + operator to allow for combining prompt templates.
Raises:
ValueError: If the template formats are not f-string or if there are
`ValueError`: If the template formats are not f-string or if there are
conflicting partial variables.
NotImplementedError: If the other object is not a `PromptTemplate` or str.
`NotImplementedError`: If the other object is not a `PromptTemplate` or str.
Returns:
A new `PromptTemplate` that is the combination of the two.
@@ -220,7 +220,7 @@ class PromptTemplate(StringPromptTemplate):
example_separator: The separator to use in between examples. Defaults
to two new line characters.
prefix: String that should go before any examples. Generally includes
examples. Default to an empty string.
examples.
Returns:
The final prompt generated.
@@ -275,13 +275,12 @@ class PromptTemplate(StringPromptTemplate):
Args:
template: The template to load.
template_format: The format of the template. Use `jinja2` for jinja2,
`mustache` for mustache, and `f-string` for f-strings.
Defaults to `f-string`.
`mustache` for mustache, and `f-string` for f-strings.
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}"`.
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}"`.
**kwargs: Any other arguments to pass to the prompt template.
Returns:
+1 -1
View File
@@ -276,7 +276,7 @@ class StringPromptTemplate(BasePromptTemplate, ABC):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "prompts", "base"]`
@@ -63,13 +63,13 @@ class StructuredPrompt(ChatPromptTemplate):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
For example, if the class is `langchain.llms.openai.OpenAI`, then the
namespace is `["langchain", "llms", "openai"]`
Returns:
The namespace of the langchain object.
The namespace of the LangChain object.
"""
return cls.__module__.split(".")
@@ -150,7 +150,7 @@ class StructuredPrompt(ChatPromptTemplate):
A RunnableSequence object.
Raises:
NotImplementedError: If the first element of `others`
`NotImplementedError`: If the first element of `others`
is not a language model.
"""
if (others and isinstance(others[0], BaseLanguageModel)) or hasattr(
+23 -23
View File
@@ -21,8 +21,8 @@ class BaseRateLimiter(abc.ABC):
Current limitations:
- Rate limiting information is not surfaced in tracing or callbacks. This means
that the total time it takes to invoke a chat model will encompass both
the time spent waiting for tokens and the time spent making the request.
that the total time it takes to invoke a chat model will encompass both
the time spent waiting for tokens and the time spent making the request.
!!! version-added "Added in version 0.2.24"
@@ -33,18 +33,18 @@ class BaseRateLimiter(abc.ABC):
"""Attempt to acquire the necessary tokens for the rate limiter.
This method blocks until the required tokens are available if `blocking`
is set to True.
is set to `True`.
If `blocking` is set to False, the method will immediately return the result
If `blocking` is set to `False`, the method will immediately return the result
of the attempt to acquire the tokens.
Args:
blocking: If `True`, the method will block until the tokens are available.
If `False`, the method will return immediately with the result of
the attempt. Defaults to `True`.
the attempt.
Returns:
`True` if the tokens were successfully acquired, `False` otherwise.
`True` if the tokens were successfully acquired, `False` otherwise.
"""
@abc.abstractmethod
@@ -52,18 +52,18 @@ class BaseRateLimiter(abc.ABC):
"""Attempt to acquire the necessary tokens for the rate limiter.
This method blocks until the required tokens are available if `blocking`
is set to True.
is set to `True`.
If `blocking` is set to False, the method will immediately return the result
If `blocking` is set to `False`, the method will immediately return the result
of the attempt to acquire the tokens.
Args:
blocking: If `True`, the method will block until the tokens are available.
If `False`, the method will return immediately with the result of
the attempt. Defaults to `True`.
the attempt.
Returns:
`True` if the tokens were successfully acquired, `False` otherwise.
`True` if the tokens were successfully acquired, `False` otherwise.
"""
@@ -84,7 +84,7 @@ class InMemoryRateLimiter(BaseRateLimiter):
not enough tokens in the bucket, the request is blocked until there are
enough tokens.
These *tokens* have NOTHING to do with LLM tokens. They are just
These tokens have nothing to do with LLM tokens. They are just
a way to keep track of how many requests can be made at a given time.
Current limitations:
@@ -109,7 +109,7 @@ class InMemoryRateLimiter(BaseRateLimiter):
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(
model_name="claude-3-opus-20240229", rate_limiter=rate_limiter
model_name="claude-sonnet-4-5-20250929", rate_limiter=rate_limiter
)
for _ in range(5):
@@ -132,7 +132,7 @@ class InMemoryRateLimiter(BaseRateLimiter):
) -> None:
"""A rate limiter based on a token bucket.
These *tokens* have NOTHING to do with LLM tokens. They are just
These tokens have nothing to do with LLM tokens. They are just
a way to keep track of how many requests can be made at a given time.
This rate limiter is designed to work in a threaded environment.
@@ -145,11 +145,11 @@ class InMemoryRateLimiter(BaseRateLimiter):
Args:
requests_per_second: The number of tokens to add per second to the bucket.
The tokens represent "credit" that can be used to make requests.
check_every_n_seconds: check whether the tokens are available
check_every_n_seconds: Check whether the tokens are available
every this many seconds. Can be a float to represent
fractions of a second.
max_bucket_size: The maximum number of tokens that can be in the bucket.
Must be at least 1. Used to prevent bursts of requests.
Must be at least `1`. Used to prevent bursts of requests.
"""
# Number of requests that we can make per second.
self.requests_per_second = requests_per_second
@@ -199,18 +199,18 @@ class InMemoryRateLimiter(BaseRateLimiter):
"""Attempt to acquire a token from the rate limiter.
This method blocks until the required tokens are available if `blocking`
is set to True.
is set to `True`.
If `blocking` is set to False, the method will immediately return the result
If `blocking` is set to `False`, the method will immediately return the result
of the attempt to acquire the tokens.
Args:
blocking: If `True`, the method will block until the tokens are available.
If `False`, the method will return immediately with the result of
the attempt. Defaults to `True`.
the attempt.
Returns:
`True` if the tokens were successfully acquired, `False` otherwise.
`True` if the tokens were successfully acquired, `False` otherwise.
"""
if not blocking:
return self._consume()
@@ -223,18 +223,18 @@ class InMemoryRateLimiter(BaseRateLimiter):
"""Attempt to acquire a token from the rate limiter. Async version.
This method blocks until the required tokens are available if `blocking`
is set to True.
is set to `True`.
If `blocking` is set to False, the method will immediately return the result
If `blocking` is set to `False`, the method will immediately return the result
of the attempt to acquire the tokens.
Args:
blocking: If `True`, the method will block until the tokens are available.
If `False`, the method will return immediately with the result of
the attempt. Defaults to `True`.
the attempt.
Returns:
`True` if the tokens were successfully acquired, `False` otherwise.
`True` if the tokens were successfully acquired, `False` otherwise.
"""
if not blocking:
return self._consume()
+29 -29
View File
@@ -70,45 +70,45 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):
Example: A retriever that returns the first 5 documents from a list of documents
```python
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
```python
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
class SimpleRetriever(BaseRetriever):
docs: list[Document]
k: int = 5
class SimpleRetriever(BaseRetriever):
docs: list[Document]
k: int = 5
def _get_relevant_documents(self, query: str) -> list[Document]:
\"\"\"Return the first k documents from the list of documents\"\"\"
return self.docs[:self.k]
def _get_relevant_documents(self, query: str) -> list[Document]:
\"\"\"Return the first k documents from the list of documents\"\"\"
return self.docs[:self.k]
async def _aget_relevant_documents(self, query: str) -> list[Document]:
\"\"\"(Optional) async native implementation.\"\"\"
return self.docs[:self.k]
```
async def _aget_relevant_documents(self, query: str) -> list[Document]:
\"\"\"(Optional) async native implementation.\"\"\"
return self.docs[:self.k]
```
Example: A simple retriever based on a scikit-learn vectorizer
```python
from sklearn.metrics.pairwise import cosine_similarity
```python
from sklearn.metrics.pairwise import cosine_similarity
class TFIDFRetriever(BaseRetriever, BaseModel):
vectorizer: Any
docs: list[Document]
tfidf_array: Any
k: int = 4
class TFIDFRetriever(BaseRetriever, BaseModel):
vectorizer: Any
docs: list[Document]
tfidf_array: Any
k: int = 4
class Config:
arbitrary_types_allowed = True
class Config:
arbitrary_types_allowed = True
def _get_relevant_documents(self, query: str) -> list[Document]:
# Ip -- (n_docs,x), Op -- (n_docs,n_Feats)
query_vec = self.vectorizer.transform([query])
# Op -- (n_docs,1) -- Cosine Sim with each doc
results = cosine_similarity(self.tfidf_array, query_vec).reshape((-1,))
return [self.docs[i] for i in results.argsort()[-self.k :][::-1]]
```
def _get_relevant_documents(self, query: str) -> list[Document]:
# Ip -- (n_docs,x), Op -- (n_docs,n_Feats)
query_vec = self.vectorizer.transform([query])
# Op -- (n_docs,1) -- Cosine Sim with each doc
results = cosine_similarity(self.tfidf_array, query_vec).reshape((-1,))
return [self.docs[i] for i in results.argsort()[-self.k :][::-1]]
```
"""
model_config = ConfigDict(
+10 -17
View File
@@ -871,7 +871,6 @@ class Runnable(ABC, Generic[Input, Output]):
to do in parallel, and other keys. Please refer to the
`RunnableConfig` for more details.
return_exceptions: Whether to return exceptions instead of raising them.
Defaults to `False`.
**kwargs: Additional keyword arguments to pass to the `Runnable`.
Returns:
@@ -938,7 +937,6 @@ class Runnable(ABC, Generic[Input, Output]):
do in parallel, and other keys. Please refer to the `RunnableConfig`
for more details.
return_exceptions: Whether to return exceptions instead of raising them.
Defaults to `False`.
**kwargs: Additional keyword arguments to pass to the `Runnable`.
Yields:
@@ -1005,7 +1003,6 @@ class Runnable(ABC, Generic[Input, Output]):
do in parallel, and other keys. Please refer to the `RunnableConfig`
for more details.
return_exceptions: Whether to return exceptions instead of raising them.
Defaults to `False`.
**kwargs: Additional keyword arguments to pass to the `Runnable`.
Returns:
@@ -1069,7 +1066,6 @@ class Runnable(ABC, Generic[Input, Output]):
do in parallel, and other keys. Please refer to the `RunnableConfig`
for more details.
return_exceptions: Whether to return exceptions instead of raising them.
Defaults to `False`.
**kwargs: Additional keyword arguments to pass to the `Runnable`.
Yields:
@@ -1357,7 +1353,8 @@ class Runnable(ABC, Generic[Input, Output]):
).with_config({"run_name": "my_template", "tags": ["my_template"]})
```
Example:
For instance:
```python
from langchain_core.runnables import RunnableLambda
@@ -1451,7 +1448,7 @@ class Runnable(ABC, Generic[Input, Output]):
An async stream of `StreamEvent`.
Raises:
NotImplementedError: If the version is not `'v1'` or `'v2'`.
`NotImplementedError`: If the version is not `'v1'` or `'v2'`.
""" # noqa: E501
if version == "v2":
@@ -1837,11 +1834,10 @@ class Runnable(ABC, Generic[Input, Output]):
Args:
retry_if_exception_type: A tuple of exception types to retry on.
Defaults to (Exception,).
wait_exponential_jitter: Whether to add jitter to the wait
time between retries. Defaults to `True`.
time between retries.
stop_after_attempt: The maximum number of attempts to make before
giving up. Defaults to 3.
giving up.
exponential_jitter_params: Parameters for
`tenacity.wait_exponential_jitter`. Namely: `initial`, `max`,
`exp_base`, and `jitter` (all float values).
@@ -1929,7 +1925,6 @@ 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,)`.
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.
@@ -2633,9 +2628,7 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
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.
Defaults to `False`.
**kwargs: A dictionary of keys to `Runnable` instances or callables that
return `Runnable` instances.
@@ -2896,7 +2889,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
@@ -3627,7 +3620,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
@@ -5156,7 +5149,7 @@ class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
@@ -5479,7 +5472,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
@@ -5761,7 +5754,7 @@ class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-re
`bind`: Bind kwargs to pass to the underlying `Runnable` when running it.
```python
# Create a Runnable binding that invokes the ChatModel with the
# Create a Runnable binding that invokes the chat model with the
# additional kwarg `stop=['-']` when running it.
from langchain_community.chat_models import ChatOpenAI
+1 -1
View File
@@ -146,7 +146,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
+1 -1
View File
@@ -536,7 +536,7 @@ class ContextThreadPoolExecutor(ThreadPoolExecutor):
fn: The function to map.
*iterables: The iterables to map over.
timeout: The timeout for the map.
chunksize: The chunksize for the map. Defaults to 1.
chunksize: The chunksize for the map.
Returns:
The iterator for the mapped function.
@@ -72,7 +72,7 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
@@ -540,7 +540,7 @@ class RunnableConfigurableAlternatives(DynamicRunnable[Input, Output]):
"""The alternatives to choose from."""
default_key: str = "default"
"""The enum value to use for the default option. Defaults to `'default'`."""
"""The enum value to use for the default option."""
prefix_keys: bool
"""Whether to prefix configurable fields of each alternative with a namespace
@@ -143,7 +143,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
+23 -28
View File
@@ -71,7 +71,7 @@ class Edge(NamedTuple):
data: Stringifiable | None = None
"""Optional data associated with the edge. """
conditional: bool = False
"""Whether the edge is conditional. Defaults to `False`."""
"""Whether the edge is conditional."""
def copy(self, *, source: str | None = None, target: str | None = None) -> Edge:
"""Return a copy of the edge with optional new source and target nodes.
@@ -157,9 +157,9 @@ class NodeStyles:
"""Schema for Hexadecimal color codes for different node types.
Args:
default: The default color code. Defaults to "fill:#f2f0ff,line-height:1.2".
first: The color code for the first node. Defaults to "fill-opacity:0".
last: The color code for the last node. Defaults to "fill:#bfb6fc".
default: The default color code.
first: The color code for the first node.
last: The color code for the last node.
"""
default: str = "fill:#f2f0ff,line-height:1.2"
@@ -201,9 +201,9 @@ def node_data_json(
"""Convert the data of a node to a JSON-serializable format.
Args:
node: The node to convert.
with_schemas: Whether to include the schema of the data if
it is a Pydantic model. Defaults to `False`.
node: The `Node` to convert.
with_schemas: Whether to include the schema of the data if it is a Pydantic
model.
Returns:
A dictionary with the type of the data and the data itself.
@@ -267,7 +267,7 @@ class Graph:
Args:
with_schemas: Whether to include the schemas of the nodes if they are
Pydantic models. Defaults to `False`.
Pydantic models.
Returns:
A dictionary with the nodes and edges of the graph.
@@ -362,7 +362,7 @@ class Graph:
source: The source node of the edge.
target: The target node of the edge.
data: Optional data associated with the edge.
conditional: Whether the edge is conditional. Defaults to `False`.
conditional: Whether the edge is conditional.
Returns:
The edge that was added to the graph.
@@ -391,7 +391,7 @@ class Graph:
Args:
graph: The graph to add.
prefix: The prefix to add to the node ids. Defaults to "".
prefix: The prefix to add to the node ids.
Returns:
A tuple of the first and last nodes of the subgraph.
@@ -458,7 +458,7 @@ class Graph:
def first_node(self) -> Node | None:
"""Find the single node that is not a target of any edge.
If there is no such node, or there are multiple, return None.
If there is no such node, or there are multiple, return `None`.
When drawing the graph, this node would be the origin.
Returns:
@@ -470,7 +470,7 @@ class Graph:
def last_node(self) -> Node | None:
"""Find the single node that is not a source of any edge.
If there is no such node, or there are multiple, return None.
If there is no such node, or there are multiple, return `None`.
When drawing the graph, this node would be the destination.
Returns:
@@ -585,11 +585,10 @@ class Graph:
"""Draw the graph as a Mermaid syntax string.
Args:
with_styles: Whether to include styles in the syntax. Defaults to `True`.
curve_style: The style of the edges. Defaults to CurveStyle.LINEAR.
node_colors: The colors of the nodes. Defaults to NodeStyles().
with_styles: Whether to include styles in the syntax.
curve_style: The style of the edges.
node_colors: The colors of the nodes.
wrap_label_n_words: The number of words to wrap the node labels at.
Defaults to 9.
frontmatter_config: Mermaid frontmatter config.
Can be used to customize theme and styles. Will be converted to YAML and
added to the beginning of the mermaid graph.
@@ -647,20 +646,16 @@ class Graph:
"""Draw the graph as a PNG image using Mermaid.
Args:
curve_style: The style of the edges. Defaults to CurveStyle.LINEAR.
node_colors: The colors of the nodes. Defaults to NodeStyles().
curve_style: The style of the edges.
node_colors: The colors of the nodes.
wrap_label_n_words: The number of words to wrap the node labels at.
Defaults to 9.
output_file_path: The path to save the image to. If `None`, the image
is not saved.
draw_method: The method to use to draw the graph.
Defaults to MermaidDrawMethod.API.
background_color: The color of the background. Defaults to "white".
padding: The padding around the graph. Defaults to 10.
max_retries: The maximum number of retries (MermaidDrawMethod.API).
Defaults to 1.
retry_delay: The delay between retries (MermaidDrawMethod.API).
Defaults to 1.0.
background_color: The color of the background.
padding: The padding around the graph.
max_retries: The maximum number of retries (`MermaidDrawMethod.API`).
retry_delay: The delay between retries (`MermaidDrawMethod.API`).
frontmatter_config: Mermaid frontmatter config.
Can be used to customize theme and styles. Will be converted to YAML and
added to the beginning of the mermaid graph.
@@ -712,7 +707,7 @@ def _first_node(graph: Graph, exclude: Sequence[str] = ()) -> Node | None:
"""Find the single node that is not a target of any edge.
Exclude nodes/sources with ids in the exclude list.
If there is no such node, or there are multiple, return None.
If there is no such node, or there are multiple, return `None`.
When drawing the graph, this node would be the origin.
"""
targets = {edge.target for edge in graph.edges if edge.source not in exclude}
@@ -728,7 +723,7 @@ def _last_node(graph: Graph, exclude: Sequence[str] = ()) -> Node | None:
"""Find the single node that is not a source of any edge.
Exclude nodes/targets with ids in the exclude list.
If there is no such node, or there are multiple, return None.
If there is no such node, or there are multiple, return `None`.
When drawing the graph, this node would be the destination.
"""
sources = {edge.source for edge in graph.edges if edge.target not in exclude}
@@ -60,10 +60,10 @@ def draw_mermaid(
edges: List of edges, object with a source, target and data.
first_node: Id of the first node.
last_node: Id of the last node.
with_styles: Whether to include styles in the graph. Defaults to `True`.
curve_style: Curve style for the edges. Defaults to CurveStyle.LINEAR.
node_styles: Node colors for different types. Defaults to NodeStyles().
wrap_label_n_words: Words to wrap the edge labels. Defaults to 9.
with_styles: Whether to include styles in the graph.
curve_style: Curve style for the edges.
node_styles: Node colors for different types.
wrap_label_n_words: Words to wrap the edge labels.
frontmatter_config: Mermaid frontmatter config.
Can be used to customize theme and styles. Will be converted to YAML and
added to the beginning of the mermaid graph.
@@ -287,11 +287,11 @@ def draw_mermaid_png(
Args:
mermaid_syntax: Mermaid graph syntax.
output_file_path: Path to save the PNG image.
draw_method: Method to draw the graph. Defaults to MermaidDrawMethod.API.
background_color: Background color of the image. Defaults to "white".
padding: Padding around the image. Defaults to 10.
max_retries: Maximum number of retries (MermaidDrawMethod.API). Defaults to 1.
retry_delay: Delay between retries (MermaidDrawMethod.API). Defaults to 1.0.
draw_method: Method to draw the graph.
background_color: Background color of the image.
padding: Padding around the image.
max_retries: Maximum number of retries (MermaidDrawMethod.API).
retry_delay: Delay between retries (MermaidDrawMethod.API).
base_url: Base URL for the Mermaid.ink API.
Returns:
@@ -105,7 +105,7 @@ class PngDrawer:
source: The source node.
target: The target node.
label: The label for the edge.
conditional: Whether the edge is conditional. Defaults to `False`.
conditional: Whether the edge is conditional.
"""
viz.add_edge(
source,
@@ -296,9 +296,9 @@ class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
```
input_messages_key: Must be specified if the base runnable accepts a dict
as input. Default is None.
as input.
output_messages_key: Must be specified if the base runnable returns a dict
as output. Default is None.
as output.
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
@@ -185,7 +185,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
@@ -409,7 +409,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
@@ -714,7 +714,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
+1 -1
View File
@@ -96,7 +96,7 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
@classmethod
@override
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the langchain object.
"""Get the namespace of the LangChain object.
Returns:
`["langchain", "schema", "runnable"]`
+5 -5
View File
@@ -136,7 +136,7 @@ def coro_with_context(
Args:
coro: The coroutine to await.
context: The context to use.
create_task: Whether to create a task. Defaults to `False`.
create_task: Whether to create a task.
Returns:
The coroutine with the context.
@@ -558,7 +558,7 @@ class ConfigurableField(NamedTuple):
annotation: Any | None = None
"""The annotation of the field. """
is_shared: bool = False
"""Whether the field is shared. Defaults to `False`."""
"""Whether the field is shared."""
@override
def __hash__(self) -> int:
@@ -579,7 +579,7 @@ class ConfigurableFieldSingleOption(NamedTuple):
description: str | None = None
"""The description of the field. """
is_shared: bool = False
"""Whether the field is shared. Defaults to `False`."""
"""Whether the field is shared."""
@override
def __hash__(self) -> int:
@@ -600,7 +600,7 @@ class ConfigurableFieldMultiOption(NamedTuple):
description: str | None = None
"""The description of the field. """
is_shared: bool = False
"""Whether the field is shared. Defaults to `False`."""
"""Whether the field is shared."""
@override
def __hash__(self) -> int:
@@ -626,7 +626,7 @@ class ConfigurableFieldSpec(NamedTuple):
default: Any = None
"""The default value for the field. """
is_shared: bool = False
"""Whether the field is shared. Defaults to `False`."""
"""Whether the field is shared."""
dependencies: list[str] | None = None
"""The dependencies of the field. """
+10 -11
View File
@@ -248,7 +248,7 @@ def _function_annotations_are_pydantic_v1(
True if all Pydantic annotations are from V1, `False` otherwise.
Raises:
NotImplementedError: If the function contains mixed V1 and V2 annotations.
`NotImplementedError`: If the function contains mixed V1 and V2 annotations.
"""
any_v1_annotations = any(
_is_pydantic_annotation(parameter.annotation, pydantic_version="v1")
@@ -293,10 +293,9 @@ def create_schema_from_function(
filter_args: Optional list of arguments to exclude from the schema.
Defaults to `FILTERED_ARGS`.
parse_docstring: Whether to parse the function's docstring for descriptions
for each argument. Defaults to `False`.
for each argument.
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.
Defaults to `True`, since we want to include them in the schema
when *validating* tool inputs.
@@ -481,11 +480,11 @@ class ChildTool(BaseTool):
"""Handle the content of the ValidationError thrown."""
response_format: Literal["content", "content_and_artifact"] = "content"
"""The tool response format. Defaults to 'content'.
"""The tool response format.
If "content" then the output of the tool is interpreted as the contents of a
ToolMessage. If "content_and_artifact" then the output is expected to be a
two-tuple corresponding to the (content, artifact) of a ToolMessage.
If `"content"` then the output of the tool is interpreted as the contents of a
ToolMessage. If `"content_and_artifact"` then the output is expected to be a
two-tuple corresponding to the (content, artifact) of a `ToolMessage`.
"""
def __init__(self, **kwargs: Any) -> None:
@@ -768,8 +767,8 @@ class ChildTool(BaseTool):
Args:
tool_input: The input to the tool.
verbose: Whether to log the tool's progress.
start_color: The color to use when starting the tool. Defaults to 'green'.
color: The color to use when ending the tool. Defaults to 'green'.
start_color: The color to use when starting the tool.
color: The color to use when ending the tool.
callbacks: Callbacks to be called during tool execution.
tags: Optional list of tags associated with the tool.
metadata: Optional metadata associated with the tool.
@@ -880,8 +879,8 @@ class ChildTool(BaseTool):
Args:
tool_input: The input to the tool.
verbose: Whether to log the tool's progress.
start_color: The color to use when starting the tool. Defaults to 'green'.
color: The color to use when ending the tool. Defaults to 'green'.
start_color: The color to use when starting the tool.
color: The color to use when ending the tool.
callbacks: Callbacks to be called during tool execution.
tags: Optional list of tags associated with the tool.
metadata: Optional metadata associated with the tool.
+13 -17
View File
@@ -81,7 +81,7 @@ def tool(
parse_docstring: bool = False,
error_on_invalid_docstring: bool = True,
) -> BaseTool | Callable[[Callable | Runnable], BaseTool]:
"""Make tools out of functions, can be used with or without arguments.
"""Make tools out of Python functions, can be used with or without arguments.
Args:
name_or_callable: Optional name of the tool or the callable to be
@@ -93,30 +93,26 @@ def tool(
- `description` argument
(used even if docstring and/or `args_schema` are provided)
- tool function docstring
- Tool function docstring
(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
than continuing the agent loop. Defaults to `False`.
args_schema: optional argument schema for user to specify.
than continuing the agent loop.
args_schema: Optional argument schema for user to specify.
infer_schema: Whether to infer the schema of the arguments from
the function's signature. This also makes the resultant tool
accept a dictionary input to its `run()` function.
Defaults to `True`.
response_format: The tool response format. If "content" then the output of
the tool is interpreted as the contents of a ToolMessage. If
"content_and_artifact" then the output is expected to be a two-tuple
corresponding to the (content, artifact) of a ToolMessage.
Defaults to "content".
response_format: The tool response format. If `"content"` then the output of
the tool is interpreted as the contents of a `ToolMessage`. If
`"content_and_artifact"` then the output is expected to be a two-tuple
corresponding to the `(content, artifact)` of a `ToolMessage`.
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
whether to raise ValueError on invalid Google Style docstrings.
Defaults to `True`.
whether to raise `ValueError` on invalid Google Style docstrings.
Raises:
ValueError: If too many positional arguments are provided.
@@ -124,8 +120,8 @@ def tool(
ValueError: If the first argument is not a string or callable with
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
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.
@@ -133,7 +129,7 @@ def tool(
The tool.
Requires:
- Function must be of type (str) -> str
- Function must be of type `(str) -> str`
- Function must have a docstring
Examples:
@@ -197,7 +193,7 @@ def tool(
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:
a summary and `"Args:"` blocks. Examples below:
```python
# No args section
+6 -6
View File
@@ -82,12 +82,12 @@ def create_retriever_tool(
description: The description for the tool. This will be passed to the language
model, so should be descriptive.
document_prompt: The prompt to use for the document.
document_separator: The separator to use between documents. Defaults to "\n\n".
response_format: The tool response format. If "content" then the output of
the tool is interpreted as the contents of a ToolMessage. If
"content_and_artifact" then the output is expected to be a two-tuple
corresponding to the (content, artifact) of a ToolMessage (artifact
being a list of documents in this case). Defaults to "content".
document_separator: The separator to use between documents.
response_format: The tool response format. If `"content"` then the output of
the tool is interpreted as the contents of a `ToolMessage`. If
`"content_and_artifact"` then the output is expected to be a two-tuple
corresponding to the `(content, artifact)` of a `ToolMessage` (artifact
being a list of documents in this case).
Returns:
Tool class to pass to an agent.
+1 -1
View File
@@ -176,7 +176,7 @@ class Tool(BaseTool):
func: The function to create the tool from.
name: The name of the tool.
description: The description of the tool.
return_direct: Whether to return the output directly. Defaults to `False`.
return_direct: Whether to return the output directly.
args_schema: The schema of the tool's input arguments.
coroutine: The asynchronous version of the function.
**kwargs: Additional arguments to pass to the tool.
+5 -10
View File
@@ -149,21 +149,16 @@ class StructuredTool(BaseTool):
description: The description of the tool.
Defaults to the function docstring.
return_direct: Whether to return the result directly or as a callback.
Defaults to `False`.
args_schema: The schema of the tool's input arguments.
infer_schema: Whether to infer the schema from the function's signature.
Defaults to `True`.
response_format: The tool response format. If "content" then the output of
the tool is interpreted as the contents of a ToolMessage. If
"content_and_artifact" then the output is expected to be a two-tuple
corresponding to the (content, artifact) of a ToolMessage.
Defaults to "content".
response_format: The tool response format. If `"content"` then the output of
the tool is interpreted as the contents of a `ToolMessage`. If
`"content_and_artifact"` then the output is expected to be a two-tuple
corresponding to the `(content, artifact)` of a `ToolMessage`.
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
whether to raise ValueError on invalid Google Style docstrings.
Defaults to `False`.
whether to raise `ValueError` on invalid Google Style docstrings.
**kwargs: Additional arguments to pass to the tool
Returns:
@@ -5,7 +5,7 @@ channel. The writer and reader can be in the same event loop or in different eve
loops. When they're in different event loops, they will also be in different
threads.
This is useful in situations when there's a mix of synchronous and asynchronous
Useful in situations when there's a mix of synchronous and asynchronous
used in the code.
"""
@@ -24,7 +24,7 @@ class RootListenersTracer(BaseTracer):
"""Tracer that calls listeners on run start, end, and error."""
log_missing_parent = False
"""Whether to log a warning if the parent is missing. Default is False."""
"""Whether to log a warning if the parent is missing."""
def __init__(
self,
@@ -79,7 +79,7 @@ class AsyncRootListenersTracer(AsyncBaseTracer):
"""Async Tracer that calls listeners on run start, end, and error."""
log_missing_parent = False
"""Whether to log a warning if the parent is missing. Default is False."""
"""Whether to log a warning if the parent is missing."""
def __init__(
self,
+1 -2
View File
@@ -49,8 +49,7 @@ class FunctionCallbackHandler(BaseTracer):
"""Tracer that calls a function with a single str parameter."""
name: str = "function_callback_handler"
"""The name of the tracer. This is used to identify the tracer in the logs.
Default is "function_callback_handler"."""
"""The name of the tracer. This is used to identify the tracer in the logs."""
def __init__(self, function: Callable[[str], None], **kwargs: Any) -> None:
"""Create a FunctionCallbackHandler.
+1 -1
View File
@@ -1,4 +1,4 @@
"""**Utility functions** for LangChain.
"""Utility functions for LangChain.
These functions do not depend on any other LangChain module.
"""
+1 -1
View File
@@ -201,7 +201,7 @@ class Tee(Generic[T]):
Args:
iterable: The iterable to split.
n: The number of iterators to create. Defaults to 2.
n: The number of iterators to create.
lock: The lock to synchronise access to the shared buffers.
"""
@@ -114,7 +114,7 @@ def _convert_json_schema_to_openai_function(
used.
description: The description of the function. If not provided, the description
of the schema will be used.
rm_titles: Whether to remove titles from the schema. Defaults to `True`.
rm_titles: Whether to remove titles from the schema.
Returns:
The function description.
@@ -148,7 +148,7 @@ def _convert_pydantic_to_openai_function(
used.
description: The description of the function. If not provided, the description
of the schema will be used.
rm_titles: Whether to remove titles from the schema. Defaults to `True`.
rm_titles: Whether to remove titles from the schema.
Raises:
TypeError: If the model is not a Pydantic model.
@@ -334,11 +334,11 @@ def convert_to_openai_function(
Args:
function:
A dictionary, Pydantic BaseModel class, TypedDict class, a LangChain
Tool object, or a Python function. If a dictionary is passed in, it is
A dictionary, Pydantic `BaseModel` class, `TypedDict` class, a LangChain
`Tool` object, or a Python function. If a dictionary is passed in, it is
assumed to already be a valid OpenAI function, a JSON schema with
top-level 'title' key specified, an Anthropic format
tool, or an Amazon Bedrock Converse format tool.
top-level `title` key specified, an Anthropic format 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
@@ -351,17 +351,8 @@ def convert_to_openai_function(
Raises:
ValueError: If function is not in a supported format.
!!! warning "Behavior changed in 0.2.29"
`strict` arg added.
!!! warning "Behavior changed in 0.3.13"
Support for Anthropic format tools added.
!!! warning "Behavior changed in 0.3.14"
Support for Amazon Bedrock Converse format tools added.
!!! warning "Behavior changed in 0.3.16"
'description' and 'parameters' keys are now optional. Only 'name' is
`description` and `parameters` keys are now optional. Only `name` is
required and guaranteed to be part of the output.
"""
# an Anthropic format tool
@@ -459,16 +450,14 @@ def convert_to_openai_tool(
) -> dict[str, Any]:
"""Convert a tool-like object to an OpenAI tool schema.
OpenAI tool schema reference:
https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools
[OpenAI tool schema reference](https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools)
Args:
tool:
Either a dictionary, a pydantic.BaseModel class, Python function, or
BaseTool. If a dictionary is passed in, it is
assumed to already be a valid OpenAI function, a JSON schema with
top-level 'title' key specified, an Anthropic format
tool, or an Amazon Bedrock Converse format tool.
Either a dictionary, a `pydantic.BaseModel` class, Python function, or
`BaseTool`. If a dictionary is passed in, it is assumed to already be a
valid OpenAI function, a JSON schema with top-level `title` key specified,
an Anthropic format 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
@@ -478,26 +467,14 @@ def convert_to_openai_tool(
A dict version of the passed in tool which is compatible with the
OpenAI tool-calling API.
!!! warning "Behavior changed in 0.2.29"
`strict` arg added.
!!! warning "Behavior changed in 0.3.13"
Support for Anthropic format tools added.
!!! warning "Behavior changed in 0.3.14"
Support for Amazon Bedrock Converse format tools added.
!!! warning "Behavior changed in 0.3.16"
'description' and 'parameters' keys are now optional. Only 'name' is
`description` and `parameters` keys are now optional. Only `name` is
required and guaranteed to be part of the output.
!!! warning "Behavior changed in 0.3.44"
Return OpenAI Responses API-style tools unchanged. This includes
any dict with "type" in "file_search", "function", "computer_use_preview",
"web_search_preview".
!!! warning "Behavior changed in 0.3.61"
Added support for OpenAI's built-in code interpreter and remote MCP tools.
any dict with `"type"` in `"file_search"`, `"function"`,
`"computer_use_preview"`, `"web_search_preview"`.
!!! warning "Behavior changed in 0.3.63"
Added support for OpenAI's image generation built-in tool.
+1 -1
View File
@@ -66,7 +66,7 @@ def print_text(
Args:
text: The text to print.
color: The color to use.
end: The end character to use. Defaults to "".
end: The end character to use.
file: The file to write to.
"""
text_to_print = get_colored_text(text, color) if color else text
+1 -1
View File
@@ -137,7 +137,7 @@ class Tee(Generic[T]):
Args:
iterable: The iterable to split.
n: The number of iterators to create. Defaults to 2.
n: The number of iterators to create.
lock: The lock to synchronise access to the shared buffers.
"""
+1 -1
View File
@@ -51,7 +51,7 @@ def parse_partial_json(s: str, *, strict: bool = False) -> Any:
Args:
s: The JSON string to parse.
strict: Whether to use strict parsing. Defaults to `False`.
strict: Whether to use strict parsing.
Returns:
The parsed JSON object as a Python dictionary.
+1 -1
View File
@@ -57,7 +57,7 @@ def sanitize_for_postgres(text: str, replacement: str = "") -> str:
Args:
text: The text to sanitize.
replacement: String to replace NUL bytes with. Defaults to empty string.
replacement: String to replace NUL bytes with.
Returns:
The sanitized text with NUL bytes removed or replaced.
+14 -25
View File
@@ -109,7 +109,7 @@ class VectorStore(ABC):
"""Delete by vector ID or other criteria.
Args:
ids: List of ids to delete. If `None`, delete all. Default is None.
ids: List of ids to delete. If `None`, delete all.
**kwargs: Other keyword arguments that subclasses might use.
Returns:
@@ -176,7 +176,7 @@ class VectorStore(ABC):
"""Async delete by vector ID or other criteria.
Args:
ids: List of ids to delete. If `None`, delete all. Default is None.
ids: List of ids to delete. If `None`, delete all.
**kwargs: Other keyword arguments that subclasses might use.
Returns:
@@ -197,7 +197,6 @@ class VectorStore(ABC):
Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
Default is None.
ids: Optional list
**kwargs: vectorstore specific parameters.
@@ -365,7 +364,7 @@ class VectorStore(ABC):
Args:
query: Input text.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
**kwargs: Arguments to pass to the search method.
Returns:
@@ -462,7 +461,7 @@ class VectorStore(ABC):
Args:
query: Input text.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
**kwargs: kwargs to be passed to similarity search. Should include:
score_threshold: Optional, a floating point value between 0 to 1 to
filter the resulting set of retrieved docs
@@ -489,7 +488,7 @@ class VectorStore(ABC):
Args:
query: Input text.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
**kwargs: kwargs to be passed to similarity search. Should include:
score_threshold: Optional, a floating point value between 0 to 1 to
filter the resulting set of retrieved docs
@@ -513,7 +512,7 @@ class VectorStore(ABC):
Args:
query: Input text.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
**kwargs: kwargs to be passed to similarity search. Should include:
score_threshold: Optional, a floating point value between 0 to 1 to
filter the resulting set of retrieved docs.
@@ -562,7 +561,7 @@ class VectorStore(ABC):
Args:
query: Input text.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
**kwargs: kwargs to be passed to similarity search. Should include:
score_threshold: Optional, a floating point value between 0 to 1 to
filter the resulting set of retrieved docs
@@ -606,7 +605,7 @@ class VectorStore(ABC):
Args:
query: Input text.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
**kwargs: Arguments to pass to the search method.
Returns:
@@ -624,7 +623,7 @@ class VectorStore(ABC):
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
**kwargs: Arguments to pass to the search method.
Returns:
@@ -639,7 +638,7 @@ class VectorStore(ABC):
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
**kwargs: Arguments to pass to the search method.
Returns:
@@ -667,13 +666,11 @@ class VectorStore(ABC):
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Default is 20.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
**kwargs: Arguments to pass to the search method.
Returns:
@@ -696,13 +693,11 @@ class VectorStore(ABC):
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Default is 20.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
**kwargs: Arguments to pass to the search method.
Returns:
@@ -736,13 +731,11 @@ class VectorStore(ABC):
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Default is 20.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
**kwargs: Arguments to pass to the search method.
Returns:
@@ -765,13 +758,11 @@ class VectorStore(ABC):
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
k: Number of Documents to return.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Default is 20.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
**kwargs: Arguments to pass to the search method.
Returns:
@@ -864,7 +855,6 @@ class VectorStore(ABC):
texts: Texts to add to the vectorstore.
embedding: Embedding function to use.
metadatas: Optional list of metadatas associated with the texts.
Default is None.
ids: Optional list of IDs associated with the texts.
**kwargs: Additional keyword arguments.
@@ -888,7 +878,6 @@ class VectorStore(ABC):
texts: Texts to add to the vectorstore.
embedding: Embedding function to use.
metadatas: Optional list of metadatas associated with the texts.
Default is None.
ids: Optional list of IDs associated with the texts.
**kwargs: Additional keyword arguments.
@@ -112,8 +112,8 @@ def maximal_marginal_relevance(
Args:
query_embedding: The query embedding.
embedding_list: A list of embeddings.
lambda_mult: The lambda parameter for MMR. Default is 0.5.
k: The number of embeddings to return. Default is 4.
lambda_mult: The lambda parameter for MMR.
k: The number of embeddings to return.
Returns:
A list of indices of the embeddings to return.
@@ -26,11 +26,11 @@ class InMemoryCache(BaseCache):
self._cache: dict[tuple[str, str], RETURN_VAL_TYPE] = {}
def lookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None:
"""Look up based on prompt and llm_string."""
"""Look up based on `prompt` and `llm_string`."""
return self._cache.get((prompt, llm_string), None)
def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:
"""Update cache based on prompt and llm_string."""
"""Update cache based on `prompt` and `llm_string`."""
self._cache[prompt, llm_string] = return_val
@override
@@ -15,11 +15,11 @@ class InMemoryCache(BaseCache):
self._cache: dict[tuple[str, str], RETURN_VAL_TYPE] = {}
def lookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None:
"""Look up based on prompt and llm_string."""
"""Look up based on `prompt` and `llm_string`."""
return self._cache.get((prompt, llm_string), None)
def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:
"""Update cache based on prompt and llm_string."""
"""Update cache based on `prompt` and `llm_string`."""
self._cache[prompt, llm_string] = return_val
@override
@@ -68,12 +68,12 @@ class InMemoryCacheBad(BaseCache):
self._cache: dict[tuple[str, str], RETURN_VAL_TYPE] = {}
def lookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None:
"""Look up based on prompt and llm_string."""
"""Look up based on `prompt` and `llm_string`."""
msg = "This code should not be triggered"
raise NotImplementedError(msg)
def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:
"""Update cache based on prompt and llm_string."""
"""Update cache based on `prompt` and `llm_string`."""
msg = "This code should not be triggered"
raise NotImplementedError(msg)
@@ -25,7 +25,7 @@ def test_base_generation_parser() -> None:
"""Parse a list of model Generations into a specific format.
Args:
result: A list of Generations to be parsed. The Generations are assumed
result: A list of `Generation` to be parsed. The Generations are assumed
to be different candidate outputs for a single model input.
Many parsers assume that only a single generation is passed it in.
We will assert for that
@@ -67,7 +67,7 @@ def test_base_transform_output_parser() -> None:
"""Parse a list of model Generations into a specific format.
Args:
result: A list of Generations to be parsed. The Generations are assumed
result: A list of `Generation` to be parsed. The Generations are assumed
to be different candidate outputs for a single model input.
Many parsers assume that only a single generation is passed it in.
We will assert for that
@@ -7,7 +7,7 @@
'description': '''
Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -389,7 +389,7 @@
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -1143,7 +1143,7 @@
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -1428,7 +1428,7 @@
'description': '''
Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -1810,7 +1810,7 @@
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -2564,7 +2564,7 @@
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -26,7 +26,7 @@ def _fake_runnable(
class FakeStructuredChatModel(FakeListChatModel):
"""Fake ChatModel for testing purposes."""
"""Fake chat model for testing purposes."""
@override
def with_structured_output(
@@ -431,7 +431,7 @@
'description': '''
Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -813,7 +813,7 @@
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -1567,7 +1567,7 @@
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -1963,7 +1963,7 @@
'description': '''
Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -2340,7 +2340,7 @@
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -3085,7 +3085,7 @@
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -3364,7 +3364,7 @@
'description': '''
Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -3804,7 +3804,7 @@
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -4568,7 +4568,7 @@
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -4859,7 +4859,7 @@
'description': '''
Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -5299,7 +5299,7 @@
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -6063,7 +6063,7 @@
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -6292,7 +6292,7 @@
'description': '''
Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -6669,7 +6669,7 @@
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -7414,7 +7414,7 @@
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -7735,7 +7735,7 @@
'description': '''
Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -8175,7 +8175,7 @@
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -8939,7 +8939,7 @@
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -9213,7 +9213,7 @@
'description': '''
Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -9590,7 +9590,7 @@
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -10335,7 +10335,7 @@
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -10564,7 +10564,7 @@
'description': '''
Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -11004,7 +11004,7 @@
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -11779,7 +11779,7 @@
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -12020,7 +12020,7 @@
'description': '''
Message from an AI.
AIMessage is returned from a chat model as a response to a prompt.
`AIMessage` is returned from a chat model as a response to a prompt.
This message represents the output of the model and consists of both
the raw output as returned by the model together standardized fields
@@ -12460,7 +12460,7 @@
do not contain the `tool_call_id` field.
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -13224,7 +13224,7 @@
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
''',
'properties': dict({
@@ -328,8 +328,8 @@ class BaseMultiActionAgent(BaseModel):
file_path: Path to file to save the agent to.
Raises:
NotImplementedError: If agent does not support saving.
ValueError: If file_path is not json or yaml.
`NotImplementedError`: If agent does not support saving.
`ValueError`: If `file_path` is not json or yaml.
Example:
```python
@@ -1053,9 +1053,9 @@ class AgentExecutor(Chain):
Defaults to `False`, which raises the error.
If `true`, the error will be sent back to the LLM as an observation.
If a string, the string itself will be sent to the LLM as an observation.
If a callable function, the function will be called with the exception
as an argument, and the result of that function will be passed to the agent
as an observation.
If a callable function, the function will be called with the exception as an
argument, and the result of that function will be passed to the agent as an
observation.
"""
trim_intermediate_steps: (
int | Callable[[list[tuple[AgentAction, str]]], list[tuple[AgentAction, str]]]
@@ -37,7 +37,7 @@ def create_conversational_retrieval_agent(
"""A convenience method for creating a conversational retrieval agent.
Args:
llm: The language model to use, should be ChatOpenAI
llm: The language model to use, should be `ChatOpenAI`
tools: A list of tools the agent has access to
remember_intermediate_steps: Whether the agent should remember intermediate
steps or not. Intermediate steps refer to prior action/observation
@@ -47,11 +47,9 @@ def create_conversational_retrieval_agent(
memory_key: The name of the memory key in the prompt.
system_message: The system message to use. By default, a basic one will
be used.
verbose: Whether or not the final AgentExecutor should be verbose or not,
defaults to False.
verbose: Whether or not the final AgentExecutor should be verbose or not.
max_token_limit: The max number of tokens to keep around in memory.
Defaults to 2000.
**kwargs: Additional keyword arguments to pass to the AgentExecutor.
**kwargs: Additional keyword arguments to pass to the `AgentExecutor`.
Returns:
An agent executor initialized appropriately
@@ -87,12 +87,11 @@ def create_vectorstore_agent(
llm: LLM that will be used by the agent
toolkit: Set of tools for the agent
callback_manager: Object to handle the callback
prefix: The prefix prompt for the agent. If not provided uses default PREFIX.
prefix: The prefix prompt for the agent.
verbose: If you want to see the content of the scratchpad.
[ Defaults to `False` ]
agent_executor_kwargs: If there is any other parameter you want to send to the
agent. [ Defaults to `None` ]
kwargs: Additional named parameters to pass to the ZeroShotAgent.
agent.
kwargs: Additional named parameters to pass to the `ZeroShotAgent`.
Returns:
Returns a callable AgentExecutor object.
@@ -202,15 +201,14 @@ def create_vectorstore_router_agent(
vector stores
callback_manager: Object to handle the callback
prefix: The prefix prompt for the router agent.
If not provided uses default ROUTER_PREFIX.
If not provided uses default `ROUTER_PREFIX`.
verbose: If you want to see the content of the scratchpad.
[ Defaults to `False` ]
agent_executor_kwargs: If there is any other parameter you want to send to the
agent. [ Defaults to `None` ]
kwargs: Additional named parameters to pass to the ZeroShotAgent.
agent.
kwargs: Additional named parameters to pass to the `ZeroShotAgent`.
Returns:
Returns a callable AgentExecutor object.
Returns a callable `AgentExecutor` object.
Either you can call it or use run method with the query to get the response.
"""
@@ -94,13 +94,10 @@ class ChatAgent(Agent):
Args:
tools: A list of tools.
system_message_prefix: The system message prefix.
Default is SYSTEM_MESSAGE_PREFIX.
system_message_suffix: The system message suffix.
Default is SYSTEM_MESSAGE_SUFFIX.
human_message: The human message. Default is HUMAN_MESSAGE.
human_message: The human message.
format_instructions: The format instructions.
Default is FORMAT_INSTRUCTIONS.
input_variables: The input variables. Default is None.
input_variables: The input variables.
Returns:
A prompt template.
@@ -141,16 +138,13 @@ class ChatAgent(Agent):
Args:
llm: The language model.
tools: A list of tools.
callback_manager: The callback manager. Default is None.
output_parser: The output parser. Default is None.
callback_manager: The callback manager.
output_parser: The output parser.
system_message_prefix: The system message prefix.
Default is SYSTEM_MESSAGE_PREFIX.
system_message_suffix: The system message suffix.
Default is SYSTEM_MESSAGE_SUFFIX.
human_message: The human message. Default is HUMAN_MESSAGE.
human_message: The human message.
format_instructions: The format instructions.
Default is FORMAT_INSTRUCTIONS.
input_variables: The input variables. Default is None.
input_variables: The input variables.
kwargs: Additional keyword arguments.
Returns:
@@ -87,15 +87,13 @@ class ConversationalAgent(Agent):
Args:
tools: List of tools the agent will have access to, used to format the
prompt.
prefix: String to put before the list of tools. Defaults to PREFIX.
suffix: String to put after the list of tools. Defaults to SUFFIX.
format_instructions: Instructions on how to use the tools. Defaults to
FORMAT_INSTRUCTIONS
ai_prefix: String to use before AI output. Defaults to "AI".
prefix: String to put before the list of tools.
suffix: String to put after the list of tools.
format_instructions: Instructions on how to use the tools.
ai_prefix: String to use before AI output.
human_prefix: String to use before human output.
Defaults to "Human".
input_variables: List of input variables the final prompt will expect.
Defaults to ["input", "chat_history", "agent_scratchpad"].
Defaults to `["input", "chat_history", "agent_scratchpad"]`.
Returns:
A PromptTemplate with the template assembled from the pieces here.
@@ -139,16 +137,14 @@ class ConversationalAgent(Agent):
Args:
llm: The language model to use.
tools: A list of tools to use.
callback_manager: The callback manager to use. Default is None.
output_parser: The output parser to use. Default is None.
prefix: The prefix to use in the prompt. Default is PREFIX.
suffix: The suffix to use in the prompt. Default is SUFFIX.
callback_manager: The callback manager to use.
output_parser: The output parser to use.
prefix: The prefix to use in the prompt.
suffix: The suffix to use in the prompt.
format_instructions: The format instructions to use.
Default is FORMAT_INSTRUCTIONS.
ai_prefix: The prefix to use before AI output. Default is "AI".
ai_prefix: The prefix to use before AI output.
human_prefix: The prefix to use before human output.
Default is "Human".
input_variables: The input variables to use. Default is None.
input_variables: The input variables to use.
**kwargs: Any additional keyword arguments to pass to the agent.
Returns:
@@ -88,14 +88,12 @@ class ConversationalChatAgent(Agent):
Args:
tools: The tools to use.
system_message: The system message to use.
Defaults to the PREFIX.
human_message: The human message to use.
Defaults to the SUFFIX.
input_variables: The input variables to use.
output_parser: The output parser to use.
Returns:
A PromptTemplate.
A `PromptTemplate`.
"""
tool_strings = "\n".join(
[f"> {tool.name}: {tool.description}" for tool in tools],
@@ -150,11 +148,11 @@ class ConversationalChatAgent(Agent):
Args:
llm: The language model to use.
tools: A list of tools to use.
callback_manager: The callback manager to use. Default is None.
output_parser: The output parser to use. Default is None.
system_message: The system message to use. Default is PREFIX.
human_message: The human message to use. Default is SUFFIX.
input_variables: The input variables to use. Default is None.
callback_manager: The callback manager to use.
output_parser: The output parser to use.
system_message: The system message to use.
human_message: The human message to use.
input_variables: The input variables to use.
**kwargs: Any additional arguments.
Returns:
@@ -11,9 +11,7 @@ def format_log_to_str(
Args:
intermediate_steps: List of tuples of AgentAction and observation strings.
observation_prefix: Prefix to append the observation with.
Defaults to "Observation: ".
llm_prefix: Prefix to append the llm call with.
Defaults to "Thought: ".
Returns:
The scratchpad.
@@ -11,7 +11,7 @@ def format_log_to_messages(
Args:
intermediate_steps: List of tuples of AgentAction and observation strings.
template_tool_response: Template to format the observation with.
Defaults to "{observation}".
Defaults to `"{observation}"`.
Returns:
The scratchpad.
@@ -30,13 +30,12 @@ def create_json_chat_agent(
If `False`, does not add a stop token.
If a list of str, uses the provided list as the stop tokens.
Default is True. You may to set this to False if the LLM you are using
does not support stop sequences.
You may to set this to False if the LLM you are using does not support stop
sequences.
tools_renderer: This controls how the tools are converted into a string and
then passed into the LLM. Default is `render_text_description`.
then passed into the LLM.
template_tool_response: Template prompt that uses the tool response
(observation) to make the LLM generate the next action to take.
Default is TEMPLATE_TOOL_RESPONSE.
Returns:
A Runnable sequence representing an agent. It takes as input all the same input
@@ -93,10 +93,9 @@ class ZeroShotAgent(Agent):
Args:
tools: List of tools the agent will have access to, used to format the
prompt.
prefix: String to put before the list of tools. Defaults to PREFIX.
suffix: String to put after the list of tools. Defaults to SUFFIX.
prefix: String to put before the list of tools.
suffix: String to put after the list of tools.
format_instructions: Instructions on how to use the tools.
Defaults to FORMAT_INSTRUCTIONS
input_variables: List of input variables the final prompt will expect.
@@ -131,10 +130,9 @@ class ZeroShotAgent(Agent):
tools: The tools to use.
callback_manager: The callback manager to use.
output_parser: The output parser to use.
prefix: The prefix to use. Defaults to PREFIX.
suffix: The suffix to use. Defaults to SUFFIX.
prefix: The prefix to use.
suffix: The suffix to use.
format_instructions: The format instructions to use.
Defaults to FORMAT_INSTRUCTIONS.
input_variables: The input variables to use.
kwargs: Additional parameters to pass to the agent.
"""
@@ -17,18 +17,17 @@ class AgentTokenBufferMemory(BaseChatMemory):
"""Memory used to save agent output AND intermediate steps.
Args:
human_prefix: Prefix for human messages. Default is "Human".
ai_prefix: Prefix for AI messages. Default is "AI".
human_prefix: Prefix for human messages.
ai_prefix: Prefix for AI messages.
llm: Language model.
memory_key: Key to save memory under. Default is "history".
memory_key: Key to save memory under.
max_token_limit: Maximum number of tokens to keep in the buffer.
Once the buffer exceeds this many tokens, the oldest
messages will be pruned. Default is 12000.
return_messages: Whether to return messages. Default is True.
output_key: Key to save output under. Default is "output".
messages will be pruned.
return_messages: Whether to return messages.
output_key: Key to save output under.
intermediate_steps_key: Key to save intermediate steps under.
Default is "intermediate_steps".
format_as_tools: Whether to format as tools. Default is False.
format_as_tools: Whether to format as tools.
"""
human_prefix: str = "Human"
@@ -40,15 +40,14 @@ class OpenAIFunctionsAgent(BaseSingleActionAgent):
"""An Agent driven by OpenAIs function powered API.
Args:
llm: This should be an instance of ChatOpenAI, specifically a model
llm: This should be an instance of `ChatOpenAI`, specifically a model
that supports using `functions`.
tools: The tools this agent has access to.
prompt: The prompt for this agent, should support agent_scratchpad as one
of the variables. For an easy way to construct this prompt, use
`OpenAIFunctionsAgent.create_prompt(...)`
output_parser: The output parser for this agent. Should be an instance of
OpenAIFunctionsAgentOutputParser.
Defaults to OpenAIFunctionsAgentOutputParser.
`OpenAIFunctionsAgentOutputParser`.
"""
llm: BaseLanguageModel
@@ -107,13 +106,13 @@ class OpenAIFunctionsAgent(BaseSingleActionAgent):
intermediate_steps: Steps the LLM has taken to date,
along with observations.
callbacks: Callbacks to use.
with_functions: Whether to use functions. Defaults to `True`.
with_functions: Whether to use functions.
**kwargs: User inputs.
Returns:
Action specifying what tool to use.
If the agent is finished, returns an AgentFinish.
If the agent is not finished, returns an AgentAction.
If the agent is finished, returns an `AgentFinish`.
If the agent is not finished, returns an `AgentAction`.
"""
agent_scratchpad = format_to_openai_function_messages(intermediate_steps)
selected_inputs = {
@@ -212,7 +212,7 @@ class OpenAIMultiFunctionsAgent(BaseMultiActionAgent):
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations.
callbacks: Callbacks to use. Default is None.
callbacks: Callbacks to use.
**kwargs: User inputs.
Returns:
@@ -243,7 +243,7 @@ class OpenAIMultiFunctionsAgent(BaseMultiActionAgent):
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations.
callbacks: Callbacks to use. Default is None.
callbacks: Callbacks to use.
**kwargs: User inputs.
Returns:
@@ -275,7 +275,7 @@ class OpenAIMultiFunctionsAgent(BaseMultiActionAgent):
system_message: Message to use as the system message that will be the
first in the prompt.
extra_prompt_messages: Prompt messages that will be placed between the
system message and the new human input. Default is None.
system message and the new human input.
Returns:
A prompt template to pass into this agent.
@@ -313,10 +313,10 @@ class OpenAIMultiFunctionsAgent(BaseMultiActionAgent):
Args:
llm: The language model to use.
tools: A list of tools to use.
callback_manager: The callback manager to use. Default is None.
extra_prompt_messages: Extra prompt messages to use. Default is None.
system_message: The system message to use.
Default is a default system message.
callback_manager: The callback manager to use.
extra_prompt_messages: Extra prompt messages to use.
system_message: The system message to use. Default is a default system
message.
kwargs: Additional arguments.
"""
system_message_ = (
@@ -42,13 +42,13 @@ def create_react_agent(
prompt: The prompt to use. See Prompt section below for more.
output_parser: AgentOutputParser for parse the LLM output.
tools_renderer: This controls how the tools are converted into a string and
then passed into the LLM. Default is `render_text_description`.
then passed into the LLM.
stop_sequence: bool or list of str.
If `True`, adds a stop token of "Observation:" to avoid hallucinates.
If `False`, does not add a stop token.
If a list of str, uses the provided list as the stop tokens.
Default is True. You may to set this to False if the LLM you are using
You may to set this to False if the LLM you are using
does not support stop sequences.
Returns:
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff. Show more