Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic-1.0.7.dist-info/licenses/LICENSE +21 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/__init__.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/base_language.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/base_memory.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/cache.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/env.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/example_generator.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/formatting.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/globals.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/hub.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/input.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/model_laboratory.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/python.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/requests.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/serpapi.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/sql_database.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/text_splitter.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__init__.py +28 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__pycache__/__init__.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__pycache__/deprecation.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__pycache__/interactive_env.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__pycache__/module_import.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__pycache__/path.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/deprecation.py +27 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/interactive_env.py +5 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/module_import.py +156 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/path.py +3 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/adapters/__init__.py +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/adapters/openai.py +63 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/__init__.py +164 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/agent.py +1792 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/agent_iterator.py +432 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/agent_types.py +54 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/initialize.py +116 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/load_tools.py +13 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/loading.py +148 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/schema.py +37 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/tools.py +48 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/types.py +27 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/utils.py +19 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/__init__.py +130 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/aim_callback.py +33 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/argilla_callback.py +25 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/arize_callback.py +25 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/arthur_callback.py +25 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/base.py +29 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/clearml_callback.py +25 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/comet_ml_callback.py +25 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/confident_callback.py +25 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/context_callback.py +25 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic-1.0.7.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) LangChain, Inc.
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (11.6 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/base_language.cpython-311.pyc
ADDED
|
Binary file (491 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/base_memory.cpython-311.pyc
ADDED
|
Binary file (5.37 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/cache.cpython-311.pyc
ADDED
|
Binary file (1.83 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/env.cpython-311.pyc
ADDED
|
Binary file (899 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/example_generator.cpython-311.pyc
ADDED
|
Binary file (402 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/formatting.cpython-311.pyc
ADDED
|
Binary file (425 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/globals.cpython-311.pyc
ADDED
|
Binary file (570 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/hub.cpython-311.pyc
ADDED
|
Binary file (5.3 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/input.cpython-311.pyc
ADDED
|
Binary file (504 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/model_laboratory.cpython-311.pyc
ADDED
|
Binary file (6.08 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/python.cpython-311.pyc
ADDED
|
Binary file (788 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/requests.cpython-311.pyc
ADDED
|
Binary file (1.07 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/serpapi.cpython-311.pyc
ADDED
|
Binary file (955 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/sql_database.cpython-311.pyc
ADDED
|
Binary file (967 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/__pycache__/text_splitter.cpython-311.pyc
ADDED
|
Binary file (1.84 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helper functions for managing the LangChain API.
|
| 2 |
+
|
| 3 |
+
This module is only relevant for LangChain developers, not for users.
|
| 4 |
+
|
| 5 |
+
!!! warning
|
| 6 |
+
|
| 7 |
+
This module and its submodules are for internal use only. Do not use them in your
|
| 8 |
+
own code. We may change the API at any time with no warning.
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from langchain_classic._api.deprecation import (
|
| 13 |
+
LangChainDeprecationWarning,
|
| 14 |
+
deprecated,
|
| 15 |
+
suppress_langchain_deprecation_warning,
|
| 16 |
+
surface_langchain_deprecation_warnings,
|
| 17 |
+
warn_deprecated,
|
| 18 |
+
)
|
| 19 |
+
from langchain_classic._api.module_import import create_importer
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
"LangChainDeprecationWarning",
|
| 23 |
+
"create_importer",
|
| 24 |
+
"deprecated",
|
| 25 |
+
"suppress_langchain_deprecation_warning",
|
| 26 |
+
"surface_langchain_deprecation_warnings",
|
| 27 |
+
"warn_deprecated",
|
| 28 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (987 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__pycache__/deprecation.cpython-311.pyc
ADDED
|
Binary file (995 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__pycache__/interactive_env.cpython-311.pyc
ADDED
|
Binary file (508 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__pycache__/module_import.cpython-311.pyc
ADDED
|
Binary file (5.7 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/__pycache__/path.cpython-311.pyc
ADDED
|
Binary file (359 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/deprecation.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core._api.deprecation import (
|
| 2 |
+
LangChainDeprecationWarning,
|
| 3 |
+
LangChainPendingDeprecationWarning,
|
| 4 |
+
deprecated,
|
| 5 |
+
suppress_langchain_deprecation_warning,
|
| 6 |
+
surface_langchain_deprecation_warnings,
|
| 7 |
+
warn_deprecated,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
AGENT_DEPRECATION_WARNING = (
|
| 11 |
+
"Use `langchain.agents.create_agent` for new applications. It provides a "
|
| 12 |
+
"more flexible agent factory with middleware support, structured output, "
|
| 13 |
+
"and integration with LangGraph for persistence, streaming, and "
|
| 14 |
+
"human-in-the-loop workflows. Migration guide: "
|
| 15 |
+
"https://docs.langchain.com/oss/python/migrate/langchain-v1"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
"AGENT_DEPRECATION_WARNING",
|
| 21 |
+
"LangChainDeprecationWarning",
|
| 22 |
+
"LangChainPendingDeprecationWarning",
|
| 23 |
+
"deprecated",
|
| 24 |
+
"suppress_langchain_deprecation_warning",
|
| 25 |
+
"surface_langchain_deprecation_warnings",
|
| 26 |
+
"warn_deprecated",
|
| 27 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/interactive_env.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def is_interactive_env() -> bool:
|
| 2 |
+
"""Determine if running within IPython or Jupyter."""
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
return hasattr(sys, "ps2")
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/module_import.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
from langchain_core._api import internal, warn_deprecated
|
| 6 |
+
|
| 7 |
+
from langchain_classic._api.interactive_env import is_interactive_env
|
| 8 |
+
|
| 9 |
+
ALLOWED_TOP_LEVEL_PKGS = {
|
| 10 |
+
"langchain_community",
|
| 11 |
+
"langchain_core",
|
| 12 |
+
"langchain_classic",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def create_importer(
|
| 17 |
+
package: str,
|
| 18 |
+
*,
|
| 19 |
+
module_lookup: dict[str, str] | None = None,
|
| 20 |
+
deprecated_lookups: dict[str, str] | None = None,
|
| 21 |
+
fallback_module: str | None = None,
|
| 22 |
+
) -> Callable[[str], Any]:
|
| 23 |
+
"""Create a function that helps retrieve objects from their new locations.
|
| 24 |
+
|
| 25 |
+
The goal of this function is to help users transition from deprecated
|
| 26 |
+
imports to new imports.
|
| 27 |
+
|
| 28 |
+
The function will raise deprecation warning on loops using
|
| 29 |
+
`deprecated_lookups` or `fallback_module`.
|
| 30 |
+
|
| 31 |
+
Module lookups will import without deprecation warnings (used to speed
|
| 32 |
+
up imports from large namespaces like llms or chat models).
|
| 33 |
+
|
| 34 |
+
This function should ideally only be used with deprecated imports not with
|
| 35 |
+
existing imports that are valid, as in addition to raising deprecation warnings
|
| 36 |
+
the dynamic imports can create other issues for developers (e.g.,
|
| 37 |
+
loss of type information, IDE support for going to definition etc).
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
package: Current package. Use `__package__`
|
| 41 |
+
module_lookup: Maps name of object to the module where it is defined.
|
| 42 |
+
e.g.,
|
| 43 |
+
```json
|
| 44 |
+
{
|
| 45 |
+
"MyDocumentLoader": (
|
| 46 |
+
"langchain_community.document_loaders.my_document_loader"
|
| 47 |
+
)
|
| 48 |
+
}
|
| 49 |
+
```
|
| 50 |
+
deprecated_lookups: Same as module look up, but will raise
|
| 51 |
+
deprecation warnings.
|
| 52 |
+
fallback_module: Module to import from if the object is not found in
|
| 53 |
+
`module_lookup` or if `module_lookup` is not provided.
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
A function that imports objects from the specified modules.
|
| 57 |
+
"""
|
| 58 |
+
all_module_lookup = {**(deprecated_lookups or {}), **(module_lookup or {})}
|
| 59 |
+
|
| 60 |
+
def import_by_name(name: str) -> Any:
|
| 61 |
+
"""Import stores from `langchain_community`."""
|
| 62 |
+
# If not in interactive env, raise warning.
|
| 63 |
+
if all_module_lookup and name in all_module_lookup:
|
| 64 |
+
new_module = all_module_lookup[name]
|
| 65 |
+
if new_module.split(".")[0] not in ALLOWED_TOP_LEVEL_PKGS:
|
| 66 |
+
msg = (
|
| 67 |
+
f"Importing from {new_module} is not allowed. "
|
| 68 |
+
f"Allowed top-level packages are: {ALLOWED_TOP_LEVEL_PKGS}"
|
| 69 |
+
)
|
| 70 |
+
raise AssertionError(msg)
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
module = importlib.import_module(new_module)
|
| 74 |
+
except ModuleNotFoundError as e:
|
| 75 |
+
if new_module.startswith("langchain_community"):
|
| 76 |
+
msg = (
|
| 77 |
+
f"Module {new_module} not found. "
|
| 78 |
+
"Please install langchain-community to access this module. "
|
| 79 |
+
"You can install it using `pip install -U langchain-community`"
|
| 80 |
+
)
|
| 81 |
+
raise ModuleNotFoundError(msg) from e
|
| 82 |
+
raise
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
result = getattr(module, name)
|
| 86 |
+
if (
|
| 87 |
+
not is_interactive_env()
|
| 88 |
+
and deprecated_lookups
|
| 89 |
+
and name in deprecated_lookups
|
| 90 |
+
# Depth 3:
|
| 91 |
+
# -> internal.py
|
| 92 |
+
# |-> module_import.py
|
| 93 |
+
# |-> Module in langchain that uses this function
|
| 94 |
+
# |-> [calling code] whose frame we want to inspect.
|
| 95 |
+
and not internal.is_caller_internal(depth=3)
|
| 96 |
+
):
|
| 97 |
+
warn_deprecated(
|
| 98 |
+
since="0.1",
|
| 99 |
+
pending=False,
|
| 100 |
+
removal="2.0.0",
|
| 101 |
+
message=(
|
| 102 |
+
f"Importing {name} from {package} is deprecated. "
|
| 103 |
+
f"Please replace deprecated imports:\n\n"
|
| 104 |
+
f">> from {package} import {name}\n\n"
|
| 105 |
+
"with new imports of:\n\n"
|
| 106 |
+
f">> from {new_module} import {name}\n"
|
| 107 |
+
"You can use the langchain cli to **automatically** "
|
| 108 |
+
"upgrade many imports. Please see documentation here "
|
| 109 |
+
"<https://python.langchain.com/docs/versions/v0_2/>"
|
| 110 |
+
),
|
| 111 |
+
)
|
| 112 |
+
except Exception as e:
|
| 113 |
+
msg = f"module {new_module} has no attribute {name}"
|
| 114 |
+
raise AttributeError(msg) from e
|
| 115 |
+
|
| 116 |
+
return result
|
| 117 |
+
|
| 118 |
+
if fallback_module:
|
| 119 |
+
try:
|
| 120 |
+
module = importlib.import_module(fallback_module)
|
| 121 |
+
result = getattr(module, name)
|
| 122 |
+
if (
|
| 123 |
+
not is_interactive_env()
|
| 124 |
+
# Depth 3:
|
| 125 |
+
# internal.py
|
| 126 |
+
# |-> module_import.py
|
| 127 |
+
# |->Module in langchain that uses this function
|
| 128 |
+
# |-> [calling code] whose frame we want to inspect.
|
| 129 |
+
and not internal.is_caller_internal(depth=3)
|
| 130 |
+
):
|
| 131 |
+
warn_deprecated(
|
| 132 |
+
since="0.1",
|
| 133 |
+
pending=False,
|
| 134 |
+
removal="2.0.0",
|
| 135 |
+
message=(
|
| 136 |
+
f"Importing {name} from {package} is deprecated. "
|
| 137 |
+
f"Please replace deprecated imports:\n\n"
|
| 138 |
+
f">> from {package} import {name}\n\n"
|
| 139 |
+
"with new imports of:\n\n"
|
| 140 |
+
f">> from {fallback_module} import {name}\n"
|
| 141 |
+
"You can use the langchain cli to **automatically** "
|
| 142 |
+
"upgrade many imports. Please see documentation here "
|
| 143 |
+
"<https://python.langchain.com/docs/versions/v0_2/>"
|
| 144 |
+
),
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
except Exception as e:
|
| 148 |
+
msg = f"module {fallback_module} has no attribute {name}"
|
| 149 |
+
raise AttributeError(msg) from e
|
| 150 |
+
|
| 151 |
+
return result
|
| 152 |
+
|
| 153 |
+
msg = f"module {package} has no attribute {name}"
|
| 154 |
+
raise AttributeError(msg)
|
| 155 |
+
|
| 156 |
+
return import_by_name
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/_api/path.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core._api.path import as_import_path, get_relative_path
|
| 2 |
+
|
| 3 |
+
__all__ = ["as_import_path", "get_relative_path"]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/adapters/__init__.py
ADDED
|
File without changes
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/adapters/openai.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Any
|
| 2 |
+
|
| 3 |
+
from langchain_classic._api import create_importer
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from langchain_community.adapters.openai import (
|
| 7 |
+
Chat,
|
| 8 |
+
ChatCompletion,
|
| 9 |
+
ChatCompletionChunk,
|
| 10 |
+
ChatCompletions,
|
| 11 |
+
Choice,
|
| 12 |
+
ChoiceChunk,
|
| 13 |
+
Completions,
|
| 14 |
+
IndexableBaseModel,
|
| 15 |
+
chat,
|
| 16 |
+
convert_dict_to_message,
|
| 17 |
+
convert_message_to_dict,
|
| 18 |
+
convert_messages_for_finetuning,
|
| 19 |
+
convert_openai_messages,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# Create a way to dynamically look up deprecated imports.
|
| 23 |
+
# Used to consolidate logic for raising deprecation warnings and
|
| 24 |
+
# handling optional imports.
|
| 25 |
+
MODULE_LOOKUP = {
|
| 26 |
+
"IndexableBaseModel": "langchain_community.adapters.openai",
|
| 27 |
+
"Choice": "langchain_community.adapters.openai",
|
| 28 |
+
"ChatCompletions": "langchain_community.adapters.openai",
|
| 29 |
+
"ChoiceChunk": "langchain_community.adapters.openai",
|
| 30 |
+
"ChatCompletionChunk": "langchain_community.adapters.openai",
|
| 31 |
+
"convert_dict_to_message": "langchain_community.adapters.openai",
|
| 32 |
+
"convert_message_to_dict": "langchain_community.adapters.openai",
|
| 33 |
+
"convert_openai_messages": "langchain_community.adapters.openai",
|
| 34 |
+
"ChatCompletion": "langchain_community.adapters.openai",
|
| 35 |
+
"convert_messages_for_finetuning": "langchain_community.adapters.openai",
|
| 36 |
+
"Completions": "langchain_community.adapters.openai",
|
| 37 |
+
"Chat": "langchain_community.adapters.openai",
|
| 38 |
+
"chat": "langchain_community.adapters.openai",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
_import_attribute = create_importer(__file__, deprecated_lookups=MODULE_LOOKUP)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def __getattr__(name: str) -> Any:
|
| 45 |
+
"""Look up attributes dynamically."""
|
| 46 |
+
return _import_attribute(name)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
__all__ = [
|
| 50 |
+
"Chat",
|
| 51 |
+
"ChatCompletion",
|
| 52 |
+
"ChatCompletionChunk",
|
| 53 |
+
"ChatCompletions",
|
| 54 |
+
"Choice",
|
| 55 |
+
"ChoiceChunk",
|
| 56 |
+
"Completions",
|
| 57 |
+
"IndexableBaseModel",
|
| 58 |
+
"chat",
|
| 59 |
+
"convert_dict_to_message",
|
| 60 |
+
"convert_message_to_dict",
|
| 61 |
+
"convert_messages_for_finetuning",
|
| 62 |
+
"convert_openai_messages",
|
| 63 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/__init__.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""**Agent** is a class that uses an LLM to choose a sequence of actions to take.
|
| 2 |
+
|
| 3 |
+
In Chains, a sequence of actions is hardcoded. In Agents,
|
| 4 |
+
a language model is used as a reasoning engine to determine which actions
|
| 5 |
+
to take and in which order.
|
| 6 |
+
|
| 7 |
+
Agents select and use **Tools** and **Toolkits** for actions.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import TYPE_CHECKING, Any
|
| 12 |
+
|
| 13 |
+
from langchain_core._api.path import as_import_path
|
| 14 |
+
from langchain_core.tools import Tool
|
| 15 |
+
from langchain_core.tools.convert import tool
|
| 16 |
+
|
| 17 |
+
from langchain_classic._api import create_importer
|
| 18 |
+
from langchain_classic.agents.agent import (
|
| 19 |
+
Agent,
|
| 20 |
+
AgentExecutor,
|
| 21 |
+
AgentOutputParser,
|
| 22 |
+
BaseMultiActionAgent,
|
| 23 |
+
BaseSingleActionAgent,
|
| 24 |
+
LLMSingleActionAgent,
|
| 25 |
+
)
|
| 26 |
+
from langchain_classic.agents.agent_iterator import AgentExecutorIterator
|
| 27 |
+
from langchain_classic.agents.agent_toolkits.vectorstore.base import (
|
| 28 |
+
create_vectorstore_agent,
|
| 29 |
+
create_vectorstore_router_agent,
|
| 30 |
+
)
|
| 31 |
+
from langchain_classic.agents.agent_types import AgentType
|
| 32 |
+
from langchain_classic.agents.conversational.base import ConversationalAgent
|
| 33 |
+
from langchain_classic.agents.conversational_chat.base import ConversationalChatAgent
|
| 34 |
+
from langchain_classic.agents.initialize import initialize_agent
|
| 35 |
+
from langchain_classic.agents.json_chat.base import create_json_chat_agent
|
| 36 |
+
from langchain_classic.agents.loading import load_agent
|
| 37 |
+
from langchain_classic.agents.mrkl.base import MRKLChain, ZeroShotAgent
|
| 38 |
+
from langchain_classic.agents.openai_functions_agent.base import (
|
| 39 |
+
OpenAIFunctionsAgent,
|
| 40 |
+
create_openai_functions_agent,
|
| 41 |
+
)
|
| 42 |
+
from langchain_classic.agents.openai_functions_multi_agent.base import (
|
| 43 |
+
OpenAIMultiFunctionsAgent,
|
| 44 |
+
)
|
| 45 |
+
from langchain_classic.agents.openai_tools.base import create_openai_tools_agent
|
| 46 |
+
from langchain_classic.agents.react.agent import create_react_agent
|
| 47 |
+
from langchain_classic.agents.react.base import ReActChain, ReActTextWorldAgent
|
| 48 |
+
from langchain_classic.agents.self_ask_with_search.base import (
|
| 49 |
+
SelfAskWithSearchChain,
|
| 50 |
+
create_self_ask_with_search_agent,
|
| 51 |
+
)
|
| 52 |
+
from langchain_classic.agents.structured_chat.base import (
|
| 53 |
+
StructuredChatAgent,
|
| 54 |
+
create_structured_chat_agent,
|
| 55 |
+
)
|
| 56 |
+
from langchain_classic.agents.tool_calling_agent.base import create_tool_calling_agent
|
| 57 |
+
from langchain_classic.agents.xml.base import XMLAgent, create_xml_agent
|
| 58 |
+
|
| 59 |
+
if TYPE_CHECKING:
|
| 60 |
+
from langchain_community.agent_toolkits.json.base import create_json_agent
|
| 61 |
+
from langchain_community.agent_toolkits.load_tools import (
|
| 62 |
+
get_all_tool_names,
|
| 63 |
+
load_huggingface_tool,
|
| 64 |
+
load_tools,
|
| 65 |
+
)
|
| 66 |
+
from langchain_community.agent_toolkits.openapi.base import create_openapi_agent
|
| 67 |
+
from langchain_community.agent_toolkits.powerbi.base import create_pbi_agent
|
| 68 |
+
from langchain_community.agent_toolkits.powerbi.chat_base import (
|
| 69 |
+
create_pbi_chat_agent,
|
| 70 |
+
)
|
| 71 |
+
from langchain_community.agent_toolkits.spark_sql.base import create_spark_sql_agent
|
| 72 |
+
from langchain_community.agent_toolkits.sql.base import create_sql_agent
|
| 73 |
+
|
| 74 |
+
DEPRECATED_CODE = [
|
| 75 |
+
"create_csv_agent",
|
| 76 |
+
"create_pandas_dataframe_agent",
|
| 77 |
+
"create_spark_dataframe_agent",
|
| 78 |
+
"create_xorbits_agent",
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
# Create a way to dynamically look up deprecated imports.
|
| 82 |
+
# Used to consolidate logic for raising deprecation warnings and
|
| 83 |
+
# handling optional imports.
|
| 84 |
+
DEPRECATED_LOOKUP = {
|
| 85 |
+
"create_json_agent": "langchain_community.agent_toolkits.json.base",
|
| 86 |
+
"create_openapi_agent": "langchain_community.agent_toolkits.openapi.base",
|
| 87 |
+
"create_pbi_agent": "langchain_community.agent_toolkits.powerbi.base",
|
| 88 |
+
"create_pbi_chat_agent": "langchain_community.agent_toolkits.powerbi.chat_base",
|
| 89 |
+
"create_spark_sql_agent": "langchain_community.agent_toolkits.spark_sql.base",
|
| 90 |
+
"create_sql_agent": "langchain_community.agent_toolkits.sql.base",
|
| 91 |
+
"load_tools": "langchain_community.agent_toolkits.load_tools",
|
| 92 |
+
"load_huggingface_tool": "langchain_community.agent_toolkits.load_tools",
|
| 93 |
+
"get_all_tool_names": "langchain_community.agent_toolkits.load_tools",
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def __getattr__(name: str) -> Any:
|
| 100 |
+
"""Get attr name."""
|
| 101 |
+
if name in DEPRECATED_CODE:
|
| 102 |
+
# Get directory of langchain package
|
| 103 |
+
here = Path(__file__).parents[1]
|
| 104 |
+
relative_path = as_import_path(
|
| 105 |
+
Path(__file__).parent,
|
| 106 |
+
suffix=name,
|
| 107 |
+
relative_to=here,
|
| 108 |
+
)
|
| 109 |
+
old_path = "langchain_classic." + relative_path
|
| 110 |
+
new_path = "langchain_experimental." + relative_path
|
| 111 |
+
msg = (
|
| 112 |
+
f"{name} has been moved to langchain_experimental. "
|
| 113 |
+
"See https://github.com/langchain-ai/langchain/discussions/11680"
|
| 114 |
+
"for more information.\n"
|
| 115 |
+
f"Please update your import statement from: `{old_path}` to `{new_path}`."
|
| 116 |
+
)
|
| 117 |
+
raise ImportError(msg)
|
| 118 |
+
return _import_attribute(name)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
__all__ = [
|
| 122 |
+
"Agent",
|
| 123 |
+
"AgentExecutor",
|
| 124 |
+
"AgentExecutorIterator",
|
| 125 |
+
"AgentOutputParser",
|
| 126 |
+
"AgentType",
|
| 127 |
+
"BaseMultiActionAgent",
|
| 128 |
+
"BaseSingleActionAgent",
|
| 129 |
+
"ConversationalAgent",
|
| 130 |
+
"ConversationalChatAgent",
|
| 131 |
+
"LLMSingleActionAgent",
|
| 132 |
+
"MRKLChain",
|
| 133 |
+
"OpenAIFunctionsAgent",
|
| 134 |
+
"OpenAIMultiFunctionsAgent",
|
| 135 |
+
"ReActChain",
|
| 136 |
+
"ReActTextWorldAgent",
|
| 137 |
+
"SelfAskWithSearchChain",
|
| 138 |
+
"StructuredChatAgent",
|
| 139 |
+
"Tool",
|
| 140 |
+
"XMLAgent",
|
| 141 |
+
"ZeroShotAgent",
|
| 142 |
+
"create_json_agent",
|
| 143 |
+
"create_json_chat_agent",
|
| 144 |
+
"create_openai_functions_agent",
|
| 145 |
+
"create_openai_tools_agent",
|
| 146 |
+
"create_openapi_agent",
|
| 147 |
+
"create_pbi_agent",
|
| 148 |
+
"create_pbi_chat_agent",
|
| 149 |
+
"create_react_agent",
|
| 150 |
+
"create_self_ask_with_search_agent",
|
| 151 |
+
"create_spark_sql_agent",
|
| 152 |
+
"create_sql_agent",
|
| 153 |
+
"create_structured_chat_agent",
|
| 154 |
+
"create_tool_calling_agent",
|
| 155 |
+
"create_vectorstore_agent",
|
| 156 |
+
"create_vectorstore_router_agent",
|
| 157 |
+
"create_xml_agent",
|
| 158 |
+
"get_all_tool_names",
|
| 159 |
+
"initialize_agent",
|
| 160 |
+
"load_agent",
|
| 161 |
+
"load_huggingface_tool",
|
| 162 |
+
"load_tools",
|
| 163 |
+
"tool",
|
| 164 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/agent.py
ADDED
|
@@ -0,0 +1,1792 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Chain that takes in an input and produces an action and action input."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import builtins
|
| 7 |
+
import contextlib
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
import time
|
| 11 |
+
from abc import abstractmethod
|
| 12 |
+
from collections.abc import AsyncIterator, Callable, Iterator, Sequence
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import (
|
| 15 |
+
Any,
|
| 16 |
+
cast,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
import yaml
|
| 20 |
+
from langchain_core._api import deprecated
|
| 21 |
+
from langchain_core.agents import AgentAction, AgentFinish, AgentStep
|
| 22 |
+
from langchain_core.callbacks import (
|
| 23 |
+
AsyncCallbackManagerForChainRun,
|
| 24 |
+
AsyncCallbackManagerForToolRun,
|
| 25 |
+
BaseCallbackManager,
|
| 26 |
+
CallbackManagerForChainRun,
|
| 27 |
+
CallbackManagerForToolRun,
|
| 28 |
+
Callbacks,
|
| 29 |
+
)
|
| 30 |
+
from langchain_core.exceptions import OutputParserException
|
| 31 |
+
from langchain_core.language_models import BaseLanguageModel
|
| 32 |
+
from langchain_core.messages import BaseMessage
|
| 33 |
+
from langchain_core.output_parsers import BaseOutputParser
|
| 34 |
+
from langchain_core.prompts import BasePromptTemplate
|
| 35 |
+
from langchain_core.prompts.few_shot import FewShotPromptTemplate
|
| 36 |
+
from langchain_core.prompts.prompt import PromptTemplate
|
| 37 |
+
from langchain_core.runnables import Runnable, RunnableConfig, ensure_config
|
| 38 |
+
from langchain_core.runnables.utils import AddableDict
|
| 39 |
+
from langchain_core.tools import BaseTool
|
| 40 |
+
from langchain_core.utils.input import get_color_mapping
|
| 41 |
+
from pydantic import BaseModel, ConfigDict, model_validator
|
| 42 |
+
from typing_extensions import Self, override
|
| 43 |
+
|
| 44 |
+
from langchain_classic._api.deprecation import AGENT_DEPRECATION_WARNING
|
| 45 |
+
from langchain_classic.agents.agent_iterator import AgentExecutorIterator
|
| 46 |
+
from langchain_classic.agents.agent_types import AgentType
|
| 47 |
+
from langchain_classic.agents.tools import InvalidTool
|
| 48 |
+
from langchain_classic.chains.base import Chain
|
| 49 |
+
from langchain_classic.chains.llm import LLMChain
|
| 50 |
+
from langchain_classic.utilities.asyncio import asyncio_timeout
|
| 51 |
+
|
| 52 |
+
logger = logging.getLogger(__name__)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class BaseSingleActionAgent(BaseModel):
|
| 56 |
+
"""Base Single Action Agent class."""
|
| 57 |
+
|
| 58 |
+
@property
|
| 59 |
+
def return_values(self) -> list[str]:
|
| 60 |
+
"""Return values of the agent."""
|
| 61 |
+
return ["output"]
|
| 62 |
+
|
| 63 |
+
def get_allowed_tools(self) -> list[str] | None:
|
| 64 |
+
"""Get allowed tools."""
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
@abstractmethod
|
| 68 |
+
def plan(
|
| 69 |
+
self,
|
| 70 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 71 |
+
callbacks: Callbacks = None,
|
| 72 |
+
**kwargs: Any,
|
| 73 |
+
) -> AgentAction | AgentFinish:
|
| 74 |
+
"""Given input, decided what to do.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 78 |
+
along with observations.
|
| 79 |
+
callbacks: Callbacks to run.
|
| 80 |
+
**kwargs: User inputs.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
Action specifying what tool to use.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
@abstractmethod
|
| 87 |
+
async def aplan(
|
| 88 |
+
self,
|
| 89 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 90 |
+
callbacks: Callbacks = None,
|
| 91 |
+
**kwargs: Any,
|
| 92 |
+
) -> AgentAction | AgentFinish:
|
| 93 |
+
"""Async given input, decided what to do.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 97 |
+
along with observations.
|
| 98 |
+
callbacks: Callbacks to run.
|
| 99 |
+
**kwargs: User inputs.
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
Action specifying what tool to use.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
@abstractmethod
|
| 107 |
+
def input_keys(self) -> list[str]:
|
| 108 |
+
"""Return the input keys."""
|
| 109 |
+
|
| 110 |
+
def return_stopped_response(
|
| 111 |
+
self,
|
| 112 |
+
early_stopping_method: str,
|
| 113 |
+
intermediate_steps: list[tuple[AgentAction, str]], # noqa: ARG002
|
| 114 |
+
**_: Any,
|
| 115 |
+
) -> AgentFinish:
|
| 116 |
+
"""Return response when agent has been stopped due to max iterations.
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
early_stopping_method: Method to use for early stopping.
|
| 120 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 121 |
+
along with observations.
|
| 122 |
+
|
| 123 |
+
Returns:
|
| 124 |
+
Agent finish object.
|
| 125 |
+
|
| 126 |
+
Raises:
|
| 127 |
+
ValueError: If `early_stopping_method` is not supported.
|
| 128 |
+
"""
|
| 129 |
+
if early_stopping_method == "force":
|
| 130 |
+
# `force` just returns a constant string
|
| 131 |
+
return AgentFinish(
|
| 132 |
+
{"output": "Agent stopped due to iteration limit or time limit."},
|
| 133 |
+
"",
|
| 134 |
+
)
|
| 135 |
+
msg = f"Got unsupported early_stopping_method `{early_stopping_method}`"
|
| 136 |
+
raise ValueError(msg)
|
| 137 |
+
|
| 138 |
+
@classmethod
|
| 139 |
+
def from_llm_and_tools(
|
| 140 |
+
cls,
|
| 141 |
+
llm: BaseLanguageModel,
|
| 142 |
+
tools: Sequence[BaseTool],
|
| 143 |
+
callback_manager: BaseCallbackManager | None = None,
|
| 144 |
+
**kwargs: Any,
|
| 145 |
+
) -> BaseSingleActionAgent:
|
| 146 |
+
"""Construct an agent from an LLM and tools.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
llm: Language model to use.
|
| 150 |
+
tools: Tools to use.
|
| 151 |
+
callback_manager: Callback manager to use.
|
| 152 |
+
kwargs: Additional arguments.
|
| 153 |
+
|
| 154 |
+
Returns:
|
| 155 |
+
Agent object.
|
| 156 |
+
"""
|
| 157 |
+
raise NotImplementedError
|
| 158 |
+
|
| 159 |
+
@property
|
| 160 |
+
def _agent_type(self) -> str:
|
| 161 |
+
"""Return Identifier of an agent type."""
|
| 162 |
+
raise NotImplementedError
|
| 163 |
+
|
| 164 |
+
@override
|
| 165 |
+
def dict(self, **kwargs: Any) -> builtins.dict:
|
| 166 |
+
"""Return dictionary representation of agent.
|
| 167 |
+
|
| 168 |
+
Returns:
|
| 169 |
+
Dictionary representation of agent.
|
| 170 |
+
"""
|
| 171 |
+
_dict = super().model_dump()
|
| 172 |
+
try:
|
| 173 |
+
_type = self._agent_type
|
| 174 |
+
except NotImplementedError:
|
| 175 |
+
_type = None
|
| 176 |
+
if isinstance(_type, AgentType):
|
| 177 |
+
_dict["_type"] = str(_type.value)
|
| 178 |
+
elif _type is not None:
|
| 179 |
+
_dict["_type"] = _type
|
| 180 |
+
return _dict
|
| 181 |
+
|
| 182 |
+
def save(self, file_path: Path | str) -> None:
|
| 183 |
+
"""Save the agent.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
file_path: Path to file to save the agent to.
|
| 187 |
+
|
| 188 |
+
Example:
|
| 189 |
+
```python
|
| 190 |
+
# If working with agent executor
|
| 191 |
+
agent.agent.save(file_path="path/agent.yaml")
|
| 192 |
+
```
|
| 193 |
+
"""
|
| 194 |
+
# Convert file to Path object.
|
| 195 |
+
save_path = Path(file_path) if isinstance(file_path, str) else file_path
|
| 196 |
+
|
| 197 |
+
directory_path = save_path.parent
|
| 198 |
+
directory_path.mkdir(parents=True, exist_ok=True)
|
| 199 |
+
|
| 200 |
+
# Fetch dictionary to save
|
| 201 |
+
agent_dict = self.dict()
|
| 202 |
+
if "_type" not in agent_dict:
|
| 203 |
+
msg = f"Agent {self} does not support saving"
|
| 204 |
+
raise NotImplementedError(msg)
|
| 205 |
+
|
| 206 |
+
if save_path.suffix == ".json":
|
| 207 |
+
with save_path.open("w") as f:
|
| 208 |
+
json.dump(agent_dict, f, indent=4)
|
| 209 |
+
elif save_path.suffix.endswith((".yaml", ".yml")):
|
| 210 |
+
with save_path.open("w") as f:
|
| 211 |
+
yaml.dump(agent_dict, f, default_flow_style=False)
|
| 212 |
+
else:
|
| 213 |
+
msg = f"{save_path} must be json or yaml"
|
| 214 |
+
raise ValueError(msg)
|
| 215 |
+
|
| 216 |
+
def tool_run_logging_kwargs(self) -> builtins.dict:
|
| 217 |
+
"""Return logging kwargs for tool run."""
|
| 218 |
+
return {}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class BaseMultiActionAgent(BaseModel):
|
| 222 |
+
"""Base Multi Action Agent class."""
|
| 223 |
+
|
| 224 |
+
@property
|
| 225 |
+
def return_values(self) -> list[str]:
|
| 226 |
+
"""Return values of the agent."""
|
| 227 |
+
return ["output"]
|
| 228 |
+
|
| 229 |
+
def get_allowed_tools(self) -> list[str] | None:
|
| 230 |
+
"""Get allowed tools.
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
Allowed tools.
|
| 234 |
+
"""
|
| 235 |
+
return None
|
| 236 |
+
|
| 237 |
+
@abstractmethod
|
| 238 |
+
def plan(
|
| 239 |
+
self,
|
| 240 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 241 |
+
callbacks: Callbacks = None,
|
| 242 |
+
**kwargs: Any,
|
| 243 |
+
) -> list[AgentAction] | AgentFinish:
|
| 244 |
+
"""Given input, decided what to do.
|
| 245 |
+
|
| 246 |
+
Args:
|
| 247 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 248 |
+
along with the observations.
|
| 249 |
+
callbacks: Callbacks to run.
|
| 250 |
+
**kwargs: User inputs.
|
| 251 |
+
|
| 252 |
+
Returns:
|
| 253 |
+
Actions specifying what tool to use.
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
@abstractmethod
|
| 257 |
+
async def aplan(
|
| 258 |
+
self,
|
| 259 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 260 |
+
callbacks: Callbacks = None,
|
| 261 |
+
**kwargs: Any,
|
| 262 |
+
) -> list[AgentAction] | AgentFinish:
|
| 263 |
+
"""Async given input, decided what to do.
|
| 264 |
+
|
| 265 |
+
Args:
|
| 266 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 267 |
+
along with the observations.
|
| 268 |
+
callbacks: Callbacks to run.
|
| 269 |
+
**kwargs: User inputs.
|
| 270 |
+
|
| 271 |
+
Returns:
|
| 272 |
+
Actions specifying what tool to use.
|
| 273 |
+
"""
|
| 274 |
+
|
| 275 |
+
@property
|
| 276 |
+
@abstractmethod
|
| 277 |
+
def input_keys(self) -> list[str]:
|
| 278 |
+
"""Return the input keys."""
|
| 279 |
+
|
| 280 |
+
def return_stopped_response(
|
| 281 |
+
self,
|
| 282 |
+
early_stopping_method: str,
|
| 283 |
+
intermediate_steps: list[tuple[AgentAction, str]], # noqa: ARG002
|
| 284 |
+
**_: Any,
|
| 285 |
+
) -> AgentFinish:
|
| 286 |
+
"""Return response when agent has been stopped due to max iterations.
|
| 287 |
+
|
| 288 |
+
Args:
|
| 289 |
+
early_stopping_method: Method to use for early stopping.
|
| 290 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 291 |
+
along with observations.
|
| 292 |
+
|
| 293 |
+
Returns:
|
| 294 |
+
Agent finish object.
|
| 295 |
+
|
| 296 |
+
Raises:
|
| 297 |
+
ValueError: If `early_stopping_method` is not supported.
|
| 298 |
+
"""
|
| 299 |
+
if early_stopping_method == "force":
|
| 300 |
+
# `force` just returns a constant string
|
| 301 |
+
return AgentFinish({"output": "Agent stopped due to max iterations."}, "")
|
| 302 |
+
msg = f"Got unsupported early_stopping_method `{early_stopping_method}`"
|
| 303 |
+
raise ValueError(msg)
|
| 304 |
+
|
| 305 |
+
@property
|
| 306 |
+
def _agent_type(self) -> str:
|
| 307 |
+
"""Return Identifier of an agent type."""
|
| 308 |
+
raise NotImplementedError
|
| 309 |
+
|
| 310 |
+
@override
|
| 311 |
+
def dict(self, **kwargs: Any) -> builtins.dict:
|
| 312 |
+
"""Return dictionary representation of agent."""
|
| 313 |
+
_dict = super().model_dump()
|
| 314 |
+
with contextlib.suppress(NotImplementedError):
|
| 315 |
+
_dict["_type"] = str(self._agent_type)
|
| 316 |
+
return _dict
|
| 317 |
+
|
| 318 |
+
def save(self, file_path: Path | str) -> None:
|
| 319 |
+
"""Save the agent.
|
| 320 |
+
|
| 321 |
+
Args:
|
| 322 |
+
file_path: Path to file to save the agent to.
|
| 323 |
+
|
| 324 |
+
Raises:
|
| 325 |
+
NotImplementedError: If agent does not support saving.
|
| 326 |
+
ValueError: If `file_path` is not json or yaml.
|
| 327 |
+
|
| 328 |
+
Example:
|
| 329 |
+
```python
|
| 330 |
+
# If working with agent executor
|
| 331 |
+
agent.agent.save(file_path="path/agent.yaml")
|
| 332 |
+
```
|
| 333 |
+
"""
|
| 334 |
+
# Convert file to Path object.
|
| 335 |
+
save_path = Path(file_path) if isinstance(file_path, str) else file_path
|
| 336 |
+
|
| 337 |
+
# Fetch dictionary to save
|
| 338 |
+
agent_dict = self.dict()
|
| 339 |
+
if "_type" not in agent_dict:
|
| 340 |
+
msg = f"Agent {self} does not support saving."
|
| 341 |
+
raise NotImplementedError(msg)
|
| 342 |
+
|
| 343 |
+
directory_path = save_path.parent
|
| 344 |
+
directory_path.mkdir(parents=True, exist_ok=True)
|
| 345 |
+
|
| 346 |
+
if save_path.suffix == ".json":
|
| 347 |
+
with save_path.open("w") as f:
|
| 348 |
+
json.dump(agent_dict, f, indent=4)
|
| 349 |
+
elif save_path.suffix.endswith((".yaml", ".yml")):
|
| 350 |
+
with save_path.open("w") as f:
|
| 351 |
+
yaml.dump(agent_dict, f, default_flow_style=False)
|
| 352 |
+
else:
|
| 353 |
+
msg = f"{save_path} must be json or yaml"
|
| 354 |
+
raise ValueError(msg)
|
| 355 |
+
|
| 356 |
+
def tool_run_logging_kwargs(self) -> builtins.dict:
|
| 357 |
+
"""Return logging kwargs for tool run."""
|
| 358 |
+
return {}
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class AgentOutputParser(BaseOutputParser[AgentAction | AgentFinish]):
|
| 362 |
+
"""Base class for parsing agent output into agent action/finish."""
|
| 363 |
+
|
| 364 |
+
@abstractmethod
|
| 365 |
+
def parse(self, text: str) -> AgentAction | AgentFinish:
|
| 366 |
+
"""Parse text into agent action/finish."""
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class MultiActionAgentOutputParser(
|
| 370 |
+
BaseOutputParser[list[AgentAction] | AgentFinish],
|
| 371 |
+
):
|
| 372 |
+
"""Base class for parsing agent output into agent actions/finish.
|
| 373 |
+
|
| 374 |
+
This is used for agents that can return multiple actions.
|
| 375 |
+
"""
|
| 376 |
+
|
| 377 |
+
@abstractmethod
|
| 378 |
+
def parse(self, text: str) -> list[AgentAction] | AgentFinish:
|
| 379 |
+
"""Parse text into agent actions/finish.
|
| 380 |
+
|
| 381 |
+
Args:
|
| 382 |
+
text: Text to parse.
|
| 383 |
+
|
| 384 |
+
Returns:
|
| 385 |
+
List of agent actions or agent finish.
|
| 386 |
+
"""
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class RunnableAgent(BaseSingleActionAgent):
|
| 390 |
+
"""Agent powered by Runnables."""
|
| 391 |
+
|
| 392 |
+
runnable: Runnable[dict, AgentAction | AgentFinish]
|
| 393 |
+
"""Runnable to call to get agent action."""
|
| 394 |
+
input_keys_arg: list[str] = []
|
| 395 |
+
return_keys_arg: list[str] = []
|
| 396 |
+
stream_runnable: bool = True
|
| 397 |
+
"""Whether to stream from the runnable or not.
|
| 398 |
+
|
| 399 |
+
If `True` then underlying LLM is invoked in a streaming fashion to make it possible
|
| 400 |
+
to get access to the individual LLM tokens when using stream_log with the
|
| 401 |
+
`AgentExecutor`. If `False` then LLM is invoked in a non-streaming fashion and
|
| 402 |
+
individual LLM tokens will not be available in stream_log.
|
| 403 |
+
"""
|
| 404 |
+
|
| 405 |
+
model_config = ConfigDict(
|
| 406 |
+
arbitrary_types_allowed=True,
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
@property
|
| 410 |
+
def return_values(self) -> list[str]:
|
| 411 |
+
"""Return values of the agent."""
|
| 412 |
+
return self.return_keys_arg
|
| 413 |
+
|
| 414 |
+
@property
|
| 415 |
+
def input_keys(self) -> list[str]:
|
| 416 |
+
"""Return the input keys."""
|
| 417 |
+
return self.input_keys_arg
|
| 418 |
+
|
| 419 |
+
def plan(
|
| 420 |
+
self,
|
| 421 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 422 |
+
callbacks: Callbacks = None,
|
| 423 |
+
**kwargs: Any,
|
| 424 |
+
) -> AgentAction | AgentFinish:
|
| 425 |
+
"""Based on past history and current inputs, decide what to do.
|
| 426 |
+
|
| 427 |
+
Args:
|
| 428 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 429 |
+
along with the observations.
|
| 430 |
+
callbacks: Callbacks to run.
|
| 431 |
+
**kwargs: User inputs.
|
| 432 |
+
|
| 433 |
+
Returns:
|
| 434 |
+
Action specifying what tool to use.
|
| 435 |
+
"""
|
| 436 |
+
inputs = {**kwargs, "intermediate_steps": intermediate_steps}
|
| 437 |
+
final_output: Any = None
|
| 438 |
+
if self.stream_runnable:
|
| 439 |
+
# Use streaming to make sure that the underlying LLM is invoked in a
|
| 440 |
+
# streaming
|
| 441 |
+
# fashion to make it possible to get access to the individual LLM tokens
|
| 442 |
+
# when using stream_log with the AgentExecutor.
|
| 443 |
+
# Because the response from the plan is not a generator, we need to
|
| 444 |
+
# accumulate the output into final output and return that.
|
| 445 |
+
for chunk in self.runnable.stream(inputs, config={"callbacks": callbacks}):
|
| 446 |
+
if final_output is None:
|
| 447 |
+
final_output = chunk
|
| 448 |
+
else:
|
| 449 |
+
final_output += chunk
|
| 450 |
+
else:
|
| 451 |
+
final_output = self.runnable.invoke(inputs, config={"callbacks": callbacks})
|
| 452 |
+
|
| 453 |
+
return final_output
|
| 454 |
+
|
| 455 |
+
async def aplan(
|
| 456 |
+
self,
|
| 457 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 458 |
+
callbacks: Callbacks = None,
|
| 459 |
+
**kwargs: Any,
|
| 460 |
+
) -> AgentAction | AgentFinish:
|
| 461 |
+
"""Async based on past history and current inputs, decide what to do.
|
| 462 |
+
|
| 463 |
+
Args:
|
| 464 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 465 |
+
along with observations.
|
| 466 |
+
callbacks: Callbacks to run.
|
| 467 |
+
**kwargs: User inputs.
|
| 468 |
+
|
| 469 |
+
Returns:
|
| 470 |
+
Action specifying what tool to use.
|
| 471 |
+
"""
|
| 472 |
+
inputs = {**kwargs, "intermediate_steps": intermediate_steps}
|
| 473 |
+
final_output: Any = None
|
| 474 |
+
if self.stream_runnable:
|
| 475 |
+
# Use streaming to make sure that the underlying LLM is invoked in a
|
| 476 |
+
# streaming
|
| 477 |
+
# fashion to make it possible to get access to the individual LLM tokens
|
| 478 |
+
# when using stream_log with the AgentExecutor.
|
| 479 |
+
# Because the response from the plan is not a generator, we need to
|
| 480 |
+
# accumulate the output into final output and return that.
|
| 481 |
+
async for chunk in self.runnable.astream(
|
| 482 |
+
inputs,
|
| 483 |
+
config={"callbacks": callbacks},
|
| 484 |
+
):
|
| 485 |
+
if final_output is None:
|
| 486 |
+
final_output = chunk
|
| 487 |
+
else:
|
| 488 |
+
final_output += chunk
|
| 489 |
+
else:
|
| 490 |
+
final_output = await self.runnable.ainvoke(
|
| 491 |
+
inputs,
|
| 492 |
+
config={"callbacks": callbacks},
|
| 493 |
+
)
|
| 494 |
+
return final_output
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
class RunnableMultiActionAgent(BaseMultiActionAgent):
|
| 498 |
+
"""Agent powered by Runnables."""
|
| 499 |
+
|
| 500 |
+
runnable: Runnable[dict, list[AgentAction] | AgentFinish]
|
| 501 |
+
"""Runnable to call to get agent actions."""
|
| 502 |
+
input_keys_arg: list[str] = []
|
| 503 |
+
return_keys_arg: list[str] = []
|
| 504 |
+
stream_runnable: bool = True
|
| 505 |
+
"""Whether to stream from the runnable or not.
|
| 506 |
+
|
| 507 |
+
If `True` then underlying LLM is invoked in a streaming fashion to make it possible
|
| 508 |
+
to get access to the individual LLM tokens when using stream_log with the
|
| 509 |
+
`AgentExecutor`. If `False` then LLM is invoked in a non-streaming fashion and
|
| 510 |
+
individual LLM tokens will not be available in stream_log.
|
| 511 |
+
"""
|
| 512 |
+
|
| 513 |
+
model_config = ConfigDict(
|
| 514 |
+
arbitrary_types_allowed=True,
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
@property
|
| 518 |
+
def return_values(self) -> list[str]:
|
| 519 |
+
"""Return values of the agent."""
|
| 520 |
+
return self.return_keys_arg
|
| 521 |
+
|
| 522 |
+
@property
|
| 523 |
+
def input_keys(self) -> list[str]:
|
| 524 |
+
"""Return the input keys.
|
| 525 |
+
|
| 526 |
+
Returns:
|
| 527 |
+
List of input keys.
|
| 528 |
+
"""
|
| 529 |
+
return self.input_keys_arg
|
| 530 |
+
|
| 531 |
+
def plan(
|
| 532 |
+
self,
|
| 533 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 534 |
+
callbacks: Callbacks = None,
|
| 535 |
+
**kwargs: Any,
|
| 536 |
+
) -> list[AgentAction] | AgentFinish:
|
| 537 |
+
"""Based on past history and current inputs, decide what to do.
|
| 538 |
+
|
| 539 |
+
Args:
|
| 540 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 541 |
+
along with the observations.
|
| 542 |
+
callbacks: Callbacks to run.
|
| 543 |
+
**kwargs: User inputs.
|
| 544 |
+
|
| 545 |
+
Returns:
|
| 546 |
+
Action specifying what tool to use.
|
| 547 |
+
"""
|
| 548 |
+
inputs = {**kwargs, "intermediate_steps": intermediate_steps}
|
| 549 |
+
final_output: Any = None
|
| 550 |
+
if self.stream_runnable:
|
| 551 |
+
# Use streaming to make sure that the underlying LLM is invoked in a
|
| 552 |
+
# streaming
|
| 553 |
+
# fashion to make it possible to get access to the individual LLM tokens
|
| 554 |
+
# when using stream_log with the AgentExecutor.
|
| 555 |
+
# Because the response from the plan is not a generator, we need to
|
| 556 |
+
# accumulate the output into final output and return that.
|
| 557 |
+
for chunk in self.runnable.stream(inputs, config={"callbacks": callbacks}):
|
| 558 |
+
if final_output is None:
|
| 559 |
+
final_output = chunk
|
| 560 |
+
else:
|
| 561 |
+
final_output += chunk
|
| 562 |
+
else:
|
| 563 |
+
final_output = self.runnable.invoke(inputs, config={"callbacks": callbacks})
|
| 564 |
+
|
| 565 |
+
return final_output
|
| 566 |
+
|
| 567 |
+
async def aplan(
|
| 568 |
+
self,
|
| 569 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 570 |
+
callbacks: Callbacks = None,
|
| 571 |
+
**kwargs: Any,
|
| 572 |
+
) -> list[AgentAction] | AgentFinish:
|
| 573 |
+
"""Async based on past history and current inputs, decide what to do.
|
| 574 |
+
|
| 575 |
+
Args:
|
| 576 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 577 |
+
along with observations.
|
| 578 |
+
callbacks: Callbacks to run.
|
| 579 |
+
**kwargs: User inputs.
|
| 580 |
+
|
| 581 |
+
Returns:
|
| 582 |
+
Action specifying what tool to use.
|
| 583 |
+
"""
|
| 584 |
+
inputs = {**kwargs, "intermediate_steps": intermediate_steps}
|
| 585 |
+
final_output: Any = None
|
| 586 |
+
if self.stream_runnable:
|
| 587 |
+
# Use streaming to make sure that the underlying LLM is invoked in a
|
| 588 |
+
# streaming
|
| 589 |
+
# fashion to make it possible to get access to the individual LLM tokens
|
| 590 |
+
# when using stream_log with the AgentExecutor.
|
| 591 |
+
# Because the response from the plan is not a generator, we need to
|
| 592 |
+
# accumulate the output into final output and return that.
|
| 593 |
+
async for chunk in self.runnable.astream(
|
| 594 |
+
inputs,
|
| 595 |
+
config={"callbacks": callbacks},
|
| 596 |
+
):
|
| 597 |
+
if final_output is None:
|
| 598 |
+
final_output = chunk
|
| 599 |
+
else:
|
| 600 |
+
final_output += chunk
|
| 601 |
+
else:
|
| 602 |
+
final_output = await self.runnable.ainvoke(
|
| 603 |
+
inputs,
|
| 604 |
+
config={"callbacks": callbacks},
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
return final_output
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
@deprecated(
|
| 611 |
+
"0.1.0",
|
| 612 |
+
message=AGENT_DEPRECATION_WARNING,
|
| 613 |
+
removal="2.0.0",
|
| 614 |
+
)
|
| 615 |
+
class LLMSingleActionAgent(BaseSingleActionAgent):
|
| 616 |
+
"""Base class for single action agents."""
|
| 617 |
+
|
| 618 |
+
llm_chain: LLMChain
|
| 619 |
+
"""LLMChain to use for agent."""
|
| 620 |
+
output_parser: AgentOutputParser
|
| 621 |
+
"""Output parser to use for agent."""
|
| 622 |
+
stop: list[str]
|
| 623 |
+
"""List of strings to stop on."""
|
| 624 |
+
|
| 625 |
+
@property
|
| 626 |
+
def input_keys(self) -> list[str]:
|
| 627 |
+
"""Return the input keys.
|
| 628 |
+
|
| 629 |
+
Returns:
|
| 630 |
+
List of input keys.
|
| 631 |
+
"""
|
| 632 |
+
return list(set(self.llm_chain.input_keys) - {"intermediate_steps"})
|
| 633 |
+
|
| 634 |
+
@override
|
| 635 |
+
def dict(self, **kwargs: Any) -> builtins.dict:
|
| 636 |
+
"""Return dictionary representation of agent."""
|
| 637 |
+
_dict = super().dict()
|
| 638 |
+
del _dict["output_parser"]
|
| 639 |
+
return _dict
|
| 640 |
+
|
| 641 |
+
def plan(
|
| 642 |
+
self,
|
| 643 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 644 |
+
callbacks: Callbacks = None,
|
| 645 |
+
**kwargs: Any,
|
| 646 |
+
) -> AgentAction | AgentFinish:
|
| 647 |
+
"""Given input, decided what to do.
|
| 648 |
+
|
| 649 |
+
Args:
|
| 650 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 651 |
+
along with the observations.
|
| 652 |
+
callbacks: Callbacks to run.
|
| 653 |
+
**kwargs: User inputs.
|
| 654 |
+
|
| 655 |
+
Returns:
|
| 656 |
+
Action specifying what tool to use.
|
| 657 |
+
"""
|
| 658 |
+
output = self.llm_chain.run(
|
| 659 |
+
intermediate_steps=intermediate_steps,
|
| 660 |
+
stop=self.stop,
|
| 661 |
+
callbacks=callbacks,
|
| 662 |
+
**kwargs,
|
| 663 |
+
)
|
| 664 |
+
return self.output_parser.parse(output)
|
| 665 |
+
|
| 666 |
+
async def aplan(
|
| 667 |
+
self,
|
| 668 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 669 |
+
callbacks: Callbacks = None,
|
| 670 |
+
**kwargs: Any,
|
| 671 |
+
) -> AgentAction | AgentFinish:
|
| 672 |
+
"""Async given input, decided what to do.
|
| 673 |
+
|
| 674 |
+
Args:
|
| 675 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 676 |
+
along with observations.
|
| 677 |
+
callbacks: Callbacks to run.
|
| 678 |
+
**kwargs: User inputs.
|
| 679 |
+
|
| 680 |
+
Returns:
|
| 681 |
+
Action specifying what tool to use.
|
| 682 |
+
"""
|
| 683 |
+
output = await self.llm_chain.arun(
|
| 684 |
+
intermediate_steps=intermediate_steps,
|
| 685 |
+
stop=self.stop,
|
| 686 |
+
callbacks=callbacks,
|
| 687 |
+
**kwargs,
|
| 688 |
+
)
|
| 689 |
+
return self.output_parser.parse(output)
|
| 690 |
+
|
| 691 |
+
def tool_run_logging_kwargs(self) -> builtins.dict:
|
| 692 |
+
"""Return logging kwargs for tool run."""
|
| 693 |
+
return {
|
| 694 |
+
"llm_prefix": "",
|
| 695 |
+
"observation_prefix": "" if len(self.stop) == 0 else self.stop[0],
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
@deprecated(
|
| 700 |
+
"0.1.0",
|
| 701 |
+
message=AGENT_DEPRECATION_WARNING,
|
| 702 |
+
removal="2.0.0",
|
| 703 |
+
)
|
| 704 |
+
class Agent(BaseSingleActionAgent):
|
| 705 |
+
"""Agent that calls the language model and deciding the action.
|
| 706 |
+
|
| 707 |
+
This is driven by a LLMChain. The prompt in the LLMChain MUST include
|
| 708 |
+
a variable called "agent_scratchpad" where the agent can put its
|
| 709 |
+
intermediary work.
|
| 710 |
+
"""
|
| 711 |
+
|
| 712 |
+
llm_chain: LLMChain
|
| 713 |
+
"""LLMChain to use for agent."""
|
| 714 |
+
output_parser: AgentOutputParser
|
| 715 |
+
"""Output parser to use for agent."""
|
| 716 |
+
allowed_tools: list[str] | None = None
|
| 717 |
+
"""Allowed tools for the agent. If `None`, all tools are allowed."""
|
| 718 |
+
|
| 719 |
+
@override
|
| 720 |
+
def dict(self, **kwargs: Any) -> builtins.dict:
|
| 721 |
+
"""Return dictionary representation of agent."""
|
| 722 |
+
_dict = super().dict()
|
| 723 |
+
del _dict["output_parser"]
|
| 724 |
+
return _dict
|
| 725 |
+
|
| 726 |
+
def get_allowed_tools(self) -> list[str] | None:
|
| 727 |
+
"""Get allowed tools."""
|
| 728 |
+
return self.allowed_tools
|
| 729 |
+
|
| 730 |
+
@property
|
| 731 |
+
def return_values(self) -> list[str]:
|
| 732 |
+
"""Return values of the agent."""
|
| 733 |
+
return ["output"]
|
| 734 |
+
|
| 735 |
+
@property
|
| 736 |
+
def _stop(self) -> list[str]:
|
| 737 |
+
return [
|
| 738 |
+
f"\n{self.observation_prefix.rstrip()}",
|
| 739 |
+
f"\n\t{self.observation_prefix.rstrip()}",
|
| 740 |
+
]
|
| 741 |
+
|
| 742 |
+
def _construct_scratchpad(
|
| 743 |
+
self,
|
| 744 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 745 |
+
) -> str | list[BaseMessage]:
|
| 746 |
+
"""Construct the scratchpad that lets the agent continue its thought process."""
|
| 747 |
+
thoughts = ""
|
| 748 |
+
for action, observation in intermediate_steps:
|
| 749 |
+
thoughts += action.log
|
| 750 |
+
thoughts += f"\n{self.observation_prefix}{observation}\n{self.llm_prefix}"
|
| 751 |
+
return thoughts
|
| 752 |
+
|
| 753 |
+
def plan(
|
| 754 |
+
self,
|
| 755 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 756 |
+
callbacks: Callbacks = None,
|
| 757 |
+
**kwargs: Any,
|
| 758 |
+
) -> AgentAction | AgentFinish:
|
| 759 |
+
"""Given input, decided what to do.
|
| 760 |
+
|
| 761 |
+
Args:
|
| 762 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 763 |
+
along with observations.
|
| 764 |
+
callbacks: Callbacks to run.
|
| 765 |
+
**kwargs: User inputs.
|
| 766 |
+
|
| 767 |
+
Returns:
|
| 768 |
+
Action specifying what tool to use.
|
| 769 |
+
"""
|
| 770 |
+
full_inputs = self.get_full_inputs(intermediate_steps, **kwargs)
|
| 771 |
+
full_output = self.llm_chain.predict(callbacks=callbacks, **full_inputs)
|
| 772 |
+
return self.output_parser.parse(full_output)
|
| 773 |
+
|
| 774 |
+
async def aplan(
|
| 775 |
+
self,
|
| 776 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 777 |
+
callbacks: Callbacks = None,
|
| 778 |
+
**kwargs: Any,
|
| 779 |
+
) -> AgentAction | AgentFinish:
|
| 780 |
+
"""Async given input, decided what to do.
|
| 781 |
+
|
| 782 |
+
Args:
|
| 783 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 784 |
+
along with observations.
|
| 785 |
+
callbacks: Callbacks to run.
|
| 786 |
+
**kwargs: User inputs.
|
| 787 |
+
|
| 788 |
+
Returns:
|
| 789 |
+
Action specifying what tool to use.
|
| 790 |
+
"""
|
| 791 |
+
full_inputs = self.get_full_inputs(intermediate_steps, **kwargs)
|
| 792 |
+
full_output = await self.llm_chain.apredict(callbacks=callbacks, **full_inputs)
|
| 793 |
+
return await self.output_parser.aparse(full_output)
|
| 794 |
+
|
| 795 |
+
def get_full_inputs(
|
| 796 |
+
self,
|
| 797 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 798 |
+
**kwargs: Any,
|
| 799 |
+
) -> builtins.dict[str, Any]:
|
| 800 |
+
"""Create the full inputs for the LLMChain from intermediate steps.
|
| 801 |
+
|
| 802 |
+
Args:
|
| 803 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 804 |
+
along with observations.
|
| 805 |
+
**kwargs: User inputs.
|
| 806 |
+
|
| 807 |
+
Returns:
|
| 808 |
+
Full inputs for the LLMChain.
|
| 809 |
+
"""
|
| 810 |
+
thoughts = self._construct_scratchpad(intermediate_steps)
|
| 811 |
+
new_inputs = {"agent_scratchpad": thoughts, "stop": self._stop}
|
| 812 |
+
return {**kwargs, **new_inputs}
|
| 813 |
+
|
| 814 |
+
@property
|
| 815 |
+
def input_keys(self) -> list[str]:
|
| 816 |
+
"""Return the input keys."""
|
| 817 |
+
return list(set(self.llm_chain.input_keys) - {"agent_scratchpad"})
|
| 818 |
+
|
| 819 |
+
@model_validator(mode="after")
|
| 820 |
+
def validate_prompt(self) -> Self:
|
| 821 |
+
"""Validate that prompt matches format.
|
| 822 |
+
|
| 823 |
+
Args:
|
| 824 |
+
values: Values to validate.
|
| 825 |
+
|
| 826 |
+
Returns:
|
| 827 |
+
Validated values.
|
| 828 |
+
|
| 829 |
+
Raises:
|
| 830 |
+
ValueError: If `agent_scratchpad` is not in prompt.input_variables
|
| 831 |
+
and prompt is not a FewShotPromptTemplate or a PromptTemplate.
|
| 832 |
+
"""
|
| 833 |
+
prompt = self.llm_chain.prompt
|
| 834 |
+
if "agent_scratchpad" not in prompt.input_variables:
|
| 835 |
+
logger.warning(
|
| 836 |
+
"`agent_scratchpad` should be a variable in prompt.input_variables."
|
| 837 |
+
" Did not find it, so adding it at the end.",
|
| 838 |
+
)
|
| 839 |
+
prompt.input_variables.append("agent_scratchpad")
|
| 840 |
+
if isinstance(prompt, PromptTemplate):
|
| 841 |
+
prompt.template += "\n{agent_scratchpad}"
|
| 842 |
+
elif isinstance(prompt, FewShotPromptTemplate):
|
| 843 |
+
prompt.suffix += "\n{agent_scratchpad}"
|
| 844 |
+
else:
|
| 845 |
+
msg = f"Got unexpected prompt type {type(prompt)}"
|
| 846 |
+
raise ValueError(msg)
|
| 847 |
+
return self
|
| 848 |
+
|
| 849 |
+
@property
|
| 850 |
+
@abstractmethod
|
| 851 |
+
def observation_prefix(self) -> str:
|
| 852 |
+
"""Prefix to append the observation with."""
|
| 853 |
+
|
| 854 |
+
@property
|
| 855 |
+
@abstractmethod
|
| 856 |
+
def llm_prefix(self) -> str:
|
| 857 |
+
"""Prefix to append the LLM call with."""
|
| 858 |
+
|
| 859 |
+
@classmethod
|
| 860 |
+
@abstractmethod
|
| 861 |
+
def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate:
|
| 862 |
+
"""Create a prompt for this class.
|
| 863 |
+
|
| 864 |
+
Args:
|
| 865 |
+
tools: Tools to use.
|
| 866 |
+
|
| 867 |
+
Returns:
|
| 868 |
+
Prompt template.
|
| 869 |
+
"""
|
| 870 |
+
|
| 871 |
+
@classmethod
|
| 872 |
+
def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
|
| 873 |
+
"""Validate that appropriate tools are passed in.
|
| 874 |
+
|
| 875 |
+
Args:
|
| 876 |
+
tools: Tools to use.
|
| 877 |
+
"""
|
| 878 |
+
|
| 879 |
+
@classmethod
|
| 880 |
+
@abstractmethod
|
| 881 |
+
def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:
|
| 882 |
+
"""Get default output parser for this class."""
|
| 883 |
+
|
| 884 |
+
@classmethod
|
| 885 |
+
def from_llm_and_tools(
|
| 886 |
+
cls,
|
| 887 |
+
llm: BaseLanguageModel,
|
| 888 |
+
tools: Sequence[BaseTool],
|
| 889 |
+
callback_manager: BaseCallbackManager | None = None,
|
| 890 |
+
output_parser: AgentOutputParser | None = None,
|
| 891 |
+
**kwargs: Any,
|
| 892 |
+
) -> Agent:
|
| 893 |
+
"""Construct an agent from an LLM and tools.
|
| 894 |
+
|
| 895 |
+
Args:
|
| 896 |
+
llm: Language model to use.
|
| 897 |
+
tools: Tools to use.
|
| 898 |
+
callback_manager: Callback manager to use.
|
| 899 |
+
output_parser: Output parser to use.
|
| 900 |
+
kwargs: Additional arguments.
|
| 901 |
+
|
| 902 |
+
Returns:
|
| 903 |
+
Agent object.
|
| 904 |
+
"""
|
| 905 |
+
cls._validate_tools(tools)
|
| 906 |
+
llm_chain = LLMChain(
|
| 907 |
+
llm=llm,
|
| 908 |
+
prompt=cls.create_prompt(tools),
|
| 909 |
+
callback_manager=callback_manager,
|
| 910 |
+
)
|
| 911 |
+
tool_names = [tool.name for tool in tools]
|
| 912 |
+
_output_parser = output_parser or cls._get_default_output_parser()
|
| 913 |
+
return cls(
|
| 914 |
+
llm_chain=llm_chain,
|
| 915 |
+
allowed_tools=tool_names,
|
| 916 |
+
output_parser=_output_parser,
|
| 917 |
+
**kwargs,
|
| 918 |
+
)
|
| 919 |
+
|
| 920 |
+
def return_stopped_response(
|
| 921 |
+
self,
|
| 922 |
+
early_stopping_method: str,
|
| 923 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 924 |
+
**kwargs: Any,
|
| 925 |
+
) -> AgentFinish:
|
| 926 |
+
"""Return response when agent has been stopped due to max iterations.
|
| 927 |
+
|
| 928 |
+
Args:
|
| 929 |
+
early_stopping_method: Method to use for early stopping.
|
| 930 |
+
intermediate_steps: Steps the LLM has taken to date,
|
| 931 |
+
along with observations.
|
| 932 |
+
**kwargs: User inputs.
|
| 933 |
+
|
| 934 |
+
Returns:
|
| 935 |
+
Agent finish object.
|
| 936 |
+
|
| 937 |
+
Raises:
|
| 938 |
+
ValueError: If `early_stopping_method` is not in ['force', 'generate'].
|
| 939 |
+
"""
|
| 940 |
+
if early_stopping_method == "force":
|
| 941 |
+
# `force` just returns a constant string
|
| 942 |
+
return AgentFinish(
|
| 943 |
+
{"output": "Agent stopped due to iteration limit or time limit."},
|
| 944 |
+
"",
|
| 945 |
+
)
|
| 946 |
+
if early_stopping_method == "generate":
|
| 947 |
+
# Generate does one final forward pass
|
| 948 |
+
thoughts = ""
|
| 949 |
+
for action, observation in intermediate_steps:
|
| 950 |
+
thoughts += action.log
|
| 951 |
+
thoughts += (
|
| 952 |
+
f"\n{self.observation_prefix}{observation}\n{self.llm_prefix}"
|
| 953 |
+
)
|
| 954 |
+
# Adding to the previous steps, we now tell the LLM to make a final pred
|
| 955 |
+
thoughts += (
|
| 956 |
+
"\n\nI now need to return a final answer based on the previous steps:"
|
| 957 |
+
)
|
| 958 |
+
new_inputs = {"agent_scratchpad": thoughts, "stop": self._stop}
|
| 959 |
+
full_inputs = {**kwargs, **new_inputs}
|
| 960 |
+
full_output = self.llm_chain.predict(**full_inputs)
|
| 961 |
+
# We try to extract a final answer
|
| 962 |
+
parsed_output = self.output_parser.parse(full_output)
|
| 963 |
+
if isinstance(parsed_output, AgentFinish):
|
| 964 |
+
# If we can extract, we send the correct stuff
|
| 965 |
+
return parsed_output
|
| 966 |
+
# If we can extract, but the tool is not the final tool,
|
| 967 |
+
# we just return the full output
|
| 968 |
+
return AgentFinish({"output": full_output}, full_output)
|
| 969 |
+
msg = (
|
| 970 |
+
"early_stopping_method should be one of `force` or `generate`, "
|
| 971 |
+
f"got {early_stopping_method}"
|
| 972 |
+
)
|
| 973 |
+
raise ValueError(msg)
|
| 974 |
+
|
| 975 |
+
def tool_run_logging_kwargs(self) -> builtins.dict:
|
| 976 |
+
"""Return logging kwargs for tool run."""
|
| 977 |
+
return {
|
| 978 |
+
"llm_prefix": self.llm_prefix,
|
| 979 |
+
"observation_prefix": self.observation_prefix,
|
| 980 |
+
}
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
class ExceptionTool(BaseTool):
|
| 984 |
+
"""Tool that just returns the query."""
|
| 985 |
+
|
| 986 |
+
name: str = "_Exception"
|
| 987 |
+
"""Name of the tool."""
|
| 988 |
+
description: str = "Exception tool"
|
| 989 |
+
"""Description of the tool."""
|
| 990 |
+
|
| 991 |
+
@override
|
| 992 |
+
def _run(
|
| 993 |
+
self,
|
| 994 |
+
query: str,
|
| 995 |
+
run_manager: CallbackManagerForToolRun | None = None,
|
| 996 |
+
) -> str:
|
| 997 |
+
return query
|
| 998 |
+
|
| 999 |
+
@override
|
| 1000 |
+
async def _arun(
|
| 1001 |
+
self,
|
| 1002 |
+
query: str,
|
| 1003 |
+
run_manager: AsyncCallbackManagerForToolRun | None = None,
|
| 1004 |
+
) -> str:
|
| 1005 |
+
return query
|
| 1006 |
+
|
| 1007 |
+
|
| 1008 |
+
NextStepOutput = list[AgentFinish | AgentAction | AgentStep]
|
| 1009 |
+
RunnableAgentType = RunnableAgent | RunnableMultiActionAgent
|
| 1010 |
+
|
| 1011 |
+
|
| 1012 |
+
class AgentExecutor(Chain):
|
| 1013 |
+
"""Agent that is using tools."""
|
| 1014 |
+
|
| 1015 |
+
agent: BaseSingleActionAgent | BaseMultiActionAgent | Runnable
|
| 1016 |
+
"""The agent to run for creating a plan and determining actions
|
| 1017 |
+
to take at each step of the execution loop."""
|
| 1018 |
+
tools: Sequence[BaseTool]
|
| 1019 |
+
"""The valid tools the agent can call."""
|
| 1020 |
+
return_intermediate_steps: bool = False
|
| 1021 |
+
"""Whether to return the agent's trajectory of intermediate steps
|
| 1022 |
+
at the end in addition to the final output."""
|
| 1023 |
+
max_iterations: int | None = 15
|
| 1024 |
+
"""The maximum number of steps to take before ending the execution
|
| 1025 |
+
loop.
|
| 1026 |
+
|
| 1027 |
+
Setting to 'None' could lead to an infinite loop."""
|
| 1028 |
+
max_execution_time: float | None = None
|
| 1029 |
+
"""The maximum amount of wall clock time to spend in the execution
|
| 1030 |
+
loop.
|
| 1031 |
+
"""
|
| 1032 |
+
early_stopping_method: str = "force"
|
| 1033 |
+
"""The method to use for early stopping if the agent never
|
| 1034 |
+
returns `AgentFinish`. Either 'force' or 'generate'.
|
| 1035 |
+
|
| 1036 |
+
`"force"` returns a string saying that it stopped because it met a
|
| 1037 |
+
time or iteration limit.
|
| 1038 |
+
|
| 1039 |
+
`"generate"` calls the agent's LLM Chain one final time to generate
|
| 1040 |
+
a final answer based on the previous steps.
|
| 1041 |
+
"""
|
| 1042 |
+
handle_parsing_errors: bool | str | Callable[[OutputParserException], str] = False
|
| 1043 |
+
"""How to handle errors raised by the agent's output parser.
|
| 1044 |
+
Defaults to `False`, which raises the error.
|
| 1045 |
+
If `true`, the error will be sent back to the LLM as an observation.
|
| 1046 |
+
If a string, the string itself will be sent to the LLM as an observation.
|
| 1047 |
+
If a callable function, the function will be called with the exception as an
|
| 1048 |
+
argument, and the result of that function will be passed to the agent as an
|
| 1049 |
+
observation.
|
| 1050 |
+
"""
|
| 1051 |
+
trim_intermediate_steps: (
|
| 1052 |
+
int | Callable[[list[tuple[AgentAction, str]]], list[tuple[AgentAction, str]]]
|
| 1053 |
+
) = -1
|
| 1054 |
+
"""How to trim the intermediate steps before returning them.
|
| 1055 |
+
Defaults to -1, which means no trimming.
|
| 1056 |
+
"""
|
| 1057 |
+
|
| 1058 |
+
@classmethod
|
| 1059 |
+
def from_agent_and_tools(
|
| 1060 |
+
cls,
|
| 1061 |
+
agent: BaseSingleActionAgent | BaseMultiActionAgent | Runnable,
|
| 1062 |
+
tools: Sequence[BaseTool],
|
| 1063 |
+
callbacks: Callbacks = None,
|
| 1064 |
+
**kwargs: Any,
|
| 1065 |
+
) -> AgentExecutor:
|
| 1066 |
+
"""Create from agent and tools.
|
| 1067 |
+
|
| 1068 |
+
Args:
|
| 1069 |
+
agent: Agent to use.
|
| 1070 |
+
tools: Tools to use.
|
| 1071 |
+
callbacks: Callbacks to use.
|
| 1072 |
+
kwargs: Additional arguments.
|
| 1073 |
+
|
| 1074 |
+
Returns:
|
| 1075 |
+
Agent executor object.
|
| 1076 |
+
"""
|
| 1077 |
+
return cls(
|
| 1078 |
+
agent=agent,
|
| 1079 |
+
tools=tools,
|
| 1080 |
+
callbacks=callbacks,
|
| 1081 |
+
**kwargs,
|
| 1082 |
+
)
|
| 1083 |
+
|
| 1084 |
+
@model_validator(mode="after")
|
| 1085 |
+
def validate_tools(self) -> Self:
|
| 1086 |
+
"""Validate that tools are compatible with agent.
|
| 1087 |
+
|
| 1088 |
+
Args:
|
| 1089 |
+
values: Values to validate.
|
| 1090 |
+
|
| 1091 |
+
Returns:
|
| 1092 |
+
Validated values.
|
| 1093 |
+
|
| 1094 |
+
Raises:
|
| 1095 |
+
ValueError: If allowed tools are different than provided tools.
|
| 1096 |
+
"""
|
| 1097 |
+
agent = self.agent
|
| 1098 |
+
tools = self.tools
|
| 1099 |
+
allowed_tools = agent.get_allowed_tools() # type: ignore[union-attr]
|
| 1100 |
+
if allowed_tools is not None and set(allowed_tools) != {
|
| 1101 |
+
tool.name for tool in tools
|
| 1102 |
+
}:
|
| 1103 |
+
msg = (
|
| 1104 |
+
f"Allowed tools ({allowed_tools}) different than "
|
| 1105 |
+
f"provided tools ({[tool.name for tool in tools]})"
|
| 1106 |
+
)
|
| 1107 |
+
raise ValueError(msg)
|
| 1108 |
+
return self
|
| 1109 |
+
|
| 1110 |
+
@model_validator(mode="before")
|
| 1111 |
+
@classmethod
|
| 1112 |
+
def validate_runnable_agent(cls, values: dict) -> Any:
|
| 1113 |
+
"""Convert runnable to agent if passed in.
|
| 1114 |
+
|
| 1115 |
+
Args:
|
| 1116 |
+
values: Values to validate.
|
| 1117 |
+
|
| 1118 |
+
Returns:
|
| 1119 |
+
Validated values.
|
| 1120 |
+
"""
|
| 1121 |
+
agent = values.get("agent")
|
| 1122 |
+
if agent and isinstance(agent, Runnable):
|
| 1123 |
+
try:
|
| 1124 |
+
output_type = agent.OutputType
|
| 1125 |
+
except TypeError:
|
| 1126 |
+
multi_action = False
|
| 1127 |
+
except Exception:
|
| 1128 |
+
logger.exception("Unexpected error getting OutputType from agent")
|
| 1129 |
+
multi_action = False
|
| 1130 |
+
else:
|
| 1131 |
+
multi_action = output_type == list[AgentAction] | AgentFinish
|
| 1132 |
+
|
| 1133 |
+
stream_runnable = values.pop("stream_runnable", True)
|
| 1134 |
+
if multi_action:
|
| 1135 |
+
values["agent"] = RunnableMultiActionAgent(
|
| 1136 |
+
runnable=agent,
|
| 1137 |
+
stream_runnable=stream_runnable,
|
| 1138 |
+
)
|
| 1139 |
+
else:
|
| 1140 |
+
values["agent"] = RunnableAgent(
|
| 1141 |
+
runnable=agent,
|
| 1142 |
+
stream_runnable=stream_runnable,
|
| 1143 |
+
)
|
| 1144 |
+
return values
|
| 1145 |
+
|
| 1146 |
+
@property
|
| 1147 |
+
def _action_agent(self) -> BaseSingleActionAgent | BaseMultiActionAgent:
|
| 1148 |
+
"""Type cast self.agent.
|
| 1149 |
+
|
| 1150 |
+
If the `agent` attribute is a Runnable, it will be converted one of
|
| 1151 |
+
RunnableAgentType in the validate_runnable_agent root_validator.
|
| 1152 |
+
|
| 1153 |
+
To support instantiating with a Runnable, here we explicitly cast the type
|
| 1154 |
+
to reflect the changes made in the root_validator.
|
| 1155 |
+
"""
|
| 1156 |
+
if isinstance(self.agent, Runnable):
|
| 1157 |
+
return cast("RunnableAgentType", self.agent)
|
| 1158 |
+
return self.agent
|
| 1159 |
+
|
| 1160 |
+
@override
|
| 1161 |
+
def save(self, file_path: Path | str) -> None:
|
| 1162 |
+
"""Raise error - saving not supported for Agent Executors.
|
| 1163 |
+
|
| 1164 |
+
Args:
|
| 1165 |
+
file_path: Path to save to.
|
| 1166 |
+
|
| 1167 |
+
Raises:
|
| 1168 |
+
ValueError: Saving not supported for agent executors.
|
| 1169 |
+
"""
|
| 1170 |
+
msg = (
|
| 1171 |
+
"Saving not supported for agent executors. "
|
| 1172 |
+
"If you are trying to save the agent, please use the "
|
| 1173 |
+
"`.save_agent(...)`"
|
| 1174 |
+
)
|
| 1175 |
+
raise ValueError(msg)
|
| 1176 |
+
|
| 1177 |
+
def save_agent(self, file_path: Path | str) -> None:
|
| 1178 |
+
"""Save the underlying agent.
|
| 1179 |
+
|
| 1180 |
+
Args:
|
| 1181 |
+
file_path: Path to save to.
|
| 1182 |
+
"""
|
| 1183 |
+
return self._action_agent.save(file_path)
|
| 1184 |
+
|
| 1185 |
+
def iter(
|
| 1186 |
+
self,
|
| 1187 |
+
inputs: Any,
|
| 1188 |
+
callbacks: Callbacks = None,
|
| 1189 |
+
*,
|
| 1190 |
+
include_run_info: bool = False,
|
| 1191 |
+
async_: bool = False, # noqa: ARG002 arg kept for backwards compat, but ignored
|
| 1192 |
+
) -> AgentExecutorIterator:
|
| 1193 |
+
"""Enables iteration over steps taken to reach final output.
|
| 1194 |
+
|
| 1195 |
+
Args:
|
| 1196 |
+
inputs: Inputs to the agent.
|
| 1197 |
+
callbacks: Callbacks to run.
|
| 1198 |
+
include_run_info: Whether to include run info.
|
| 1199 |
+
async_: Whether to run async. (Ignored)
|
| 1200 |
+
|
| 1201 |
+
Returns:
|
| 1202 |
+
Agent executor iterator object.
|
| 1203 |
+
"""
|
| 1204 |
+
return AgentExecutorIterator(
|
| 1205 |
+
self,
|
| 1206 |
+
inputs,
|
| 1207 |
+
callbacks,
|
| 1208 |
+
tags=self.tags,
|
| 1209 |
+
include_run_info=include_run_info,
|
| 1210 |
+
)
|
| 1211 |
+
|
| 1212 |
+
@property
|
| 1213 |
+
def input_keys(self) -> list[str]:
|
| 1214 |
+
"""Return the input keys."""
|
| 1215 |
+
return self._action_agent.input_keys
|
| 1216 |
+
|
| 1217 |
+
@property
|
| 1218 |
+
def output_keys(self) -> list[str]:
|
| 1219 |
+
"""Return the singular output key."""
|
| 1220 |
+
if self.return_intermediate_steps:
|
| 1221 |
+
return [*self._action_agent.return_values, "intermediate_steps"]
|
| 1222 |
+
return self._action_agent.return_values
|
| 1223 |
+
|
| 1224 |
+
def lookup_tool(self, name: str) -> BaseTool:
|
| 1225 |
+
"""Lookup tool by name.
|
| 1226 |
+
|
| 1227 |
+
Args:
|
| 1228 |
+
name: Name of tool.
|
| 1229 |
+
|
| 1230 |
+
Returns:
|
| 1231 |
+
Tool object.
|
| 1232 |
+
"""
|
| 1233 |
+
return {tool.name: tool for tool in self.tools}[name]
|
| 1234 |
+
|
| 1235 |
+
def _should_continue(self, iterations: int, time_elapsed: float) -> bool:
|
| 1236 |
+
if self.max_iterations is not None and iterations >= self.max_iterations:
|
| 1237 |
+
return False
|
| 1238 |
+
return self.max_execution_time is None or time_elapsed < self.max_execution_time
|
| 1239 |
+
|
| 1240 |
+
def _return(
|
| 1241 |
+
self,
|
| 1242 |
+
output: AgentFinish,
|
| 1243 |
+
intermediate_steps: list,
|
| 1244 |
+
run_manager: CallbackManagerForChainRun | None = None,
|
| 1245 |
+
) -> dict[str, Any]:
|
| 1246 |
+
if run_manager:
|
| 1247 |
+
run_manager.on_agent_finish(output, color="green", verbose=self.verbose)
|
| 1248 |
+
final_output = output.return_values
|
| 1249 |
+
if self.return_intermediate_steps:
|
| 1250 |
+
final_output["intermediate_steps"] = intermediate_steps
|
| 1251 |
+
return final_output
|
| 1252 |
+
|
| 1253 |
+
async def _areturn(
|
| 1254 |
+
self,
|
| 1255 |
+
output: AgentFinish,
|
| 1256 |
+
intermediate_steps: list,
|
| 1257 |
+
run_manager: AsyncCallbackManagerForChainRun | None = None,
|
| 1258 |
+
) -> dict[str, Any]:
|
| 1259 |
+
if run_manager:
|
| 1260 |
+
await run_manager.on_agent_finish(
|
| 1261 |
+
output,
|
| 1262 |
+
color="green",
|
| 1263 |
+
verbose=self.verbose,
|
| 1264 |
+
)
|
| 1265 |
+
final_output = output.return_values
|
| 1266 |
+
if self.return_intermediate_steps:
|
| 1267 |
+
final_output["intermediate_steps"] = intermediate_steps
|
| 1268 |
+
return final_output
|
| 1269 |
+
|
| 1270 |
+
def _consume_next_step(
|
| 1271 |
+
self,
|
| 1272 |
+
values: NextStepOutput,
|
| 1273 |
+
) -> AgentFinish | list[tuple[AgentAction, str]]:
|
| 1274 |
+
if isinstance(values[-1], AgentFinish):
|
| 1275 |
+
if len(values) != 1:
|
| 1276 |
+
msg = "Expected a single AgentFinish output, but got multiple values."
|
| 1277 |
+
raise ValueError(msg)
|
| 1278 |
+
return values[-1]
|
| 1279 |
+
return [(a.action, a.observation) for a in values if isinstance(a, AgentStep)]
|
| 1280 |
+
|
| 1281 |
+
def _take_next_step(
|
| 1282 |
+
self,
|
| 1283 |
+
name_to_tool_map: dict[str, BaseTool],
|
| 1284 |
+
color_mapping: dict[str, str],
|
| 1285 |
+
inputs: dict[str, str],
|
| 1286 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 1287 |
+
run_manager: CallbackManagerForChainRun | None = None,
|
| 1288 |
+
) -> AgentFinish | list[tuple[AgentAction, str]]:
|
| 1289 |
+
return self._consume_next_step(
|
| 1290 |
+
list(
|
| 1291 |
+
self._iter_next_step(
|
| 1292 |
+
name_to_tool_map,
|
| 1293 |
+
color_mapping,
|
| 1294 |
+
inputs,
|
| 1295 |
+
intermediate_steps,
|
| 1296 |
+
run_manager,
|
| 1297 |
+
),
|
| 1298 |
+
),
|
| 1299 |
+
)
|
| 1300 |
+
|
| 1301 |
+
def _iter_next_step(
|
| 1302 |
+
self,
|
| 1303 |
+
name_to_tool_map: dict[str, BaseTool],
|
| 1304 |
+
color_mapping: dict[str, str],
|
| 1305 |
+
inputs: dict[str, str],
|
| 1306 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 1307 |
+
run_manager: CallbackManagerForChainRun | None = None,
|
| 1308 |
+
) -> Iterator[AgentFinish | AgentAction | AgentStep]:
|
| 1309 |
+
"""Take a single step in the thought-action-observation loop.
|
| 1310 |
+
|
| 1311 |
+
Override this to take control of how the agent makes and acts on choices.
|
| 1312 |
+
"""
|
| 1313 |
+
try:
|
| 1314 |
+
intermediate_steps = self._prepare_intermediate_steps(intermediate_steps)
|
| 1315 |
+
|
| 1316 |
+
# Call the LLM to see what to do.
|
| 1317 |
+
output = self._action_agent.plan(
|
| 1318 |
+
intermediate_steps,
|
| 1319 |
+
callbacks=run_manager.get_child() if run_manager else None,
|
| 1320 |
+
**inputs,
|
| 1321 |
+
)
|
| 1322 |
+
except OutputParserException as e:
|
| 1323 |
+
if isinstance(self.handle_parsing_errors, bool):
|
| 1324 |
+
raise_error = not self.handle_parsing_errors
|
| 1325 |
+
else:
|
| 1326 |
+
raise_error = False
|
| 1327 |
+
if raise_error:
|
| 1328 |
+
msg = (
|
| 1329 |
+
"An output parsing error occurred. "
|
| 1330 |
+
"In order to pass this error back to the agent and have it try "
|
| 1331 |
+
"again, pass `handle_parsing_errors=True` to the AgentExecutor. "
|
| 1332 |
+
f"This is the error: {e!s}"
|
| 1333 |
+
)
|
| 1334 |
+
raise ValueError(msg) from e
|
| 1335 |
+
text = str(e)
|
| 1336 |
+
if isinstance(self.handle_parsing_errors, bool):
|
| 1337 |
+
if e.send_to_llm:
|
| 1338 |
+
observation = str(e.observation)
|
| 1339 |
+
text = str(e.llm_output)
|
| 1340 |
+
else:
|
| 1341 |
+
observation = "Invalid or incomplete response"
|
| 1342 |
+
elif isinstance(self.handle_parsing_errors, str):
|
| 1343 |
+
observation = self.handle_parsing_errors
|
| 1344 |
+
elif callable(self.handle_parsing_errors):
|
| 1345 |
+
observation = self.handle_parsing_errors(e)
|
| 1346 |
+
else:
|
| 1347 |
+
msg = "Got unexpected type of `handle_parsing_errors`" # type: ignore[unreachable]
|
| 1348 |
+
raise ValueError(msg) from e # noqa: TRY004
|
| 1349 |
+
output = AgentAction("_Exception", observation, text)
|
| 1350 |
+
if run_manager:
|
| 1351 |
+
run_manager.on_agent_action(output, color="green")
|
| 1352 |
+
tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()
|
| 1353 |
+
observation = ExceptionTool().run(
|
| 1354 |
+
output.tool_input,
|
| 1355 |
+
verbose=self.verbose,
|
| 1356 |
+
color=None,
|
| 1357 |
+
callbacks=run_manager.get_child() if run_manager else None,
|
| 1358 |
+
**tool_run_kwargs,
|
| 1359 |
+
)
|
| 1360 |
+
yield AgentStep(action=output, observation=observation)
|
| 1361 |
+
return
|
| 1362 |
+
|
| 1363 |
+
# If the tool chosen is the finishing tool, then we end and return.
|
| 1364 |
+
if isinstance(output, AgentFinish):
|
| 1365 |
+
yield output
|
| 1366 |
+
return
|
| 1367 |
+
|
| 1368 |
+
actions: list[AgentAction]
|
| 1369 |
+
actions = [output] if isinstance(output, AgentAction) else output
|
| 1370 |
+
for agent_action in actions:
|
| 1371 |
+
yield agent_action
|
| 1372 |
+
for agent_action in actions:
|
| 1373 |
+
yield self._perform_agent_action(
|
| 1374 |
+
name_to_tool_map,
|
| 1375 |
+
color_mapping,
|
| 1376 |
+
agent_action,
|
| 1377 |
+
run_manager,
|
| 1378 |
+
)
|
| 1379 |
+
|
| 1380 |
+
def _perform_agent_action(
|
| 1381 |
+
self,
|
| 1382 |
+
name_to_tool_map: dict[str, BaseTool],
|
| 1383 |
+
color_mapping: dict[str, str],
|
| 1384 |
+
agent_action: AgentAction,
|
| 1385 |
+
run_manager: CallbackManagerForChainRun | None = None,
|
| 1386 |
+
) -> AgentStep:
|
| 1387 |
+
if run_manager:
|
| 1388 |
+
run_manager.on_agent_action(agent_action, color="green")
|
| 1389 |
+
# Otherwise we lookup the tool
|
| 1390 |
+
if agent_action.tool in name_to_tool_map:
|
| 1391 |
+
tool = name_to_tool_map[agent_action.tool]
|
| 1392 |
+
return_direct = tool.return_direct
|
| 1393 |
+
color = color_mapping[agent_action.tool]
|
| 1394 |
+
tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()
|
| 1395 |
+
if return_direct:
|
| 1396 |
+
tool_run_kwargs["llm_prefix"] = ""
|
| 1397 |
+
# We then call the tool on the tool input to get an observation
|
| 1398 |
+
observation = tool.run(
|
| 1399 |
+
agent_action.tool_input,
|
| 1400 |
+
verbose=self.verbose,
|
| 1401 |
+
color=color,
|
| 1402 |
+
callbacks=run_manager.get_child() if run_manager else None,
|
| 1403 |
+
**tool_run_kwargs,
|
| 1404 |
+
)
|
| 1405 |
+
else:
|
| 1406 |
+
tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()
|
| 1407 |
+
observation = InvalidTool().run(
|
| 1408 |
+
{
|
| 1409 |
+
"requested_tool_name": agent_action.tool,
|
| 1410 |
+
"available_tool_names": list(name_to_tool_map.keys()),
|
| 1411 |
+
},
|
| 1412 |
+
verbose=self.verbose,
|
| 1413 |
+
color=None,
|
| 1414 |
+
callbacks=run_manager.get_child() if run_manager else None,
|
| 1415 |
+
**tool_run_kwargs,
|
| 1416 |
+
)
|
| 1417 |
+
return AgentStep(action=agent_action, observation=observation)
|
| 1418 |
+
|
| 1419 |
+
async def _atake_next_step(
|
| 1420 |
+
self,
|
| 1421 |
+
name_to_tool_map: dict[str, BaseTool],
|
| 1422 |
+
color_mapping: dict[str, str],
|
| 1423 |
+
inputs: dict[str, str],
|
| 1424 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 1425 |
+
run_manager: AsyncCallbackManagerForChainRun | None = None,
|
| 1426 |
+
) -> AgentFinish | list[tuple[AgentAction, str]]:
|
| 1427 |
+
return self._consume_next_step(
|
| 1428 |
+
[
|
| 1429 |
+
a
|
| 1430 |
+
async for a in self._aiter_next_step(
|
| 1431 |
+
name_to_tool_map,
|
| 1432 |
+
color_mapping,
|
| 1433 |
+
inputs,
|
| 1434 |
+
intermediate_steps,
|
| 1435 |
+
run_manager,
|
| 1436 |
+
)
|
| 1437 |
+
],
|
| 1438 |
+
)
|
| 1439 |
+
|
| 1440 |
+
async def _aiter_next_step(
|
| 1441 |
+
self,
|
| 1442 |
+
name_to_tool_map: dict[str, BaseTool],
|
| 1443 |
+
color_mapping: dict[str, str],
|
| 1444 |
+
inputs: dict[str, str],
|
| 1445 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 1446 |
+
run_manager: AsyncCallbackManagerForChainRun | None = None,
|
| 1447 |
+
) -> AsyncIterator[AgentFinish | AgentAction | AgentStep]:
|
| 1448 |
+
"""Take a single step in the thought-action-observation loop.
|
| 1449 |
+
|
| 1450 |
+
Override this to take control of how the agent makes and acts on choices.
|
| 1451 |
+
"""
|
| 1452 |
+
try:
|
| 1453 |
+
intermediate_steps = self._prepare_intermediate_steps(intermediate_steps)
|
| 1454 |
+
|
| 1455 |
+
# Call the LLM to see what to do.
|
| 1456 |
+
output = await self._action_agent.aplan(
|
| 1457 |
+
intermediate_steps,
|
| 1458 |
+
callbacks=run_manager.get_child() if run_manager else None,
|
| 1459 |
+
**inputs,
|
| 1460 |
+
)
|
| 1461 |
+
except OutputParserException as e:
|
| 1462 |
+
if isinstance(self.handle_parsing_errors, bool):
|
| 1463 |
+
raise_error = not self.handle_parsing_errors
|
| 1464 |
+
else:
|
| 1465 |
+
raise_error = False
|
| 1466 |
+
if raise_error:
|
| 1467 |
+
msg = (
|
| 1468 |
+
"An output parsing error occurred. "
|
| 1469 |
+
"In order to pass this error back to the agent and have it try "
|
| 1470 |
+
"again, pass `handle_parsing_errors=True` to the AgentExecutor. "
|
| 1471 |
+
f"This is the error: {e!s}"
|
| 1472 |
+
)
|
| 1473 |
+
raise ValueError(msg) from e
|
| 1474 |
+
text = str(e)
|
| 1475 |
+
if isinstance(self.handle_parsing_errors, bool):
|
| 1476 |
+
if e.send_to_llm:
|
| 1477 |
+
observation = str(e.observation)
|
| 1478 |
+
text = str(e.llm_output)
|
| 1479 |
+
else:
|
| 1480 |
+
observation = "Invalid or incomplete response"
|
| 1481 |
+
elif isinstance(self.handle_parsing_errors, str):
|
| 1482 |
+
observation = self.handle_parsing_errors
|
| 1483 |
+
elif callable(self.handle_parsing_errors):
|
| 1484 |
+
observation = self.handle_parsing_errors(e)
|
| 1485 |
+
else:
|
| 1486 |
+
msg = "Got unexpected type of `handle_parsing_errors`" # type: ignore[unreachable]
|
| 1487 |
+
raise ValueError(msg) from e # noqa: TRY004
|
| 1488 |
+
output = AgentAction("_Exception", observation, text)
|
| 1489 |
+
tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()
|
| 1490 |
+
observation = await ExceptionTool().arun(
|
| 1491 |
+
output.tool_input,
|
| 1492 |
+
verbose=self.verbose,
|
| 1493 |
+
color=None,
|
| 1494 |
+
callbacks=run_manager.get_child() if run_manager else None,
|
| 1495 |
+
**tool_run_kwargs,
|
| 1496 |
+
)
|
| 1497 |
+
yield AgentStep(action=output, observation=observation)
|
| 1498 |
+
return
|
| 1499 |
+
|
| 1500 |
+
# If the tool chosen is the finishing tool, then we end and return.
|
| 1501 |
+
if isinstance(output, AgentFinish):
|
| 1502 |
+
yield output
|
| 1503 |
+
return
|
| 1504 |
+
|
| 1505 |
+
actions: list[AgentAction]
|
| 1506 |
+
actions = [output] if isinstance(output, AgentAction) else output
|
| 1507 |
+
for agent_action in actions:
|
| 1508 |
+
yield agent_action
|
| 1509 |
+
|
| 1510 |
+
# Use asyncio.gather to run multiple tool.arun() calls concurrently
|
| 1511 |
+
result = await asyncio.gather(
|
| 1512 |
+
*[
|
| 1513 |
+
self._aperform_agent_action(
|
| 1514 |
+
name_to_tool_map,
|
| 1515 |
+
color_mapping,
|
| 1516 |
+
agent_action,
|
| 1517 |
+
run_manager,
|
| 1518 |
+
)
|
| 1519 |
+
for agent_action in actions
|
| 1520 |
+
],
|
| 1521 |
+
)
|
| 1522 |
+
|
| 1523 |
+
# TODO: This could yield each result as it becomes available
|
| 1524 |
+
for chunk in result:
|
| 1525 |
+
yield chunk
|
| 1526 |
+
|
| 1527 |
+
async def _aperform_agent_action(
|
| 1528 |
+
self,
|
| 1529 |
+
name_to_tool_map: dict[str, BaseTool],
|
| 1530 |
+
color_mapping: dict[str, str],
|
| 1531 |
+
agent_action: AgentAction,
|
| 1532 |
+
run_manager: AsyncCallbackManagerForChainRun | None = None,
|
| 1533 |
+
) -> AgentStep:
|
| 1534 |
+
if run_manager:
|
| 1535 |
+
await run_manager.on_agent_action(
|
| 1536 |
+
agent_action,
|
| 1537 |
+
verbose=self.verbose,
|
| 1538 |
+
color="green",
|
| 1539 |
+
)
|
| 1540 |
+
# Otherwise we lookup the tool
|
| 1541 |
+
if agent_action.tool in name_to_tool_map:
|
| 1542 |
+
tool = name_to_tool_map[agent_action.tool]
|
| 1543 |
+
return_direct = tool.return_direct
|
| 1544 |
+
color = color_mapping[agent_action.tool]
|
| 1545 |
+
tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()
|
| 1546 |
+
if return_direct:
|
| 1547 |
+
tool_run_kwargs["llm_prefix"] = ""
|
| 1548 |
+
# We then call the tool on the tool input to get an observation
|
| 1549 |
+
observation = await tool.arun(
|
| 1550 |
+
agent_action.tool_input,
|
| 1551 |
+
verbose=self.verbose,
|
| 1552 |
+
color=color,
|
| 1553 |
+
callbacks=run_manager.get_child() if run_manager else None,
|
| 1554 |
+
**tool_run_kwargs,
|
| 1555 |
+
)
|
| 1556 |
+
else:
|
| 1557 |
+
tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()
|
| 1558 |
+
observation = await InvalidTool().arun(
|
| 1559 |
+
{
|
| 1560 |
+
"requested_tool_name": agent_action.tool,
|
| 1561 |
+
"available_tool_names": list(name_to_tool_map.keys()),
|
| 1562 |
+
},
|
| 1563 |
+
verbose=self.verbose,
|
| 1564 |
+
color=None,
|
| 1565 |
+
callbacks=run_manager.get_child() if run_manager else None,
|
| 1566 |
+
**tool_run_kwargs,
|
| 1567 |
+
)
|
| 1568 |
+
return AgentStep(action=agent_action, observation=observation)
|
| 1569 |
+
|
| 1570 |
+
def _call(
|
| 1571 |
+
self,
|
| 1572 |
+
inputs: dict[str, str],
|
| 1573 |
+
run_manager: CallbackManagerForChainRun | None = None,
|
| 1574 |
+
) -> dict[str, Any]:
|
| 1575 |
+
"""Run text through and get agent response."""
|
| 1576 |
+
# Construct a mapping of tool name to tool for easy lookup
|
| 1577 |
+
name_to_tool_map = {tool.name: tool for tool in self.tools}
|
| 1578 |
+
# We construct a mapping from each tool to a color, used for logging.
|
| 1579 |
+
color_mapping = get_color_mapping(
|
| 1580 |
+
[tool.name for tool in self.tools],
|
| 1581 |
+
excluded_colors=["green", "red"],
|
| 1582 |
+
)
|
| 1583 |
+
intermediate_steps: list[tuple[AgentAction, str]] = []
|
| 1584 |
+
# Let's start tracking the number of iterations and time elapsed
|
| 1585 |
+
iterations = 0
|
| 1586 |
+
time_elapsed = 0.0
|
| 1587 |
+
start_time = time.time()
|
| 1588 |
+
# We now enter the agent loop (until it returns something).
|
| 1589 |
+
while self._should_continue(iterations, time_elapsed):
|
| 1590 |
+
next_step_output = self._take_next_step(
|
| 1591 |
+
name_to_tool_map,
|
| 1592 |
+
color_mapping,
|
| 1593 |
+
inputs,
|
| 1594 |
+
intermediate_steps,
|
| 1595 |
+
run_manager=run_manager,
|
| 1596 |
+
)
|
| 1597 |
+
if isinstance(next_step_output, AgentFinish):
|
| 1598 |
+
return self._return(
|
| 1599 |
+
next_step_output,
|
| 1600 |
+
intermediate_steps,
|
| 1601 |
+
run_manager=run_manager,
|
| 1602 |
+
)
|
| 1603 |
+
|
| 1604 |
+
intermediate_steps.extend(next_step_output)
|
| 1605 |
+
if len(next_step_output) == 1:
|
| 1606 |
+
next_step_action = next_step_output[0]
|
| 1607 |
+
# See if tool should return directly
|
| 1608 |
+
tool_return = self._get_tool_return(next_step_action)
|
| 1609 |
+
if tool_return is not None:
|
| 1610 |
+
return self._return(
|
| 1611 |
+
tool_return,
|
| 1612 |
+
intermediate_steps,
|
| 1613 |
+
run_manager=run_manager,
|
| 1614 |
+
)
|
| 1615 |
+
iterations += 1
|
| 1616 |
+
time_elapsed = time.time() - start_time
|
| 1617 |
+
output = self._action_agent.return_stopped_response(
|
| 1618 |
+
self.early_stopping_method,
|
| 1619 |
+
intermediate_steps,
|
| 1620 |
+
**inputs,
|
| 1621 |
+
)
|
| 1622 |
+
return self._return(output, intermediate_steps, run_manager=run_manager)
|
| 1623 |
+
|
| 1624 |
+
async def _acall(
|
| 1625 |
+
self,
|
| 1626 |
+
inputs: dict[str, str],
|
| 1627 |
+
run_manager: AsyncCallbackManagerForChainRun | None = None,
|
| 1628 |
+
) -> dict[str, str]:
|
| 1629 |
+
"""Async run text through and get agent response."""
|
| 1630 |
+
# Construct a mapping of tool name to tool for easy lookup
|
| 1631 |
+
name_to_tool_map = {tool.name: tool for tool in self.tools}
|
| 1632 |
+
# We construct a mapping from each tool to a color, used for logging.
|
| 1633 |
+
color_mapping = get_color_mapping(
|
| 1634 |
+
[tool.name for tool in self.tools],
|
| 1635 |
+
excluded_colors=["green"],
|
| 1636 |
+
)
|
| 1637 |
+
intermediate_steps: list[tuple[AgentAction, str]] = []
|
| 1638 |
+
# Let's start tracking the number of iterations and time elapsed
|
| 1639 |
+
iterations = 0
|
| 1640 |
+
time_elapsed = 0.0
|
| 1641 |
+
start_time = time.time()
|
| 1642 |
+
# We now enter the agent loop (until it returns something).
|
| 1643 |
+
try:
|
| 1644 |
+
async with asyncio_timeout(self.max_execution_time):
|
| 1645 |
+
while self._should_continue(iterations, time_elapsed):
|
| 1646 |
+
next_step_output = await self._atake_next_step(
|
| 1647 |
+
name_to_tool_map,
|
| 1648 |
+
color_mapping,
|
| 1649 |
+
inputs,
|
| 1650 |
+
intermediate_steps,
|
| 1651 |
+
run_manager=run_manager,
|
| 1652 |
+
)
|
| 1653 |
+
if isinstance(next_step_output, AgentFinish):
|
| 1654 |
+
return await self._areturn(
|
| 1655 |
+
next_step_output,
|
| 1656 |
+
intermediate_steps,
|
| 1657 |
+
run_manager=run_manager,
|
| 1658 |
+
)
|
| 1659 |
+
|
| 1660 |
+
intermediate_steps.extend(next_step_output)
|
| 1661 |
+
if len(next_step_output) == 1:
|
| 1662 |
+
next_step_action = next_step_output[0]
|
| 1663 |
+
# See if tool should return directly
|
| 1664 |
+
tool_return = self._get_tool_return(next_step_action)
|
| 1665 |
+
if tool_return is not None:
|
| 1666 |
+
return await self._areturn(
|
| 1667 |
+
tool_return,
|
| 1668 |
+
intermediate_steps,
|
| 1669 |
+
run_manager=run_manager,
|
| 1670 |
+
)
|
| 1671 |
+
|
| 1672 |
+
iterations += 1
|
| 1673 |
+
time_elapsed = time.time() - start_time
|
| 1674 |
+
output = self._action_agent.return_stopped_response(
|
| 1675 |
+
self.early_stopping_method,
|
| 1676 |
+
intermediate_steps,
|
| 1677 |
+
**inputs,
|
| 1678 |
+
)
|
| 1679 |
+
return await self._areturn(
|
| 1680 |
+
output,
|
| 1681 |
+
intermediate_steps,
|
| 1682 |
+
run_manager=run_manager,
|
| 1683 |
+
)
|
| 1684 |
+
except (TimeoutError, asyncio.TimeoutError):
|
| 1685 |
+
# stop early when interrupted by the async timeout
|
| 1686 |
+
output = self._action_agent.return_stopped_response(
|
| 1687 |
+
self.early_stopping_method,
|
| 1688 |
+
intermediate_steps,
|
| 1689 |
+
**inputs,
|
| 1690 |
+
)
|
| 1691 |
+
return await self._areturn(
|
| 1692 |
+
output,
|
| 1693 |
+
intermediate_steps,
|
| 1694 |
+
run_manager=run_manager,
|
| 1695 |
+
)
|
| 1696 |
+
|
| 1697 |
+
def _get_tool_return(
|
| 1698 |
+
self,
|
| 1699 |
+
next_step_output: tuple[AgentAction, str],
|
| 1700 |
+
) -> AgentFinish | None:
|
| 1701 |
+
"""Check if the tool is a returning tool."""
|
| 1702 |
+
agent_action, observation = next_step_output
|
| 1703 |
+
name_to_tool_map = {tool.name: tool for tool in self.tools}
|
| 1704 |
+
return_value_key = "output"
|
| 1705 |
+
if len(self._action_agent.return_values) > 0:
|
| 1706 |
+
return_value_key = self._action_agent.return_values[0]
|
| 1707 |
+
# Invalid tools won't be in the map, so we return False.
|
| 1708 |
+
if (
|
| 1709 |
+
agent_action.tool in name_to_tool_map
|
| 1710 |
+
and name_to_tool_map[agent_action.tool].return_direct
|
| 1711 |
+
):
|
| 1712 |
+
return AgentFinish(
|
| 1713 |
+
{return_value_key: observation},
|
| 1714 |
+
"",
|
| 1715 |
+
)
|
| 1716 |
+
return None
|
| 1717 |
+
|
| 1718 |
+
def _prepare_intermediate_steps(
|
| 1719 |
+
self,
|
| 1720 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 1721 |
+
) -> list[tuple[AgentAction, str]]:
|
| 1722 |
+
if (
|
| 1723 |
+
isinstance(self.trim_intermediate_steps, int)
|
| 1724 |
+
and self.trim_intermediate_steps > 0
|
| 1725 |
+
):
|
| 1726 |
+
return intermediate_steps[-self.trim_intermediate_steps :]
|
| 1727 |
+
if callable(self.trim_intermediate_steps):
|
| 1728 |
+
return self.trim_intermediate_steps(intermediate_steps)
|
| 1729 |
+
return intermediate_steps
|
| 1730 |
+
|
| 1731 |
+
@override
|
| 1732 |
+
def stream(
|
| 1733 |
+
self,
|
| 1734 |
+
input: dict[str, Any] | Any,
|
| 1735 |
+
config: RunnableConfig | None = None,
|
| 1736 |
+
**kwargs: Any,
|
| 1737 |
+
) -> Iterator[AddableDict]:
|
| 1738 |
+
"""Enables streaming over steps taken to reach final output.
|
| 1739 |
+
|
| 1740 |
+
Args:
|
| 1741 |
+
input: Input to the agent.
|
| 1742 |
+
config: Config to use.
|
| 1743 |
+
kwargs: Additional arguments.
|
| 1744 |
+
|
| 1745 |
+
Yields:
|
| 1746 |
+
Addable dictionary.
|
| 1747 |
+
"""
|
| 1748 |
+
config = ensure_config(config)
|
| 1749 |
+
iterator = AgentExecutorIterator(
|
| 1750 |
+
self,
|
| 1751 |
+
input,
|
| 1752 |
+
config.get("callbacks"),
|
| 1753 |
+
tags=config.get("tags"),
|
| 1754 |
+
metadata=config.get("metadata"),
|
| 1755 |
+
run_name=config.get("run_name"),
|
| 1756 |
+
run_id=config.get("run_id"),
|
| 1757 |
+
yield_actions=True,
|
| 1758 |
+
**kwargs,
|
| 1759 |
+
)
|
| 1760 |
+
yield from iterator
|
| 1761 |
+
|
| 1762 |
+
@override
|
| 1763 |
+
async def astream(
|
| 1764 |
+
self,
|
| 1765 |
+
input: dict[str, Any] | Any,
|
| 1766 |
+
config: RunnableConfig | None = None,
|
| 1767 |
+
**kwargs: Any,
|
| 1768 |
+
) -> AsyncIterator[AddableDict]:
|
| 1769 |
+
"""Async enables streaming over steps taken to reach final output.
|
| 1770 |
+
|
| 1771 |
+
Args:
|
| 1772 |
+
input: Input to the agent.
|
| 1773 |
+
config: Config to use.
|
| 1774 |
+
kwargs: Additional arguments.
|
| 1775 |
+
|
| 1776 |
+
Yields:
|
| 1777 |
+
Addable dictionary.
|
| 1778 |
+
"""
|
| 1779 |
+
config = ensure_config(config)
|
| 1780 |
+
iterator = AgentExecutorIterator(
|
| 1781 |
+
self,
|
| 1782 |
+
input,
|
| 1783 |
+
config.get("callbacks"),
|
| 1784 |
+
tags=config.get("tags"),
|
| 1785 |
+
metadata=config.get("metadata"),
|
| 1786 |
+
run_name=config.get("run_name"),
|
| 1787 |
+
run_id=config.get("run_id"),
|
| 1788 |
+
yield_actions=True,
|
| 1789 |
+
**kwargs,
|
| 1790 |
+
)
|
| 1791 |
+
async for step in iterator:
|
| 1792 |
+
yield step
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/agent_iterator.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ECKING,
|
| 9 |
+
Any,
|
| 10 |
+
)
|
| 11 |
+
from uuid import UUID
|
| 12 |
+
|
| 13 |
+
from langchain_core.agents import (
|
| 14 |
+
AgentAction,
|
| 15 |
+
AgentFinish,
|
| 16 |
+
AgentStep,
|
| 17 |
+
)
|
| 18 |
+
from langchain_core.callbacks import (
|
| 19 |
+
AsyncCallbackManager,
|
| 20 |
+
AsyncCallbackManagerForChainRun,
|
| 21 |
+
CallbackManager,
|
| 22 |
+
CallbackManagerForChainRun,
|
| 23 |
+
Callbacks,
|
| 24 |
+
)
|
| 25 |
+
from langchain_core.load.dump import dumpd
|
| 26 |
+
from langchain_core.outputs import RunInfo
|
| 27 |
+
from langchain_core.runnables.utils import AddableDict
|
| 28 |
+
from langchain_core.tools import BaseTool
|
| 29 |
+
from langchain_core.utils.input import get_color_mapping
|
| 30 |
+
|
| 31 |
+
from langchain_classic.schema import RUN_KEY
|
| 32 |
+
from langchain_classic.utilities.asyncio import asyncio_timeout
|
| 33 |
+
|
| 34 |
+
if TYPE_CHECKING:
|
| 35 |
+
from langchain_classic.agents.agent import AgentExecutor, NextStepOutput
|
| 36 |
+
|
| 37 |
+
logger = logging.getLogger(__name__)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class AgentExecutorIterator:
|
| 41 |
+
"""Iterator for AgentExecutor."""
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
agent_executor: AgentExecutor,
|
| 46 |
+
inputs: Any,
|
| 47 |
+
callbacks: Callbacks = None,
|
| 48 |
+
*,
|
| 49 |
+
tags: list[str] | None = None,
|
| 50 |
+
metadata: dict[str, Any] | None = None,
|
| 51 |
+
run_name: str | None = None,
|
| 52 |
+
run_id: UUID | None = None,
|
| 53 |
+
include_run_info: bool = False,
|
| 54 |
+
yield_actions: bool = False,
|
| 55 |
+
):
|
| 56 |
+
"""Initialize the `AgentExecutorIterator`.
|
| 57 |
+
|
| 58 |
+
Initialize the `AgentExecutorIterator` with the given `AgentExecutor`,
|
| 59 |
+
inputs, and optional callbacks.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
agent_executor: The `AgentExecutor` to iterate over.
|
| 63 |
+
inputs: The inputs to the `AgentExecutor`.
|
| 64 |
+
callbacks: The callbacks to use during iteration.
|
| 65 |
+
tags: The tags to use during iteration.
|
| 66 |
+
metadata: The metadata to use during iteration.
|
| 67 |
+
run_name: The name of the run.
|
| 68 |
+
run_id: The ID of the run.
|
| 69 |
+
include_run_info: Whether to include run info in the output.
|
| 70 |
+
yield_actions: Whether to yield actions as they are generated.
|
| 71 |
+
"""
|
| 72 |
+
self._agent_executor = agent_executor
|
| 73 |
+
self.inputs = inputs
|
| 74 |
+
self.callbacks = callbacks
|
| 75 |
+
self.tags = tags
|
| 76 |
+
self.metadata = metadata
|
| 77 |
+
self.run_name = run_name
|
| 78 |
+
self.run_id = run_id
|
| 79 |
+
self.include_run_info = include_run_info
|
| 80 |
+
self.yield_actions = yield_actions
|
| 81 |
+
self.reset()
|
| 82 |
+
|
| 83 |
+
_inputs: dict[str, str]
|
| 84 |
+
callbacks: Callbacks
|
| 85 |
+
tags: list[str] | None
|
| 86 |
+
metadata: dict[str, Any] | None
|
| 87 |
+
run_name: str | None
|
| 88 |
+
run_id: UUID | None
|
| 89 |
+
include_run_info: bool
|
| 90 |
+
yield_actions: bool
|
| 91 |
+
|
| 92 |
+
@property
|
| 93 |
+
def inputs(self) -> dict[str, str]:
|
| 94 |
+
"""The inputs to the `AgentExecutor`."""
|
| 95 |
+
return self._inputs
|
| 96 |
+
|
| 97 |
+
@inputs.setter
|
| 98 |
+
def inputs(self, inputs: Any) -> None:
|
| 99 |
+
self._inputs = self.agent_executor.prep_inputs(inputs)
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def agent_executor(self) -> AgentExecutor:
|
| 103 |
+
"""The `AgentExecutor` to iterate over."""
|
| 104 |
+
return self._agent_executor
|
| 105 |
+
|
| 106 |
+
@agent_executor.setter
|
| 107 |
+
def agent_executor(self, agent_executor: AgentExecutor) -> None:
|
| 108 |
+
self._agent_executor = agent_executor
|
| 109 |
+
# force re-prep inputs in case agent_executor's prep_inputs fn changed
|
| 110 |
+
self.inputs = self.inputs
|
| 111 |
+
|
| 112 |
+
@property
|
| 113 |
+
def name_to_tool_map(self) -> dict[str, BaseTool]:
|
| 114 |
+
"""A mapping of tool names to tools."""
|
| 115 |
+
return {tool.name: tool for tool in self.agent_executor.tools}
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def color_mapping(self) -> dict[str, str]:
|
| 119 |
+
"""A mapping of tool names to colors."""
|
| 120 |
+
return get_color_mapping(
|
| 121 |
+
[tool.name for tool in self.agent_executor.tools],
|
| 122 |
+
excluded_colors=["green", "red"],
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
def reset(self) -> None:
|
| 126 |
+
"""Reset the iterator to its initial state.
|
| 127 |
+
|
| 128 |
+
Reset the iterator to its initial state, clearing intermediate steps,
|
| 129 |
+
iterations, and time elapsed.
|
| 130 |
+
"""
|
| 131 |
+
logger.debug("(Re)setting AgentExecutorIterator to fresh state")
|
| 132 |
+
self.intermediate_steps: list[tuple[AgentAction, str]] = []
|
| 133 |
+
self.iterations = 0
|
| 134 |
+
# maybe better to start these on the first __anext__ call?
|
| 135 |
+
self.time_elapsed = 0.0
|
| 136 |
+
self.start_time = time.time()
|
| 137 |
+
|
| 138 |
+
def update_iterations(self) -> None:
|
| 139 |
+
"""Increment the number of iterations and update the time elapsed."""
|
| 140 |
+
self.iterations += 1
|
| 141 |
+
self.time_elapsed = time.time() - self.start_time
|
| 142 |
+
logger.debug(
|
| 143 |
+
"Agent Iterations: %s (%.2fs elapsed)",
|
| 144 |
+
self.iterations,
|
| 145 |
+
self.time_elapsed,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
def make_final_outputs(
|
| 149 |
+
self,
|
| 150 |
+
outputs: dict[str, Any],
|
| 151 |
+
run_manager: CallbackManagerForChainRun | AsyncCallbackManagerForChainRun,
|
| 152 |
+
) -> AddableDict:
|
| 153 |
+
"""Make final outputs for the iterator.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
outputs: The outputs from the agent executor.
|
| 157 |
+
run_manager: The run manager to use for callbacks.
|
| 158 |
+
"""
|
| 159 |
+
# have access to intermediate steps by design in iterator,
|
| 160 |
+
# so return only outputs may as well always be true.
|
| 161 |
+
|
| 162 |
+
prepared_outputs = AddableDict(
|
| 163 |
+
self.agent_executor.prep_outputs(
|
| 164 |
+
self.inputs,
|
| 165 |
+
outputs,
|
| 166 |
+
return_only_outputs=True,
|
| 167 |
+
),
|
| 168 |
+
)
|
| 169 |
+
if self.include_run_info:
|
| 170 |
+
prepared_outputs[RUN_KEY] = RunInfo(run_id=run_manager.run_id)
|
| 171 |
+
return prepared_outputs
|
| 172 |
+
|
| 173 |
+
def __iter__(self: AgentExecutorIterator) -> Iterator[AddableDict]:
|
| 174 |
+
"""Create an async iterator for the `AgentExecutor`."""
|
| 175 |
+
logger.debug("Initialising AgentExecutorIterator")
|
| 176 |
+
self.reset()
|
| 177 |
+
callback_manager = CallbackManager.configure(
|
| 178 |
+
self.callbacks,
|
| 179 |
+
self.agent_executor.callbacks,
|
| 180 |
+
self.agent_executor.verbose,
|
| 181 |
+
self.tags,
|
| 182 |
+
self.agent_executor.tags,
|
| 183 |
+
self.metadata,
|
| 184 |
+
self.agent_executor.metadata,
|
| 185 |
+
)
|
| 186 |
+
run_manager = callback_manager.on_chain_start(
|
| 187 |
+
dumpd(self.agent_executor),
|
| 188 |
+
self.inputs,
|
| 189 |
+
self.run_id,
|
| 190 |
+
name=self.run_name,
|
| 191 |
+
)
|
| 192 |
+
try:
|
| 193 |
+
while self.agent_executor._should_continue( # noqa: SLF001
|
| 194 |
+
self.iterations,
|
| 195 |
+
self.time_elapsed,
|
| 196 |
+
):
|
| 197 |
+
# take the next step: this plans next action, executes it,
|
| 198 |
+
# yielding action and observation as they are generated
|
| 199 |
+
next_step_seq: NextStepOutput = []
|
| 200 |
+
for chunk in self.agent_executor._iter_next_step( # noqa: SLF001
|
| 201 |
+
self.name_to_tool_map,
|
| 202 |
+
self.color_mapping,
|
| 203 |
+
self.inputs,
|
| 204 |
+
self.intermediate_steps,
|
| 205 |
+
run_manager,
|
| 206 |
+
):
|
| 207 |
+
next_step_seq.append(chunk)
|
| 208 |
+
# if we're yielding actions, yield them as they come
|
| 209 |
+
# do not yield AgentFinish, which will be handled below
|
| 210 |
+
if self.yield_actions:
|
| 211 |
+
if isinstance(chunk, AgentAction):
|
| 212 |
+
yield AddableDict(actions=[chunk], messages=chunk.messages)
|
| 213 |
+
elif isinstance(chunk, AgentStep):
|
| 214 |
+
yield AddableDict(steps=[chunk], messages=chunk.messages)
|
| 215 |
+
|
| 216 |
+
# convert iterator output to format handled by _process_next_step_output
|
| 217 |
+
next_step = self.agent_executor._consume_next_step(next_step_seq) # noqa: SLF001
|
| 218 |
+
# update iterations and time elapsed
|
| 219 |
+
self.update_iterations()
|
| 220 |
+
# decide if this is the final output
|
| 221 |
+
output = self._process_next_step_output(next_step, run_manager)
|
| 222 |
+
is_final = "intermediate_step" not in output
|
| 223 |
+
# yield the final output always
|
| 224 |
+
# for backwards compat, yield int. output if not yielding actions
|
| 225 |
+
if not self.yield_actions or is_final:
|
| 226 |
+
yield output
|
| 227 |
+
# if final output reached, stop iteration
|
| 228 |
+
if is_final:
|
| 229 |
+
return
|
| 230 |
+
except BaseException as e:
|
| 231 |
+
run_manager.on_chain_error(e)
|
| 232 |
+
raise
|
| 233 |
+
|
| 234 |
+
# if we got here means we exhausted iterations or time
|
| 235 |
+
yield self._stop(run_manager)
|
| 236 |
+
|
| 237 |
+
async def __aiter__(self) -> AsyncIterator[AddableDict]:
|
| 238 |
+
"""Create an async iterator for the `AgentExecutor`.
|
| 239 |
+
|
| 240 |
+
N.B. __aiter__ must be a normal method, so need to initialize async run manager
|
| 241 |
+
on first __anext__ call where we can await it.
|
| 242 |
+
"""
|
| 243 |
+
logger.debug("Initialising AgentExecutorIterator (async)")
|
| 244 |
+
self.reset()
|
| 245 |
+
callback_manager = AsyncCallbackManager.configure(
|
| 246 |
+
self.callbacks,
|
| 247 |
+
self.agent_executor.callbacks,
|
| 248 |
+
self.agent_executor.verbose,
|
| 249 |
+
self.tags,
|
| 250 |
+
self.agent_executor.tags,
|
| 251 |
+
self.metadata,
|
| 252 |
+
self.agent_executor.metadata,
|
| 253 |
+
)
|
| 254 |
+
run_manager = await callback_manager.on_chain_start(
|
| 255 |
+
dumpd(self.agent_executor),
|
| 256 |
+
self.inputs,
|
| 257 |
+
self.run_id,
|
| 258 |
+
name=self.run_name,
|
| 259 |
+
)
|
| 260 |
+
try:
|
| 261 |
+
async with asyncio_timeout(self.agent_executor.max_execution_time):
|
| 262 |
+
while self.agent_executor._should_continue( # noqa: SLF001
|
| 263 |
+
self.iterations,
|
| 264 |
+
self.time_elapsed,
|
| 265 |
+
):
|
| 266 |
+
# take the next step: this plans next action, executes it,
|
| 267 |
+
# yielding action and observation as they are generated
|
| 268 |
+
next_step_seq: NextStepOutput = []
|
| 269 |
+
async for chunk in self.agent_executor._aiter_next_step( # noqa: SLF001
|
| 270 |
+
self.name_to_tool_map,
|
| 271 |
+
self.color_mapping,
|
| 272 |
+
self.inputs,
|
| 273 |
+
self.intermediate_steps,
|
| 274 |
+
run_manager,
|
| 275 |
+
):
|
| 276 |
+
next_step_seq.append(chunk)
|
| 277 |
+
# if we're yielding actions, yield them as they come
|
| 278 |
+
# do not yield AgentFinish, which will be handled below
|
| 279 |
+
if self.yield_actions:
|
| 280 |
+
if isinstance(chunk, AgentAction):
|
| 281 |
+
yield AddableDict(
|
| 282 |
+
actions=[chunk],
|
| 283 |
+
messages=chunk.messages,
|
| 284 |
+
)
|
| 285 |
+
elif isinstance(chunk, AgentStep):
|
| 286 |
+
yield AddableDict(
|
| 287 |
+
steps=[chunk],
|
| 288 |
+
messages=chunk.messages,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
# convert iterator output to format handled by _process_next_step
|
| 292 |
+
next_step = self.agent_executor._consume_next_step(next_step_seq) # noqa: SLF001
|
| 293 |
+
# update iterations and time elapsed
|
| 294 |
+
self.update_iterations()
|
| 295 |
+
# decide if this is the final output
|
| 296 |
+
output = await self._aprocess_next_step_output(
|
| 297 |
+
next_step,
|
| 298 |
+
run_manager,
|
| 299 |
+
)
|
| 300 |
+
is_final = "intermediate_step" not in output
|
| 301 |
+
# yield the final output always
|
| 302 |
+
# for backwards compat, yield int. output if not yielding actions
|
| 303 |
+
if not self.yield_actions or is_final:
|
| 304 |
+
yield output
|
| 305 |
+
# if final output reached, stop iteration
|
| 306 |
+
if is_final:
|
| 307 |
+
return
|
| 308 |
+
except (TimeoutError, asyncio.TimeoutError):
|
| 309 |
+
yield await self._astop(run_manager)
|
| 310 |
+
return
|
| 311 |
+
except BaseException as e:
|
| 312 |
+
await run_manager.on_chain_error(e)
|
| 313 |
+
raise
|
| 314 |
+
|
| 315 |
+
# if we got here means we exhausted iterations or time
|
| 316 |
+
yield await self._astop(run_manager)
|
| 317 |
+
|
| 318 |
+
def _process_next_step_output(
|
| 319 |
+
self,
|
| 320 |
+
next_step_output: AgentFinish | list[tuple[AgentAction, str]],
|
| 321 |
+
run_manager: CallbackManagerForChainRun,
|
| 322 |
+
) -> AddableDict:
|
| 323 |
+
"""Process the output of the next step.
|
| 324 |
+
|
| 325 |
+
Process the output of the next step,
|
| 326 |
+
handling AgentFinish and tool return cases.
|
| 327 |
+
"""
|
| 328 |
+
logger.debug("Processing output of Agent loop step")
|
| 329 |
+
if isinstance(next_step_output, AgentFinish):
|
| 330 |
+
logger.debug(
|
| 331 |
+
"Hit AgentFinish: _return -> on_chain_end -> run final output logic",
|
| 332 |
+
)
|
| 333 |
+
return self._return(next_step_output, run_manager=run_manager)
|
| 334 |
+
|
| 335 |
+
self.intermediate_steps.extend(next_step_output)
|
| 336 |
+
logger.debug("Updated intermediate_steps with step output")
|
| 337 |
+
|
| 338 |
+
# Check for tool return
|
| 339 |
+
if len(next_step_output) == 1:
|
| 340 |
+
next_step_action = next_step_output[0]
|
| 341 |
+
tool_return = self.agent_executor._get_tool_return(next_step_action) # noqa: SLF001
|
| 342 |
+
if tool_return is not None:
|
| 343 |
+
return self._return(tool_return, run_manager=run_manager)
|
| 344 |
+
|
| 345 |
+
return AddableDict(intermediate_step=next_step_output)
|
| 346 |
+
|
| 347 |
+
async def _aprocess_next_step_output(
|
| 348 |
+
self,
|
| 349 |
+
next_step_output: AgentFinish | list[tuple[AgentAction, str]],
|
| 350 |
+
run_manager: AsyncCallbackManagerForChainRun,
|
| 351 |
+
) -> AddableDict:
|
| 352 |
+
"""Process the output of the next async step.
|
| 353 |
+
|
| 354 |
+
Process the output of the next async step,
|
| 355 |
+
handling AgentFinish and tool return cases.
|
| 356 |
+
"""
|
| 357 |
+
logger.debug("Processing output of async Agent loop step")
|
| 358 |
+
if isinstance(next_step_output, AgentFinish):
|
| 359 |
+
logger.debug(
|
| 360 |
+
"Hit AgentFinish: _areturn -> on_chain_end -> run final output logic",
|
| 361 |
+
)
|
| 362 |
+
return await self._areturn(next_step_output, run_manager=run_manager)
|
| 363 |
+
|
| 364 |
+
self.intermediate_steps.extend(next_step_output)
|
| 365 |
+
logger.debug("Updated intermediate_steps with step output")
|
| 366 |
+
|
| 367 |
+
# Check for tool return
|
| 368 |
+
if len(next_step_output) == 1:
|
| 369 |
+
next_step_action = next_step_output[0]
|
| 370 |
+
tool_return = self.agent_executor._get_tool_return(next_step_action) # noqa: SLF001
|
| 371 |
+
if tool_return is not None:
|
| 372 |
+
return await self._areturn(tool_return, run_manager=run_manager)
|
| 373 |
+
|
| 374 |
+
return AddableDict(intermediate_step=next_step_output)
|
| 375 |
+
|
| 376 |
+
def _stop(self, run_manager: CallbackManagerForChainRun) -> AddableDict:
|
| 377 |
+
"""Stop the iterator.
|
| 378 |
+
|
| 379 |
+
Stop the iterator and raise a StopIteration exception with the stopped response.
|
| 380 |
+
"""
|
| 381 |
+
logger.warning("Stopping agent prematurely due to triggering stop condition")
|
| 382 |
+
# this manually constructs agent finish with output key
|
| 383 |
+
output = self.agent_executor._action_agent.return_stopped_response( # noqa: SLF001
|
| 384 |
+
self.agent_executor.early_stopping_method,
|
| 385 |
+
self.intermediate_steps,
|
| 386 |
+
**self.inputs,
|
| 387 |
+
)
|
| 388 |
+
return self._return(output, run_manager=run_manager)
|
| 389 |
+
|
| 390 |
+
async def _astop(self, run_manager: AsyncCallbackManagerForChainRun) -> AddableDict:
|
| 391 |
+
"""Stop the async iterator.
|
| 392 |
+
|
| 393 |
+
Stop the async iterator and raise a StopAsyncIteration exception with
|
| 394 |
+
the stopped response.
|
| 395 |
+
"""
|
| 396 |
+
logger.warning("Stopping agent prematurely due to triggering stop condition")
|
| 397 |
+
output = self.agent_executor._action_agent.return_stopped_response( # noqa: SLF001
|
| 398 |
+
self.agent_executor.early_stopping_method,
|
| 399 |
+
self.intermediate_steps,
|
| 400 |
+
**self.inputs,
|
| 401 |
+
)
|
| 402 |
+
return await self._areturn(output, run_manager=run_manager)
|
| 403 |
+
|
| 404 |
+
def _return(
|
| 405 |
+
self,
|
| 406 |
+
output: AgentFinish,
|
| 407 |
+
run_manager: CallbackManagerForChainRun,
|
| 408 |
+
) -> AddableDict:
|
| 409 |
+
"""Return the final output of the iterator."""
|
| 410 |
+
returned_output = self.agent_executor._return( # noqa: SLF001
|
| 411 |
+
output,
|
| 412 |
+
self.intermediate_steps,
|
| 413 |
+
run_manager=run_manager,
|
| 414 |
+
)
|
| 415 |
+
returned_output["messages"] = output.messages
|
| 416 |
+
run_manager.on_chain_end(returned_output)
|
| 417 |
+
return self.make_final_outputs(returned_output, run_manager)
|
| 418 |
+
|
| 419 |
+
async def _areturn(
|
| 420 |
+
self,
|
| 421 |
+
output: AgentFinish,
|
| 422 |
+
run_manager: AsyncCallbackManagerForChainRun,
|
| 423 |
+
) -> AddableDict:
|
| 424 |
+
"""Return the final output of the async iterator."""
|
| 425 |
+
returned_output = await self.agent_executor._areturn( # noqa: SLF001
|
| 426 |
+
output,
|
| 427 |
+
self.intermediate_steps,
|
| 428 |
+
run_manager=run_manager,
|
| 429 |
+
)
|
| 430 |
+
returned_output["messages"] = output.messages
|
| 431 |
+
await run_manager.on_chain_end(returned_output)
|
| 432 |
+
return self.make_final_outputs(returned_output, run_manager)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/agent_types.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Module definitions of agent types together with corresponding agents."""
|
| 2 |
+
|
| 3 |
+
from enum import Enum
|
| 4 |
+
|
| 5 |
+
from langchain_core._api import deprecated
|
| 6 |
+
|
| 7 |
+
from langchain_classic._api.deprecation import AGENT_DEPRECATION_WARNING
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@deprecated(
|
| 11 |
+
"0.1.0",
|
| 12 |
+
message=AGENT_DEPRECATION_WARNING,
|
| 13 |
+
removal="2.0.0",
|
| 14 |
+
)
|
| 15 |
+
class AgentType(str, Enum):
|
| 16 |
+
"""An enum for agent types."""
|
| 17 |
+
|
| 18 |
+
ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description"
|
| 19 |
+
"""A zero shot agent that does a reasoning step before acting."""
|
| 20 |
+
|
| 21 |
+
REACT_DOCSTORE = "react-docstore"
|
| 22 |
+
"""A zero shot agent that does a reasoning step before acting.
|
| 23 |
+
|
| 24 |
+
This agent has access to a document store that allows it to look up
|
| 25 |
+
relevant information to answering the question.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
SELF_ASK_WITH_SEARCH = "self-ask-with-search"
|
| 29 |
+
"""An agent that breaks down a complex question into a series of simpler questions.
|
| 30 |
+
|
| 31 |
+
This agent uses a search tool to look up answers to the simpler questions
|
| 32 |
+
in order to answer the original complex question.
|
| 33 |
+
"""
|
| 34 |
+
CONVERSATIONAL_REACT_DESCRIPTION = "conversational-react-description"
|
| 35 |
+
CHAT_ZERO_SHOT_REACT_DESCRIPTION = "chat-zero-shot-react-description"
|
| 36 |
+
"""A zero shot agent that does a reasoning step before acting.
|
| 37 |
+
|
| 38 |
+
This agent is designed to be used in conjunction
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
CHAT_CONVERSATIONAL_REACT_DESCRIPTION = "chat-conversational-react-description"
|
| 42 |
+
|
| 43 |
+
STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION = (
|
| 44 |
+
"structured-chat-zero-shot-react-description"
|
| 45 |
+
)
|
| 46 |
+
"""An zero-shot react agent optimized for chat models.
|
| 47 |
+
|
| 48 |
+
This agent is capable of invoking tools that have multiple inputs.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
OPENAI_FUNCTIONS = "openai-functions"
|
| 52 |
+
"""An agent optimized for using open AI functions."""
|
| 53 |
+
|
| 54 |
+
OPENAI_MULTI_FUNCTIONS = "openai-multi-functions"
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/initialize.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load agent."""
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
from collections.abc import Sequence
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from langchain_core._api import deprecated
|
| 8 |
+
from langchain_core.callbacks import BaseCallbackManager
|
| 9 |
+
from langchain_core.language_models import BaseLanguageModel
|
| 10 |
+
from langchain_core.tools import BaseTool
|
| 11 |
+
|
| 12 |
+
from langchain_classic._api.deprecation import AGENT_DEPRECATION_WARNING
|
| 13 |
+
from langchain_classic.agents.agent import AgentExecutor
|
| 14 |
+
from langchain_classic.agents.agent_types import AgentType
|
| 15 |
+
from langchain_classic.agents.loading import load_agent
|
| 16 |
+
from langchain_classic.agents.types import AGENT_TO_CLASS
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@deprecated(
|
| 20 |
+
"0.1.0",
|
| 21 |
+
message=AGENT_DEPRECATION_WARNING,
|
| 22 |
+
removal="2.0.0",
|
| 23 |
+
)
|
| 24 |
+
def initialize_agent(
|
| 25 |
+
tools: Sequence[BaseTool],
|
| 26 |
+
llm: BaseLanguageModel,
|
| 27 |
+
agent: AgentType | None = None,
|
| 28 |
+
callback_manager: BaseCallbackManager | None = None,
|
| 29 |
+
agent_path: str | None = None,
|
| 30 |
+
agent_kwargs: dict | None = None,
|
| 31 |
+
*,
|
| 32 |
+
tags: Sequence[str] | None = None,
|
| 33 |
+
**kwargs: Any,
|
| 34 |
+
) -> AgentExecutor:
|
| 35 |
+
"""Load an agent executor given tools and LLM.
|
| 36 |
+
|
| 37 |
+
!!! warning
|
| 38 |
+
|
| 39 |
+
This function is no deprecated in favor of
|
| 40 |
+
[`create_agent`][langchain.agents.create_agent] from the `langchain`
|
| 41 |
+
package, which provides a more flexible agent factory with middleware
|
| 42 |
+
support, structured output, and integration with LangGraph.
|
| 43 |
+
|
| 44 |
+
For migration guidance, see
|
| 45 |
+
[Migrating to langchain v1](https://docs.langchain.com/oss/python/migrate/langchain-v1)
|
| 46 |
+
and
|
| 47 |
+
[Migrating from AgentExecutor](https://python.langchain.com/docs/how_to/migrate_agent/).
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
tools: List of tools this agent has access to.
|
| 51 |
+
llm: Language model to use as the agent.
|
| 52 |
+
agent: Agent type to use. If `None` and agent_path is also None, will default
|
| 53 |
+
to AgentType.ZERO_SHOT_REACT_DESCRIPTION.
|
| 54 |
+
callback_manager: CallbackManager to use. Global callback manager is used if
|
| 55 |
+
not provided.
|
| 56 |
+
agent_path: Path to serialized agent to use. If `None` and agent is also None,
|
| 57 |
+
will default to AgentType.ZERO_SHOT_REACT_DESCRIPTION.
|
| 58 |
+
agent_kwargs: Additional keyword arguments to pass to the underlying agent.
|
| 59 |
+
tags: Tags to apply to the traced runs.
|
| 60 |
+
kwargs: Additional keyword arguments passed to the agent executor.
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
An agent executor.
|
| 64 |
+
|
| 65 |
+
Raises:
|
| 66 |
+
ValueError: If both `agent` and `agent_path` are specified.
|
| 67 |
+
ValueError: If `agent` is not a valid agent type.
|
| 68 |
+
ValueError: If both `agent` and `agent_path` are None.
|
| 69 |
+
"""
|
| 70 |
+
tags_ = list(tags) if tags else []
|
| 71 |
+
if agent is None and agent_path is None:
|
| 72 |
+
agent = AgentType.ZERO_SHOT_REACT_DESCRIPTION
|
| 73 |
+
if agent is not None and agent_path is not None:
|
| 74 |
+
msg = (
|
| 75 |
+
"Both `agent` and `agent_path` are specified, "
|
| 76 |
+
"but at most only one should be."
|
| 77 |
+
)
|
| 78 |
+
raise ValueError(msg)
|
| 79 |
+
if agent is not None:
|
| 80 |
+
if agent not in AGENT_TO_CLASS:
|
| 81 |
+
msg = (
|
| 82 |
+
f"Got unknown agent type: {agent}. "
|
| 83 |
+
f"Valid types are: {AGENT_TO_CLASS.keys()}."
|
| 84 |
+
)
|
| 85 |
+
raise ValueError(msg)
|
| 86 |
+
tags_.append(agent.value if isinstance(agent, AgentType) else agent)
|
| 87 |
+
agent_cls = AGENT_TO_CLASS[agent]
|
| 88 |
+
agent_kwargs = agent_kwargs or {}
|
| 89 |
+
agent_obj = agent_cls.from_llm_and_tools(
|
| 90 |
+
llm,
|
| 91 |
+
tools,
|
| 92 |
+
callback_manager=callback_manager,
|
| 93 |
+
**agent_kwargs,
|
| 94 |
+
)
|
| 95 |
+
elif agent_path is not None:
|
| 96 |
+
agent_obj = load_agent(
|
| 97 |
+
agent_path,
|
| 98 |
+
llm=llm,
|
| 99 |
+
tools=tools,
|
| 100 |
+
callback_manager=callback_manager,
|
| 101 |
+
)
|
| 102 |
+
with contextlib.suppress(NotImplementedError):
|
| 103 |
+
# TODO: Add tags from the serialized object directly.
|
| 104 |
+
tags_.append(agent_obj._agent_type) # noqa: SLF001
|
| 105 |
+
else:
|
| 106 |
+
msg = (
|
| 107 |
+
"Somehow both `agent` and `agent_path` are None, this should never happen."
|
| 108 |
+
)
|
| 109 |
+
raise ValueError(msg)
|
| 110 |
+
return AgentExecutor.from_agent_and_tools(
|
| 111 |
+
agent=agent_obj,
|
| 112 |
+
tools=tools,
|
| 113 |
+
callback_manager=callback_manager,
|
| 114 |
+
tags=tags_,
|
| 115 |
+
**kwargs,
|
| 116 |
+
)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/load_tools.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
from langchain_classic._api import create_importer
|
| 4 |
+
|
| 5 |
+
_importer = create_importer(
|
| 6 |
+
__package__,
|
| 7 |
+
fallback_module="langchain_community.agent_toolkits.load_tools",
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def __getattr__(name: str) -> Any:
|
| 12 |
+
"""Look up attributes dynamically."""
|
| 13 |
+
return _importer(name)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/loading.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functionality for loading agents."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import yaml
|
| 9 |
+
from langchain_core._api import deprecated
|
| 10 |
+
from langchain_core.language_models import BaseLanguageModel
|
| 11 |
+
from langchain_core.tools import Tool
|
| 12 |
+
|
| 13 |
+
from langchain_classic.agents.agent import BaseMultiActionAgent, BaseSingleActionAgent
|
| 14 |
+
from langchain_classic.agents.types import AGENT_TO_CLASS
|
| 15 |
+
from langchain_classic.chains.loading import load_chain, load_chain_from_config
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/agents/"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _load_agent_from_tools(
|
| 23 |
+
config: dict,
|
| 24 |
+
llm: BaseLanguageModel,
|
| 25 |
+
tools: list[Tool],
|
| 26 |
+
**kwargs: Any,
|
| 27 |
+
) -> BaseSingleActionAgent | BaseMultiActionAgent:
|
| 28 |
+
config_type = config.pop("_type")
|
| 29 |
+
if config_type not in AGENT_TO_CLASS:
|
| 30 |
+
msg = f"Loading {config_type} agent not supported"
|
| 31 |
+
raise ValueError(msg)
|
| 32 |
+
|
| 33 |
+
agent_cls = AGENT_TO_CLASS[config_type]
|
| 34 |
+
combined_config = {**config, **kwargs}
|
| 35 |
+
return agent_cls.from_llm_and_tools(llm, tools, **combined_config)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@deprecated("0.1.0", removal="2.0.0")
|
| 39 |
+
def load_agent_from_config(
|
| 40 |
+
config: dict,
|
| 41 |
+
llm: BaseLanguageModel | None = None,
|
| 42 |
+
tools: list[Tool] | None = None,
|
| 43 |
+
**kwargs: Any,
|
| 44 |
+
) -> BaseSingleActionAgent | BaseMultiActionAgent:
|
| 45 |
+
"""Load agent from Config Dict.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
config: Config dict to load agent from.
|
| 49 |
+
llm: Language model to use as the agent.
|
| 50 |
+
tools: List of tools this agent has access to.
|
| 51 |
+
kwargs: Additional keyword arguments passed to the agent executor.
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
An agent executor.
|
| 55 |
+
|
| 56 |
+
Raises:
|
| 57 |
+
ValueError: If agent type is not specified in the config.
|
| 58 |
+
"""
|
| 59 |
+
if "_type" not in config:
|
| 60 |
+
msg = "Must specify an agent Type in config"
|
| 61 |
+
raise ValueError(msg)
|
| 62 |
+
load_from_tools = config.pop("load_from_llm_and_tools", False)
|
| 63 |
+
if load_from_tools:
|
| 64 |
+
if llm is None:
|
| 65 |
+
msg = (
|
| 66 |
+
"If `load_from_llm_and_tools` is set to True, then LLM must be provided"
|
| 67 |
+
)
|
| 68 |
+
raise ValueError(msg)
|
| 69 |
+
if tools is None:
|
| 70 |
+
msg = (
|
| 71 |
+
"If `load_from_llm_and_tools` is set to True, "
|
| 72 |
+
"then tools must be provided"
|
| 73 |
+
)
|
| 74 |
+
raise ValueError(msg)
|
| 75 |
+
return _load_agent_from_tools(config, llm, tools, **kwargs)
|
| 76 |
+
config_type = config.pop("_type")
|
| 77 |
+
|
| 78 |
+
if config_type not in AGENT_TO_CLASS:
|
| 79 |
+
msg = f"Loading {config_type} agent not supported"
|
| 80 |
+
raise ValueError(msg)
|
| 81 |
+
|
| 82 |
+
agent_cls = AGENT_TO_CLASS[config_type]
|
| 83 |
+
if "llm_chain" in config:
|
| 84 |
+
config["llm_chain"] = load_chain_from_config(config.pop("llm_chain"))
|
| 85 |
+
elif "llm_chain_path" in config:
|
| 86 |
+
config["llm_chain"] = load_chain(config.pop("llm_chain_path"))
|
| 87 |
+
else:
|
| 88 |
+
msg = "One of `llm_chain` and `llm_chain_path` should be specified."
|
| 89 |
+
raise ValueError(msg)
|
| 90 |
+
if "output_parser" in config:
|
| 91 |
+
logger.warning(
|
| 92 |
+
"Currently loading output parsers on agent is not supported, "
|
| 93 |
+
"will just use the default one.",
|
| 94 |
+
)
|
| 95 |
+
del config["output_parser"]
|
| 96 |
+
|
| 97 |
+
combined_config = {**config, **kwargs}
|
| 98 |
+
return agent_cls(**combined_config)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@deprecated("0.1.0", removal="2.0.0")
|
| 102 |
+
def load_agent(
|
| 103 |
+
path: str | Path,
|
| 104 |
+
**kwargs: Any,
|
| 105 |
+
) -> BaseSingleActionAgent | BaseMultiActionAgent:
|
| 106 |
+
"""Unified method for loading an agent from LangChainHub or local fs.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
path: Path to the agent file.
|
| 110 |
+
kwargs: Additional keyword arguments passed to the agent executor.
|
| 111 |
+
|
| 112 |
+
Returns:
|
| 113 |
+
An agent executor.
|
| 114 |
+
|
| 115 |
+
Raises:
|
| 116 |
+
RuntimeError: If loading from the deprecated github-based
|
| 117 |
+
Hub is attempted.
|
| 118 |
+
"""
|
| 119 |
+
if isinstance(path, str) and path.startswith("lc://"):
|
| 120 |
+
msg = (
|
| 121 |
+
"Loading from the deprecated github-based Hub is no longer supported. "
|
| 122 |
+
"Please use the new LangChain Hub at https://smith.langchain.com/hub "
|
| 123 |
+
"instead."
|
| 124 |
+
)
|
| 125 |
+
raise RuntimeError(msg)
|
| 126 |
+
return _load_agent_from_file(path, **kwargs)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _load_agent_from_file(
|
| 130 |
+
file: str | Path,
|
| 131 |
+
**kwargs: Any,
|
| 132 |
+
) -> BaseSingleActionAgent | BaseMultiActionAgent:
|
| 133 |
+
"""Load agent from file."""
|
| 134 |
+
valid_suffixes = {"json", "yaml"}
|
| 135 |
+
# Convert file to Path object.
|
| 136 |
+
file_path = Path(file) if isinstance(file, str) else file
|
| 137 |
+
# Load from either json or yaml.
|
| 138 |
+
if file_path.suffix[1:] == "json":
|
| 139 |
+
with file_path.open() as f:
|
| 140 |
+
config = json.load(f)
|
| 141 |
+
elif file_path.suffix[1:] == "yaml":
|
| 142 |
+
with file_path.open() as f:
|
| 143 |
+
config = yaml.safe_load(f)
|
| 144 |
+
else:
|
| 145 |
+
msg = f"Unsupported file type, must be one of {valid_suffixes}."
|
| 146 |
+
raise ValueError(msg)
|
| 147 |
+
# Load the agent from the config now.
|
| 148 |
+
return load_agent_from_config(config, **kwargs)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/schema.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
from langchain_core.agents import AgentAction
|
| 4 |
+
from langchain_core.prompts.chat import ChatPromptTemplate
|
| 5 |
+
from typing_extensions import override
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class AgentScratchPadChatPromptTemplate(ChatPromptTemplate):
|
| 9 |
+
"""Chat prompt template for the agent scratchpad."""
|
| 10 |
+
|
| 11 |
+
@classmethod
|
| 12 |
+
@override
|
| 13 |
+
def is_lc_serializable(cls) -> bool:
|
| 14 |
+
return False
|
| 15 |
+
|
| 16 |
+
def _construct_agent_scratchpad(
|
| 17 |
+
self,
|
| 18 |
+
intermediate_steps: list[tuple[AgentAction, str]],
|
| 19 |
+
) -> str:
|
| 20 |
+
if len(intermediate_steps) == 0:
|
| 21 |
+
return ""
|
| 22 |
+
thoughts = ""
|
| 23 |
+
for action, observation in intermediate_steps:
|
| 24 |
+
thoughts += action.log
|
| 25 |
+
thoughts += f"\nObservation: {observation}\nThought: "
|
| 26 |
+
return (
|
| 27 |
+
f"This was your previous work "
|
| 28 |
+
f"(but I haven't seen any of it! I only see what "
|
| 29 |
+
f"you return as final answer):\n{thoughts}"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
def _merge_partial_and_user_variables(self, **kwargs: Any) -> dict[str, Any]:
|
| 33 |
+
intermediate_steps = kwargs.pop("intermediate_steps")
|
| 34 |
+
kwargs["agent_scratchpad"] = self._construct_agent_scratchpad(
|
| 35 |
+
intermediate_steps,
|
| 36 |
+
)
|
| 37 |
+
return kwargs
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/tools.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Interface for tools."""
|
| 2 |
+
|
| 3 |
+
from langchain_core.callbacks import (
|
| 4 |
+
AsyncCallbackManagerForToolRun,
|
| 5 |
+
CallbackManagerForToolRun,
|
| 6 |
+
)
|
| 7 |
+
from langchain_core.tools import BaseTool, tool
|
| 8 |
+
from typing_extensions import override
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class InvalidTool(BaseTool):
|
| 12 |
+
"""Tool that is run when invalid tool name is encountered by agent."""
|
| 13 |
+
|
| 14 |
+
name: str = "invalid_tool"
|
| 15 |
+
"""Name of the tool."""
|
| 16 |
+
description: str = "Called when tool name is invalid. Suggests valid tool names."
|
| 17 |
+
"""Description of the tool."""
|
| 18 |
+
|
| 19 |
+
@override
|
| 20 |
+
def _run(
|
| 21 |
+
self,
|
| 22 |
+
requested_tool_name: str,
|
| 23 |
+
available_tool_names: list[str],
|
| 24 |
+
run_manager: CallbackManagerForToolRun | None = None,
|
| 25 |
+
) -> str:
|
| 26 |
+
"""Use the tool."""
|
| 27 |
+
available_tool_names_str = ", ".join(list(available_tool_names))
|
| 28 |
+
return (
|
| 29 |
+
f"{requested_tool_name} is not a valid tool, "
|
| 30 |
+
f"try one of [{available_tool_names_str}]."
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
@override
|
| 34 |
+
async def _arun(
|
| 35 |
+
self,
|
| 36 |
+
requested_tool_name: str,
|
| 37 |
+
available_tool_names: list[str],
|
| 38 |
+
run_manager: AsyncCallbackManagerForToolRun | None = None,
|
| 39 |
+
) -> str:
|
| 40 |
+
"""Use the tool asynchronously."""
|
| 41 |
+
available_tool_names_str = ", ".join(list(available_tool_names))
|
| 42 |
+
return (
|
| 43 |
+
f"{requested_tool_name} is not a valid tool, "
|
| 44 |
+
f"try one of [{available_tool_names_str}]."
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
__all__ = ["InvalidTool", "tool"]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/types.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_classic.agents.agent import BaseSingleActionAgent
|
| 2 |
+
from langchain_classic.agents.agent_types import AgentType
|
| 3 |
+
from langchain_classic.agents.chat.base import ChatAgent
|
| 4 |
+
from langchain_classic.agents.conversational.base import ConversationalAgent
|
| 5 |
+
from langchain_classic.agents.conversational_chat.base import ConversationalChatAgent
|
| 6 |
+
from langchain_classic.agents.mrkl.base import ZeroShotAgent
|
| 7 |
+
from langchain_classic.agents.openai_functions_agent.base import OpenAIFunctionsAgent
|
| 8 |
+
from langchain_classic.agents.openai_functions_multi_agent.base import (
|
| 9 |
+
OpenAIMultiFunctionsAgent,
|
| 10 |
+
)
|
| 11 |
+
from langchain_classic.agents.react.base import ReActDocstoreAgent
|
| 12 |
+
from langchain_classic.agents.self_ask_with_search.base import SelfAskWithSearchAgent
|
| 13 |
+
from langchain_classic.agents.structured_chat.base import StructuredChatAgent
|
| 14 |
+
|
| 15 |
+
AGENT_TYPE = type[BaseSingleActionAgent] | type[OpenAIMultiFunctionsAgent]
|
| 16 |
+
|
| 17 |
+
AGENT_TO_CLASS: dict[AgentType, AGENT_TYPE] = {
|
| 18 |
+
AgentType.ZERO_SHOT_REACT_DESCRIPTION: ZeroShotAgent,
|
| 19 |
+
AgentType.REACT_DOCSTORE: ReActDocstoreAgent,
|
| 20 |
+
AgentType.SELF_ASK_WITH_SEARCH: SelfAskWithSearchAgent,
|
| 21 |
+
AgentType.CONVERSATIONAL_REACT_DESCRIPTION: ConversationalAgent,
|
| 22 |
+
AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION: ChatAgent,
|
| 23 |
+
AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION: ConversationalChatAgent,
|
| 24 |
+
AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION: StructuredChatAgent,
|
| 25 |
+
AgentType.OPENAI_FUNCTIONS: OpenAIFunctionsAgent,
|
| 26 |
+
AgentType.OPENAI_MULTI_FUNCTIONS: OpenAIMultiFunctionsAgent,
|
| 27 |
+
}
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/agents/utils.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
|
| 3 |
+
from langchain_core.tools import BaseTool
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def validate_tools_single_input(class_name: str, tools: Sequence[BaseTool]) -> None:
|
| 7 |
+
"""Validate tools for single input.
|
| 8 |
+
|
| 9 |
+
Args:
|
| 10 |
+
class_name: Name of the class.
|
| 11 |
+
tools: List of tools to validate.
|
| 12 |
+
|
| 13 |
+
Raises:
|
| 14 |
+
ValueError: If a multi-input tool is found in tools.
|
| 15 |
+
"""
|
| 16 |
+
for tool in tools:
|
| 17 |
+
if not tool.is_single_input:
|
| 18 |
+
msg = f"{class_name} does not support multi-input tool {tool.name}."
|
| 19 |
+
raise ValueError(msg)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/__init__.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""**Callback handlers** allow listening to events in LangChain."""
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Any
|
| 4 |
+
|
| 5 |
+
from langchain_core.callbacks import (
|
| 6 |
+
FileCallbackHandler,
|
| 7 |
+
StdOutCallbackHandler,
|
| 8 |
+
StreamingStdOutCallbackHandler,
|
| 9 |
+
)
|
| 10 |
+
from langchain_core.tracers.context import (
|
| 11 |
+
collect_runs,
|
| 12 |
+
tracing_v2_enabled,
|
| 13 |
+
)
|
| 14 |
+
from langchain_core.tracers.langchain import LangChainTracer
|
| 15 |
+
|
| 16 |
+
from langchain_classic._api import create_importer
|
| 17 |
+
from langchain_classic.callbacks.streaming_aiter import AsyncIteratorCallbackHandler
|
| 18 |
+
from langchain_classic.callbacks.streaming_stdout_final_only import (
|
| 19 |
+
FinalStreamingStdOutCallbackHandler,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from langchain_community.callbacks.aim_callback import AimCallbackHandler
|
| 24 |
+
from langchain_community.callbacks.argilla_callback import ArgillaCallbackHandler
|
| 25 |
+
from langchain_community.callbacks.arize_callback import ArizeCallbackHandler
|
| 26 |
+
from langchain_community.callbacks.arthur_callback import ArthurCallbackHandler
|
| 27 |
+
from langchain_community.callbacks.clearml_callback import ClearMLCallbackHandler
|
| 28 |
+
from langchain_community.callbacks.comet_ml_callback import CometCallbackHandler
|
| 29 |
+
from langchain_community.callbacks.context_callback import ContextCallbackHandler
|
| 30 |
+
from langchain_community.callbacks.flyte_callback import FlyteCallbackHandler
|
| 31 |
+
from langchain_community.callbacks.human import HumanApprovalCallbackHandler
|
| 32 |
+
from langchain_community.callbacks.infino_callback import InfinoCallbackHandler
|
| 33 |
+
from langchain_community.callbacks.labelstudio_callback import (
|
| 34 |
+
LabelStudioCallbackHandler,
|
| 35 |
+
)
|
| 36 |
+
from langchain_community.callbacks.llmonitor_callback import (
|
| 37 |
+
LLMonitorCallbackHandler,
|
| 38 |
+
)
|
| 39 |
+
from langchain_community.callbacks.manager import (
|
| 40 |
+
get_openai_callback,
|
| 41 |
+
wandb_tracing_enabled,
|
| 42 |
+
)
|
| 43 |
+
from langchain_community.callbacks.mlflow_callback import MlflowCallbackHandler
|
| 44 |
+
from langchain_community.callbacks.openai_info import OpenAICallbackHandler
|
| 45 |
+
from langchain_community.callbacks.promptlayer_callback import (
|
| 46 |
+
PromptLayerCallbackHandler,
|
| 47 |
+
)
|
| 48 |
+
from langchain_community.callbacks.sagemaker_callback import (
|
| 49 |
+
SageMakerCallbackHandler,
|
| 50 |
+
)
|
| 51 |
+
from langchain_community.callbacks.streamlit import StreamlitCallbackHandler
|
| 52 |
+
from langchain_community.callbacks.streamlit.streamlit_callback_handler import (
|
| 53 |
+
LLMThoughtLabeler,
|
| 54 |
+
)
|
| 55 |
+
from langchain_community.callbacks.trubrics_callback import TrubricsCallbackHandler
|
| 56 |
+
from langchain_community.callbacks.wandb_callback import WandbCallbackHandler
|
| 57 |
+
from langchain_community.callbacks.whylabs_callback import WhyLabsCallbackHandler
|
| 58 |
+
|
| 59 |
+
# Create a way to dynamically look up deprecated imports.
|
| 60 |
+
# Used to consolidate logic for raising deprecation warnings and
|
| 61 |
+
# handling optional imports.
|
| 62 |
+
DEPRECATED_LOOKUP = {
|
| 63 |
+
"AimCallbackHandler": "langchain_community.callbacks.aim_callback",
|
| 64 |
+
"ArgillaCallbackHandler": "langchain_community.callbacks.argilla_callback",
|
| 65 |
+
"ArizeCallbackHandler": "langchain_community.callbacks.arize_callback",
|
| 66 |
+
"PromptLayerCallbackHandler": "langchain_community.callbacks.promptlayer_callback",
|
| 67 |
+
"ArthurCallbackHandler": "langchain_community.callbacks.arthur_callback",
|
| 68 |
+
"ClearMLCallbackHandler": "langchain_community.callbacks.clearml_callback",
|
| 69 |
+
"CometCallbackHandler": "langchain_community.callbacks.comet_ml_callback",
|
| 70 |
+
"ContextCallbackHandler": "langchain_community.callbacks.context_callback",
|
| 71 |
+
"HumanApprovalCallbackHandler": "langchain_community.callbacks.human",
|
| 72 |
+
"InfinoCallbackHandler": "langchain_community.callbacks.infino_callback",
|
| 73 |
+
"MlflowCallbackHandler": "langchain_community.callbacks.mlflow_callback",
|
| 74 |
+
"LLMonitorCallbackHandler": "langchain_community.callbacks.llmonitor_callback",
|
| 75 |
+
"OpenAICallbackHandler": "langchain_community.callbacks.openai_info",
|
| 76 |
+
"LLMThoughtLabeler": (
|
| 77 |
+
"langchain_community.callbacks.streamlit.streamlit_callback_handler"
|
| 78 |
+
),
|
| 79 |
+
"StreamlitCallbackHandler": "langchain_community.callbacks.streamlit",
|
| 80 |
+
"WandbCallbackHandler": "langchain_community.callbacks.wandb_callback",
|
| 81 |
+
"WhyLabsCallbackHandler": "langchain_community.callbacks.whylabs_callback",
|
| 82 |
+
"get_openai_callback": "langchain_community.callbacks.manager",
|
| 83 |
+
"wandb_tracing_enabled": "langchain_community.callbacks.manager",
|
| 84 |
+
"FlyteCallbackHandler": "langchain_community.callbacks.flyte_callback",
|
| 85 |
+
"SageMakerCallbackHandler": "langchain_community.callbacks.sagemaker_callback",
|
| 86 |
+
"LabelStudioCallbackHandler": "langchain_community.callbacks.labelstudio_callback",
|
| 87 |
+
"TrubricsCallbackHandler": "langchain_community.callbacks.trubrics_callback",
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
_import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def __getattr__(name: str) -> Any:
|
| 94 |
+
"""Look up attributes dynamically."""
|
| 95 |
+
return _import_attribute(name)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
__all__ = [
|
| 99 |
+
"AimCallbackHandler",
|
| 100 |
+
"ArgillaCallbackHandler",
|
| 101 |
+
"ArizeCallbackHandler",
|
| 102 |
+
"ArthurCallbackHandler",
|
| 103 |
+
"AsyncIteratorCallbackHandler",
|
| 104 |
+
"ClearMLCallbackHandler",
|
| 105 |
+
"CometCallbackHandler",
|
| 106 |
+
"ContextCallbackHandler",
|
| 107 |
+
"FileCallbackHandler",
|
| 108 |
+
"FinalStreamingStdOutCallbackHandler",
|
| 109 |
+
"FlyteCallbackHandler",
|
| 110 |
+
"HumanApprovalCallbackHandler",
|
| 111 |
+
"InfinoCallbackHandler",
|
| 112 |
+
"LLMThoughtLabeler",
|
| 113 |
+
"LLMonitorCallbackHandler",
|
| 114 |
+
"LabelStudioCallbackHandler",
|
| 115 |
+
"LangChainTracer",
|
| 116 |
+
"MlflowCallbackHandler",
|
| 117 |
+
"OpenAICallbackHandler",
|
| 118 |
+
"PromptLayerCallbackHandler",
|
| 119 |
+
"SageMakerCallbackHandler",
|
| 120 |
+
"StdOutCallbackHandler",
|
| 121 |
+
"StreamingStdOutCallbackHandler",
|
| 122 |
+
"StreamlitCallbackHandler",
|
| 123 |
+
"TrubricsCallbackHandler",
|
| 124 |
+
"WandbCallbackHandler",
|
| 125 |
+
"WhyLabsCallbackHandler",
|
| 126 |
+
"collect_runs",
|
| 127 |
+
"get_openai_callback",
|
| 128 |
+
"tracing_v2_enabled",
|
| 129 |
+
"wandb_tracing_enabled",
|
| 130 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/aim_callback.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Any
|
| 2 |
+
|
| 3 |
+
from langchain_classic._api import create_importer
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from langchain_community.callbacks.aim_callback import (
|
| 7 |
+
AimCallbackHandler,
|
| 8 |
+
BaseMetadataCallbackHandler,
|
| 9 |
+
import_aim,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
# Create a way to dynamically look up deprecated imports.
|
| 13 |
+
# Used to consolidate logic for raising deprecation warnings and
|
| 14 |
+
# handling optional imports.
|
| 15 |
+
DEPRECATED_LOOKUP = {
|
| 16 |
+
"import_aim": "langchain_community.callbacks.aim_callback",
|
| 17 |
+
"BaseMetadataCallbackHandler": "langchain_community.callbacks.aim_callback",
|
| 18 |
+
"AimCallbackHandler": "langchain_community.callbacks.aim_callback",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
_import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def __getattr__(name: str) -> Any:
|
| 25 |
+
"""Look up attributes dynamically."""
|
| 26 |
+
return _import_attribute(name)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
__all__ = [
|
| 30 |
+
"AimCallbackHandler",
|
| 31 |
+
"BaseMetadataCallbackHandler",
|
| 32 |
+
"import_aim",
|
| 33 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/argilla_callback.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Any
|
| 2 |
+
|
| 3 |
+
from langchain_classic._api import create_importer
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from langchain_community.callbacks.argilla_callback import ArgillaCallbackHandler
|
| 7 |
+
|
| 8 |
+
# Create a way to dynamically look up deprecated imports.
|
| 9 |
+
# Used to consolidate logic for raising deprecation warnings and
|
| 10 |
+
# handling optional imports.
|
| 11 |
+
DEPRECATED_LOOKUP = {
|
| 12 |
+
"ArgillaCallbackHandler": "langchain_community.callbacks.argilla_callback",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
_import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def __getattr__(name: str) -> Any:
|
| 19 |
+
"""Look up attributes dynamically."""
|
| 20 |
+
return _import_attribute(name)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = [
|
| 24 |
+
"ArgillaCallbackHandler",
|
| 25 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/arize_callback.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Any
|
| 2 |
+
|
| 3 |
+
from langchain_classic._api import create_importer
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from langchain_community.callbacks.arize_callback import ArizeCallbackHandler
|
| 7 |
+
|
| 8 |
+
# Create a way to dynamically look up deprecated imports.
|
| 9 |
+
# Used to consolidate logic for raising deprecation warnings and
|
| 10 |
+
# handling optional imports.
|
| 11 |
+
DEPRECATED_LOOKUP = {
|
| 12 |
+
"ArizeCallbackHandler": "langchain_community.callbacks.arize_callback",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
_import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def __getattr__(name: str) -> Any:
|
| 19 |
+
"""Look up attributes dynamically."""
|
| 20 |
+
return _import_attribute(name)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = [
|
| 24 |
+
"ArizeCallbackHandler",
|
| 25 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/arthur_callback.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Any
|
| 2 |
+
|
| 3 |
+
from langchain_classic._api import create_importer
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from langchain_community.callbacks.arthur_callback import ArthurCallbackHandler
|
| 7 |
+
|
| 8 |
+
# Create a way to dynamically look up deprecated imports.
|
| 9 |
+
# Used to consolidate logic for raising deprecation warnings and
|
| 10 |
+
# handling optional imports.
|
| 11 |
+
DEPRECATED_LOOKUP = {
|
| 12 |
+
"ArthurCallbackHandler": "langchain_community.callbacks.arthur_callback",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
_import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def __getattr__(name: str) -> Any:
|
| 19 |
+
"""Look up attributes dynamically."""
|
| 20 |
+
return _import_attribute(name)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = [
|
| 24 |
+
"ArthurCallbackHandler",
|
| 25 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/base.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base callback handler that can be used to handle callbacks in langchain."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from langchain_core.callbacks import (
|
| 6 |
+
AsyncCallbackHandler,
|
| 7 |
+
BaseCallbackHandler,
|
| 8 |
+
BaseCallbackManager,
|
| 9 |
+
CallbackManagerMixin,
|
| 10 |
+
Callbacks,
|
| 11 |
+
ChainManagerMixin,
|
| 12 |
+
LLMManagerMixin,
|
| 13 |
+
RetrieverManagerMixin,
|
| 14 |
+
RunManagerMixin,
|
| 15 |
+
ToolManagerMixin,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"AsyncCallbackHandler",
|
| 20 |
+
"BaseCallbackHandler",
|
| 21 |
+
"BaseCallbackManager",
|
| 22 |
+
"CallbackManagerMixin",
|
| 23 |
+
"Callbacks",
|
| 24 |
+
"ChainManagerMixin",
|
| 25 |
+
"LLMManagerMixin",
|
| 26 |
+
"RetrieverManagerMixin",
|
| 27 |
+
"RunManagerMixin",
|
| 28 |
+
"ToolManagerMixin",
|
| 29 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/clearml_callback.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Any
|
| 2 |
+
|
| 3 |
+
from langchain_classic._api import create_importer
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from langchain_community.callbacks.clearml_callback import ClearMLCallbackHandler
|
| 7 |
+
|
| 8 |
+
# Create a way to dynamically look up deprecated imports.
|
| 9 |
+
# Used to consolidate logic for raising deprecation warnings and
|
| 10 |
+
# handling optional imports.
|
| 11 |
+
DEPRECATED_LOOKUP = {
|
| 12 |
+
"ClearMLCallbackHandler": "langchain_community.callbacks.clearml_callback",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
_import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def __getattr__(name: str) -> Any:
|
| 19 |
+
"""Look up attributes dynamically."""
|
| 20 |
+
return _import_attribute(name)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = [
|
| 24 |
+
"ClearMLCallbackHandler",
|
| 25 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/comet_ml_callback.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Any
|
| 2 |
+
|
| 3 |
+
from langchain_classic._api import create_importer
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from langchain_community.callbacks.comet_ml_callback import CometCallbackHandler
|
| 7 |
+
|
| 8 |
+
# Create a way to dynamically look up deprecated imports.
|
| 9 |
+
# Used to consolidate logic for raising deprecation warnings and
|
| 10 |
+
# handling optional imports.
|
| 11 |
+
DEPRECATED_LOOKUP = {
|
| 12 |
+
"CometCallbackHandler": "langchain_community.callbacks.comet_ml_callback",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
_import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def __getattr__(name: str) -> Any:
|
| 19 |
+
"""Look up attributes dynamically."""
|
| 20 |
+
return _import_attribute(name)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = [
|
| 24 |
+
"CometCallbackHandler",
|
| 25 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/confident_callback.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Any
|
| 2 |
+
|
| 3 |
+
from langchain_classic._api import create_importer
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from langchain_community.callbacks.confident_callback import DeepEvalCallbackHandler
|
| 7 |
+
|
| 8 |
+
# Create a way to dynamically look up deprecated imports.
|
| 9 |
+
# Used to consolidate logic for raising deprecation warnings and
|
| 10 |
+
# handling optional imports.
|
| 11 |
+
DEPRECATED_LOOKUP = {
|
| 12 |
+
"DeepEvalCallbackHandler": "langchain_community.callbacks.confident_callback",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
_import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def __getattr__(name: str) -> Any:
|
| 19 |
+
"""Look up attributes dynamically."""
|
| 20 |
+
return _import_attribute(name)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = [
|
| 24 |
+
"DeepEvalCallbackHandler",
|
| 25 |
+
]
|
micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_classic/callbacks/context_callback.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Any
|
| 2 |
+
|
| 3 |
+
from langchain_classic._api import create_importer
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from langchain_community.callbacks.context_callback import ContextCallbackHandler
|
| 7 |
+
|
| 8 |
+
# Create a way to dynamically look up deprecated imports.
|
| 9 |
+
# Used to consolidate logic for raising deprecation warnings and
|
| 10 |
+
# handling optional imports.
|
| 11 |
+
DEPRECATED_LOOKUP = {
|
| 12 |
+
"ContextCallbackHandler": "langchain_community.callbacks.context_callback",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
_import_attribute = create_importer(__file__, deprecated_lookups=DEPRECATED_LOOKUP)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def __getattr__(name: str) -> Any:
|
| 19 |
+
"""Look up attributes dynamically."""
|
| 20 |
+
return _import_attribute(name)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = [
|
| 24 |
+
"ContextCallbackHandler",
|
| 25 |
+
]
|