The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
style: misc refs work (#33771)
Mason Daughertyf2dab562a89a
diff --git a/libs/core/langchain_core/agents.py b/libs/core/langchain_core/agents.pyindex a4038d1d3f..8ea46fb79e 100644--- a/libs/core/langchain_core/agents.py+++ b/libs/core/langchain_core/agents.py@@ -118,12 +118,12 @@ class AgentActionMessageLog(AgentAction):class AgentStep(Serializable):- """Result of running an AgentAction."""+ """Result of running an `AgentAction`."""action: AgentAction- """The AgentAction that was executed."""+ """The `AgentAction` that was executed."""observation: Any- """The result of the AgentAction."""+ """The result of the `AgentAction`."""@propertydef messages(self) -> Sequence[BaseMessage]:diff --git a/libs/core/langchain_core/exceptions.py b/libs/core/langchain_core/exceptions.pyindex 72a0b7292b..a1e8a5cb91 100644--- a/libs/core/langchain_core/exceptions.py+++ b/libs/core/langchain_core/exceptions.py@@ -16,9 +16,10 @@ 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. `OutputParserException` will be- available to catch and handle in ways to fix the parsing error, while other- errors will be raised.+ 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."""def __init__(@@ -32,18 +33,19 @@ class OutputParserException(ValueError, LangChainException): # noqa: N818Args:error: The error that's being re-raised or an error message.- observation: String explanation of error which can be passed to a- model to try and remediate the issue.+ observation: String explanation of error which can be passed to a model to+ try and remediate the issue.llm_output: String model output which is error-ing.send_to_llm: Whether to send the observation and llm_output back to an Agentafter an `OutputParserException` has been raised.+This gives the underlying model driving the agent the context that theprevious output was improperly structured, in the hopes that it willupdate the output to the correct format.Raises:- ValueError: If `send_to_llm` is True but either observation or+ ValueError: If `send_to_llm` is `True` but either observation or`llm_output` are not provided."""if isinstance(error, str):@@ -66,11 +68,11 @@ class ErrorCode(Enum):"""Error codes."""INVALID_PROMPT_INPUT = "INVALID_PROMPT_INPUT"- INVALID_TOOL_RESULTS = "INVALID_TOOL_RESULTS"+ INVALID_TOOL_RESULTS = "INVALID_TOOL_RESULTS" # Used in JS; not Py (yet)MESSAGE_COERCION_FAILURE = "MESSAGE_COERCION_FAILURE"- MODEL_AUTHENTICATION = "MODEL_AUTHENTICATION"- MODEL_NOT_FOUND = "MODEL_NOT_FOUND"- MODEL_RATE_LIMIT = "MODEL_RATE_LIMIT"+ MODEL_AUTHENTICATION = "MODEL_AUTHENTICATION" # Used in JS; not Py (yet)+ MODEL_NOT_FOUND = "MODEL_NOT_FOUND" # Used in JS; not Py (yet)+ MODEL_RATE_LIMIT = "MODEL_RATE_LIMIT" # Used in JS; not Py (yet)OUTPUT_PARSING_FAILURE = "OUTPUT_PARSING_FAILURE"diff --git a/libs/core/langchain_core/vectorstores/base.py b/libs/core/langchain_core/vectorstores/base.pyindex 4b4e136ab5..3580f5e9cd 100644--- a/libs/core/langchain_core/vectorstores/base.py+++ b/libs/core/langchain_core/vectorstores/base.py@@ -237,8 +237,9 @@ class VectorStore(ABC):Args:documents: Documents to add to the `VectorStore`.**kwargs: Additional keyword arguments.- if kwargs contains IDs and documents contain ids,- the IDs in the kwargs will receive precedence.++ If kwargs contains IDs and documents contain ids, the IDs in the kwargs+ will receive precedence.Returns:List of IDs of the added texts.@@ -421,7 +422,7 @@ class VectorStore(ABC):**kwargs: Arguments to pass to the search method.Returns:- List of Tuples of `(doc, similarity_score)`.+ List of tuples of `(doc, similarity_score)`."""raise NotImplementedError@@ -435,7 +436,7 @@ class VectorStore(ABC):**kwargs: Arguments to pass to the search method.Returns:- List of Tuples of `(doc, similarity_score)`.+ List of tuples of `(doc, similarity_score)`."""# This is a temporary workaround to make the similarity search# asynchronous. The proper solution is to make the similarity search@@ -465,7 +466,7 @@ class VectorStore(ABC):to filter the resulting set of retrieved docsReturns:- List of Tuples of `(doc, similarity_score)`+ List of tuples of `(doc, similarity_score)`"""relevance_score_fn = self._select_relevance_score_fn()docs_and_scores = self.similarity_search_with_score(query, k, **kwargs)@@ -492,7 +493,7 @@ class VectorStore(ABC):to filter the resulting set of retrieved docsReturns:- List of Tuples of `(doc, similarity_score)`+ List of tuples of `(doc, similarity_score)`"""relevance_score_fn = self._select_relevance_score_fn()docs_and_scores = await self.asimilarity_search_with_score(query, k, **kwargs)@@ -516,7 +517,7 @@ class VectorStore(ABC):to filter the resulting set of retrieved docsReturns:- List of Tuples of `(doc, similarity_score)`.+ List of tuples of `(doc, similarity_score)`."""score_threshold = kwargs.pop("score_threshold", None)@@ -565,7 +566,7 @@ class VectorStore(ABC):to filter the resulting set of retrieved docsReturns:- List of Tuples of `(doc, similarity_score)`+ List of tuples of `(doc, similarity_score)`"""score_threshold = kwargs.pop("score_threshold", None)@@ -667,7 +668,7 @@ class VectorStore(ABC):k: Number of `Document` objects to return.fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.lambda_mult: Number between `0` and `1` that determines the degree- of diversity among the results with 0 corresponding+ of diversity among the results with `0` correspondingto maximum diversity and `1` to minimum diversity.**kwargs: Arguments to pass to the search method.@@ -694,7 +695,7 @@ class VectorStore(ABC):k: Number of `Document` objects to return.fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.lambda_mult: Number between `0` and `1` that determines the degree- of diversity among the results with 0 corresponding+ of diversity among the results with `0` correspondingto maximum diversity and `1` to minimum diversity.**kwargs: Arguments to pass to the search method.@@ -732,7 +733,7 @@ class VectorStore(ABC):k: Number of `Document` objects to return.fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.lambda_mult: Number between `0` and `1` that determines the degree- of diversity among the results with 0 corresponding+ of diversity among the results with `0` correspondingto maximum diversity and `1` to minimum diversity.**kwargs: Arguments to pass to the search method.@@ -759,7 +760,7 @@ class VectorStore(ABC):k: Number of `Document` objects to return.fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.lambda_mult: Number between `0` and `1` that determines the degree- of diversity among the results with 0 corresponding+ of diversity among the results with `0` correspondingto maximum diversity and `1` to minimum diversity.**kwargs: Arguments to pass to the search method.diff --git a/libs/langchain/langchain_classic/agents/agent.py b/libs/langchain/langchain_classic/agents/agent.pyindex 786fd3921c..bd0c8e7412 100644--- a/libs/langchain/langchain_classic/agents/agent.py+++ b/libs/langchain/langchain_classic/agents/agent.py@@ -403,8 +403,8 @@ class RunnableAgent(BaseSingleActionAgent):"""Whether to stream from the runnable or not.If `True` then underlying LLM is invoked in a streaming fashion to make it possible- to get access to the individual LLM tokens when using stream_log with the Agent- Executor. If `False` then LLM is invoked in a non-streaming fashion and+ to get access to the individual LLM tokens when using stream_log with the+ `AgentExecutor`. If `False` then LLM is invoked in a non-streaming fashion andindividual LLM tokens will not be available in stream_log."""@@ -445,7 +445,7 @@ class RunnableAgent(BaseSingleActionAgent):# Use streaming to make sure that the underlying LLM is invoked in a# streaming# fashion to make it possible to get access to the individual LLM tokens- # when using stream_log with the Agent Executor.+ # when using stream_log with the AgentExecutor.# Because the response from the plan is not a generator, we need to# accumulate the output into final output and return that.for chunk in self.runnable.stream(inputs, config={"callbacks": callbacks}):@@ -481,7 +481,7 @@ class RunnableAgent(BaseSingleActionAgent):# Use streaming to make sure that the underlying LLM is invoked in a# streaming# fashion to make it possible to get access to the individual LLM tokens- # when using stream_log with the Agent Executor.+ # when using stream_log with the AgentExecutor.# Because the response from the plan is not a generator, we need to# accumulate the output into final output and return that.async for chunk in self.runnable.astream(@@ -511,8 +511,8 @@ class RunnableMultiActionAgent(BaseMultiActionAgent):"""Whether to stream from the runnable or not.If `True` then underlying LLM is invoked in a streaming fashion to make it possible- to get access to the individual LLM tokens when using stream_log with the Agent- Executor. If `False` then LLM is invoked in a non-streaming fashion and+ to get access to the individual LLM tokens when using stream_log with the+ `AgentExecutor`. If `False` then LLM is invoked in a non-streaming fashion andindividual LLM tokens will not be available in stream_log."""@@ -557,7 +557,7 @@ class RunnableMultiActionAgent(BaseMultiActionAgent):# Use streaming to make sure that the underlying LLM is invoked in a# streaming# fashion to make it possible to get access to the individual LLM tokens- # when using stream_log with the Agent Executor.+ # when using stream_log with the AgentExecutor.# Because the response from the plan is not a generator, we need to# accumulate the output into final output and return that.for chunk in self.runnable.stream(inputs, config={"callbacks": callbacks}):@@ -593,7 +593,7 @@ class RunnableMultiActionAgent(BaseMultiActionAgent):# Use streaming to make sure that the underlying LLM is invoked in a# streaming# fashion to make it possible to get access to the individual LLM tokens- # when using stream_log with the Agent Executor.+ # when using stream_log with the AgentExecutor.# Because the response from the plan is not a generator, we need to# accumulate the output into final output and return that.async for chunk in self.runnable.astream(diff --git a/libs/langchain/langchain_classic/agents/agent_iterator.py b/libs/langchain/langchain_classic/agents/agent_iterator.pyindex f9ed911c91..138b58f69c 100644--- a/libs/langchain/langchain_classic/agents/agent_iterator.py+++ b/libs/langchain/langchain_classic/agents/agent_iterator.py@@ -53,9 +53,9 @@ class AgentExecutorIterator:include_run_info: bool = False,yield_actions: bool = False,):- """Initialize the AgentExecutorIterator.+ """Initialize the `AgentExecutorIterator`.- Initialize the AgentExecutorIterator with the given AgentExecutor,+ Initialize the `AgentExecutorIterator` with the given `AgentExecutor`,inputs, and optional callbacks.Args:@@ -91,7 +91,7 @@ class AgentExecutorIterator:@propertydef inputs(self) -> dict[str, str]:- """The inputs to the AgentExecutor."""+ """The inputs to the `AgentExecutor`."""return self._inputs@inputs.setter@@ -100,7 +100,7 @@ class AgentExecutorIterator:@propertydef agent_executor(self) -> AgentExecutor:- """The AgentExecutor to iterate over."""+ """The `AgentExecutor` to iterate over."""return self._agent_executor@agent_executor.setter@@ -171,7 +171,7 @@ class AgentExecutorIterator:return prepared_outputsdef __iter__(self: AgentExecutorIterator) -> Iterator[AddableDict]:- """Create an async iterator for the AgentExecutor."""+ """Create an async iterator for the `AgentExecutor`."""logger.debug("Initialising AgentExecutorIterator")self.reset()callback_manager = CallbackManager.configure(@@ -235,7 +235,7 @@ class AgentExecutorIterator:yield self._stop(run_manager)async def __aiter__(self) -> AsyncIterator[AddableDict]:- """Create an async iterator for the AgentExecutor.+ """Create an async iterator for the `AgentExecutor`.N.B. __aiter__ must be a normal method, so need to initialize async run manageron first __anext__ call where we can await it.diff --git a/libs/langchain/langchain_classic/agents/openai_assistant/base.py b/libs/langchain/langchain_classic/agents/openai_assistant/base.pyindex dc4f33b58e..472c3ad27a 100644--- a/libs/langchain/langchain_classic/agents/openai_assistant/base.py+++ b/libs/langchain/langchain_classic/agents/openai_assistant/base.py@@ -231,15 +231,15 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):"""client: Any = Field(default_factory=_get_openai_client)- """OpenAI or AzureOpenAI client."""+ """`OpenAI` or `AzureOpenAI` client."""async_client: Any = None- """OpenAI or AzureOpenAI async client."""+ """`OpenAI` or `AzureOpenAI` async client."""assistant_id: str"""OpenAI assistant id."""check_every_ms: float = 1_000.0"""Frequency with which to check run progress in ms."""as_agent: bool = False- """Use as a LangChain agent, compatible with the AgentExecutor."""+ """Use as a LangChain agent, compatible with the `AgentExecutor`."""@model_validator(mode="after")def _validate_async_client(self) -> Self:diff --git a/libs/partners/nomic/langchain_nomic/embeddings.py b/libs/partners/nomic/langchain_nomic/embeddings.pyindex 6357134576..775f8fad85 100644--- a/libs/partners/nomic/langchain_nomic/embeddings.py+++ b/libs/partners/nomic/langchain_nomic/embeddings.py@@ -11,7 +11,7 @@ from nomic import embedclass NomicEmbeddings(Embeddings):- """NomicEmbeddings embedding model.+ """`NomicEmbeddings` embedding model.Example:```python@@ -66,8 +66,8 @@ class NomicEmbeddings(Embeddings):"""Initialize `NomicEmbeddings` model.Args:- model: model name- nomic_api_key: optionally, set the Nomic API key. Uses the `NOMIC_API_KEY`+ model: Model name+ nomic_api_key: Optionally, set the Nomic API key. Uses the `NOMIC_API_KEY`environment variable by default.dimensionality: The embedding dimension, for use with Matryoshka-capablemodels. Defaults to full-size.@@ -76,7 +76,12 @@ class NomicEmbeddings(Embeddings):device: The device to use for local embeddings. Choices include`'cpu'`, `'gpu'`, `'nvidia'`, `'amd'`, or a specific devicename. See the docstring for `GPT4All.__init__` for more info.- Typically defaults to `'cpu'`. Do not use on macOS.++ Typically defaults to `'cpu'`.++ !!! warning++ Do not use on macOS.vision_model: The vision model to use for image embeddings."""@@ -93,8 +98,8 @@ class NomicEmbeddings(Embeddings):"""Embed texts.Args:- texts: list of texts to embed- task_type: the task type to use when embedding. One of `'search_query'`,+ texts: List of texts to embed+ task_type: The task type to use when embedding. One of `'search_query'`,`'search_document'`, `'classification'`, `'clustering'`"""@@ -112,7 +117,7 @@ class NomicEmbeddings(Embeddings):"""Embed search docs.Args:- texts: list of texts to embed as documents+ texts: List of texts to embed as documents"""return self.embed(@@ -124,7 +129,7 @@ class NomicEmbeddings(Embeddings):"""Embed query text.Args:- text: query text+ text: Query text"""return self.embed(@@ -136,7 +141,7 @@ class NomicEmbeddings(Embeddings):"""Embed images.Args:- uris: list of image URIs to embed+ uris: List of image URIs to embed"""return embed.image(images=uris,diff --git a/libs/partners/ollama/tests/integration_tests/chat_models/test_chat_models.py b/libs/partners/ollama/tests/integration_tests/chat_models/test_chat_models.pyindex e68f2e0855..a38bdbfad9 100644--- a/libs/partners/ollama/tests/integration_tests/chat_models/test_chat_models.py+++ b/libs/partners/ollama/tests/integration_tests/chat_models/test_chat_models.py@@ -40,7 +40,7 @@ def test_init_model_not_found(mock_list: MagicMock) -> None:@patch("langchain_ollama.chat_models.Client.list")def test_init_connection_error(mock_list: MagicMock) -> None:- """Test that a ValidationError is raised on connect failure during init."""+ """Test that a `ValidationError` is raised on connect failure during init."""mock_list.side_effect = ConnectError("Test connection error")with pytest.raises(ValidationError) as excinfo:diff --git a/libs/partners/qdrant/langchain_qdrant/vectorstores.py b/libs/partners/qdrant/langchain_qdrant/vectorstores.pyindex e149fd54b9..95f5500a13 100644--- a/libs/partners/qdrant/langchain_qdrant/vectorstores.py+++ b/libs/partners/qdrant/langchain_qdrant/vectorstores.py@@ -742,9 +742,9 @@ class Qdrant(VectorStore):query: Text to look up documents similar to.k: Number of Documents to return.fetch_k: Number of Documents to fetch to pass to MMR algorithm.- 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.+ 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.filter: Filter by metadata.search_params: Additional search paramsscore_threshold:@@ -1002,9 +1002,9 @@ class Qdrant(VectorStore):embedding: Embedding vector to look up documents similar to.k: Number of Documents to return.fetch_k: Number of Documents to fetch to pass to MMR algorithm.- 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.+ 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.filter: Filter by metadata.search_params: Additional search paramsscore_threshold:@@ -1091,9 +1091,9 @@ class Qdrant(VectorStore):embedding: Embedding vector to look up documents similar to.k: Number of Documents to return.fetch_k: Number of Documents to fetch to pass to MMR algorithm.- 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.+ 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.filter: Filter by metadata.search_params: Additional search params.score_threshold: Define a minimal score threshold for the result.@@ -1985,7 +1985,7 @@ class Qdrant(VectorStore):to filter the resulting set of retrieved docsReturns:- List of Tuples of `(doc, similarity_score)`+ List of tuples of `(doc, similarity_score)`"""return self.similarity_search_with_score(query, k, **kwargs)@@ -2009,7 +2009,7 @@ class Qdrant(VectorStore):to filter the resulting set of retrieved docsReturns:- List of Tuples of `(doc, similarity_score)`+ List of tuples of `(doc, similarity_score)`"""return await self.asimilarity_search_with_score(query, k, **kwargs)