sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
langchain-ai/langchain:libs/langchain/langchain_classic/chat_models/minimax.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.minimax import MiniMaxChat
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"MiniMaxChat": "langchain_community.chat_models.minimax"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"MiniMaxChat",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/chat_models/minimax.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/chat_models/mlflow.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.mlflow import ChatMlflow
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"ChatMlflow": "langchain_community.chat_models.mlflow"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ChatMlflow",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/chat_models/mlflow.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/chat_models/mlflow_ai_gateway.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.mlflow_ai_gateway import (
ChatMLflowAIGateway,
ChatParams,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"ChatMLflowAIGateway": "langchain_community.chat_models.mlflow_ai_gateway",
"ChatParams": "langchain_community.chat_models.mlflow_ai_gateway",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ChatMLflowAIGateway",
"ChatParams",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/chat_models/mlflow_ai_gateway.py",
"license": "MIT License",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/chat_models/ollama.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.ollama import ChatOllama
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"ChatOllama": "langchain_community.chat_models.ollama"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ChatOllama",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/chat_models/ollama.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/chat_models/openai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.openai import ChatOpenAI
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"ChatOpenAI": "langchain_community.chat_models.openai"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ChatOpenAI",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/chat_models/openai.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/chat_models/pai_eas_endpoint.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.pai_eas_endpoint import PaiEasChatEndpoint
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"PaiEasChatEndpoint": "langchain_community.chat_models.pai_eas_endpoint",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"PaiEasChatEndpoint",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/chat_models/pai_eas_endpoint.py",
"license": "MIT License",
"lines": 17,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/chat_models/promptlayer_openai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.promptlayer_openai import PromptLayerChatOpenAI
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"PromptLayerChatOpenAI": "langchain_community.chat_models.promptlayer_openai",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"PromptLayerChatOpenAI",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/chat_models/promptlayer_openai.py",
"license": "MIT License",
"lines": 17,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/chat_models/tongyi.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.tongyi import ChatTongyi
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"ChatTongyi": "langchain_community.chat_models.tongyi"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ChatTongyi",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/chat_models/tongyi.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/chat_models/vertexai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.vertexai import ChatVertexAI
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"ChatVertexAI": "langchain_community.chat_models.vertexai"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ChatVertexAI",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/chat_models/vertexai.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/chat_models/volcengine_maas.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.volcengine_maas import (
VolcEngineMaasChat,
convert_dict_to_message,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"convert_dict_to_message": "langchain_community.chat_models.volcengine_maas",
"VolcEngineMaasChat": "langchain_community.chat_models.volcengine_maas",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"VolcEngineMaasChat",
"convert_dict_to_message",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/chat_models/volcengine_maas.py",
"license": "MIT License",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/chat_models/yandex.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.yandex import ChatYandexGPT
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"ChatYandexGPT": "langchain_community.chat_models.yandex"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ChatYandexGPT",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/chat_models/yandex.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/docstore/base.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.docstore.base import AddableMixin, Docstore
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"Docstore": "langchain_community.docstore.base",
"AddableMixin": "langchain_community.docstore.base",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"AddableMixin",
"Docstore",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/docstore/base.py",
"license": "MIT License",
"lines": 19,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/docstore/in_memory.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.docstore.in_memory import InMemoryDocstore
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"InMemoryDocstore": "langchain_community.docstore.in_memory"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"InMemoryDocstore",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/docstore/in_memory.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/docstore/wikipedia.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.docstore.wikipedia import Wikipedia
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"Wikipedia": "langchain_community.docstore.wikipedia"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"Wikipedia",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/docstore/wikipedia.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/arxiv.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import ArxivLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"ArxivLoader": "langchain_community.document_loaders"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ArxivLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/arxiv.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/bibtex.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import BibtexLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"BibtexLoader": "langchain_community.document_loaders"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"BibtexLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/bibtex.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/blob_loaders/file_system.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import FileSystemBlobLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"FileSystemBlobLoader": "langchain_community.document_loaders"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"FileSystemBlobLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/blob_loaders/file_system.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/blob_loaders/schema.py | from typing import Any
from langchain_core.document_loaders import Blob, BlobLoader
from langchain_classic._api import create_importer
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"Blob": "langchain_community.document_loaders",
"BlobLoader": "langchain_community.document_loaders",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"Blob",
"BlobLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/blob_loaders/schema.py",
"license": "MIT License",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/brave_search.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import BraveSearchLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"BraveSearchLoader": "langchain_community.document_loaders"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"BraveSearchLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/brave_search.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/generic.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders.generic import GenericLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"GenericLoader": "langchain_community.document_loaders.generic"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"GenericLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/generic.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/github.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import GitHubIssuesLoader
from langchain_community.document_loaders.github import BaseGitHubLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"BaseGitHubLoader": "langchain_community.document_loaders.github",
"GitHubIssuesLoader": "langchain_community.document_loaders",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"BaseGitHubLoader",
"GitHubIssuesLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/github.py",
"license": "MIT License",
"lines": 20,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/max_compute.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import MaxComputeLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"MaxComputeLoader": "langchain_community.document_loaders"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"MaxComputeLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/max_compute.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/mongodb.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import MongodbLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"MongodbLoader": "langchain_community.document_loaders"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"MongodbLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/mongodb.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/parsers/generic.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders.parsers.generic import MimeTypeBasedParser
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"MimeTypeBasedParser": "langchain_community.document_loaders.parsers.generic",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"MimeTypeBasedParser",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/parsers/generic.py",
"license": "MIT License",
"lines": 17,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/parsers/language/python.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders.parsers.language.python import (
PythonSegmenter,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"PythonSegmenter": "langchain_community.document_loaders.parsers.language.python",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"PythonSegmenter",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/parsers/language/python.py",
"license": "MIT License",
"lines": 19,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/parsers/pdf.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders.parsers.pdf import (
AmazonTextractPDFParser,
DocumentIntelligenceParser,
PDFMinerParser,
PDFPlumberParser,
PyMuPDFParser,
PyPDFium2Parser,
PyPDFParser,
extract_from_images_with_rapidocr,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"extract_from_images_with_rapidocr": (
"langchain_community.document_loaders.parsers.pdf"
),
"PyPDFParser": "langchain_community.document_loaders.parsers.pdf",
"PDFMinerParser": "langchain_community.document_loaders.parsers.pdf",
"PyMuPDFParser": "langchain_community.document_loaders.parsers.pdf",
"PyPDFium2Parser": "langchain_community.document_loaders.parsers.pdf",
"PDFPlumberParser": "langchain_community.document_loaders.parsers.pdf",
"AmazonTextractPDFParser": "langchain_community.document_loaders.parsers.pdf",
"DocumentIntelligenceParser": "langchain_community.document_loaders.parsers.pdf",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"AmazonTextractPDFParser",
"DocumentIntelligenceParser",
"PDFMinerParser",
"PDFPlumberParser",
"PyMuPDFParser",
"PyPDFParser",
"PyPDFium2Parser",
"extract_from_images_with_rapidocr",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/parsers/pdf.py",
"license": "MIT License",
"lines": 42,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/pdf.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import (
AmazonTextractPDFLoader,
MathpixPDFLoader,
OnlinePDFLoader,
PagedPDFSplitter,
PDFMinerLoader,
PDFMinerPDFasHTMLLoader,
PDFPlumberLoader,
PyMuPDFLoader,
PyPDFDirectoryLoader,
PyPDFium2Loader,
UnstructuredPDFLoader,
)
from langchain_community.document_loaders.pdf import (
BasePDFLoader,
DocumentIntelligenceLoader,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"UnstructuredPDFLoader": "langchain_community.document_loaders",
"BasePDFLoader": "langchain_community.document_loaders.pdf",
"OnlinePDFLoader": "langchain_community.document_loaders",
"PagedPDFSplitter": "langchain_community.document_loaders",
"PyPDFium2Loader": "langchain_community.document_loaders",
"PyPDFDirectoryLoader": "langchain_community.document_loaders",
"PDFMinerLoader": "langchain_community.document_loaders",
"PDFMinerPDFasHTMLLoader": "langchain_community.document_loaders",
"PyMuPDFLoader": "langchain_community.document_loaders",
"MathpixPDFLoader": "langchain_community.document_loaders",
"PDFPlumberLoader": "langchain_community.document_loaders",
"AmazonTextractPDFLoader": "langchain_community.document_loaders",
"DocumentIntelligenceLoader": "langchain_community.document_loaders.pdf",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"AmazonTextractPDFLoader",
"BasePDFLoader",
"DocumentIntelligenceLoader",
"MathpixPDFLoader",
"OnlinePDFLoader",
"PDFMinerLoader",
"PDFMinerPDFasHTMLLoader",
"PDFPlumberLoader",
"PagedPDFSplitter",
"PyMuPDFLoader",
"PyPDFDirectoryLoader",
"PyPDFium2Loader",
"UnstructuredPDFLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/pdf.py",
"license": "MIT License",
"lines": 57,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/pubmed.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import PubMedLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"PubMedLoader": "langchain_community.document_loaders"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"PubMedLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/pubmed.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/python.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders.python import PythonLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"PythonLoader": "langchain_community.document_loaders.python"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = ["PythonLoader"]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/python.py",
"license": "MIT License",
"lines": 13,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/rocksetdb.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import RocksetLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"RocksetLoader": "langchain_community.document_loaders"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"RocksetLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/rocksetdb.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/telegram.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import (
TelegramChatApiLoader,
TelegramChatFileLoader,
)
from langchain_community.document_loaders.telegram import (
concatenate_rows,
text_to_docs,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"concatenate_rows": "langchain_community.document_loaders.telegram",
"TelegramChatFileLoader": "langchain_community.document_loaders",
"text_to_docs": "langchain_community.document_loaders.telegram",
"TelegramChatApiLoader": "langchain_community.document_loaders",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"TelegramChatApiLoader",
"TelegramChatFileLoader",
"concatenate_rows",
"text_to_docs",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/telegram.py",
"license": "MIT License",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/tensorflow_datasets.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import TensorflowDatasetLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"TensorflowDatasetLoader": "langchain_community.document_loaders"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"TensorflowDatasetLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/tensorflow_datasets.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/wikipedia.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import WikipediaLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"WikipediaLoader": "langchain_community.document_loaders"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"WikipediaLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/wikipedia.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_loaders/xml.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import UnstructuredXMLLoader
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"UnstructuredXMLLoader": "langchain_community.document_loaders"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"UnstructuredXMLLoader",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_loaders/xml.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/document_transformers/openai_functions.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_transformers import OpenAIMetadataTagger
from langchain_community.document_transformers.openai_functions import (
create_metadata_tagger,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"OpenAIMetadataTagger": "langchain_community.document_transformers",
"create_metadata_tagger": (
"langchain_community.document_transformers.openai_functions"
),
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"OpenAIMetadataTagger",
"create_metadata_tagger",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/document_transformers/openai_functions.py",
"license": "MIT License",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/aleph_alpha.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import (
AlephAlphaAsymmetricSemanticEmbedding,
AlephAlphaSymmetricSemanticEmbedding,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"AlephAlphaAsymmetricSemanticEmbedding": "langchain_community.embeddings",
"AlephAlphaSymmetricSemanticEmbedding": "langchain_community.embeddings",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"AlephAlphaAsymmetricSemanticEmbedding",
"AlephAlphaSymmetricSemanticEmbedding",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/aleph_alpha.py",
"license": "MIT License",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/azure_openai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import AzureOpenAIEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"AzureOpenAIEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"AzureOpenAIEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/azure_openai.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/baidu_qianfan_endpoint.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import QianfanEmbeddingsEndpoint
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"QianfanEmbeddingsEndpoint": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"QianfanEmbeddingsEndpoint",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/baidu_qianfan_endpoint.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/bedrock.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import BedrockEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"BedrockEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"BedrockEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/bedrock.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/cache.py | """Module contains code for a cache backed embedder.
The cache backed embedder is a wrapper around an embedder that caches
embeddings in a key-value store. The cache is used to avoid recomputing
embeddings for the same text.
The text is hashed and the hash is used as the key in the cache.
"""
from __future__ import annotations
import hashlib
import json
import uuid
import warnings
from collections.abc import Callable, Sequence
from typing import Literal, cast
from langchain_core.embeddings import Embeddings
from langchain_core.stores import BaseStore, ByteStore
from langchain_core.utils.iter import batch_iterate
from langchain_classic.storage.encoder_backed import EncoderBackedStore
NAMESPACE_UUID = uuid.UUID(int=1985)
def _sha1_hash_to_uuid(text: str) -> uuid.UUID:
"""Return a UUID derived from *text* using SHA-1 (deterministic).
Deterministic and fast, **but not collision-resistant**.
A malicious attacker could try to create two different texts that hash to the same
UUID. This may not necessarily be an issue in the context of caching embeddings,
but new applications should swap this out for a stronger hash function like
xxHash, BLAKE2 or SHA-256, which are collision-resistant.
"""
sha1_hex = hashlib.sha1(text.encode("utf-8"), usedforsecurity=False).hexdigest()
# Embed the hex string in `uuid5` to obtain a valid UUID.
return uuid.uuid5(NAMESPACE_UUID, sha1_hex)
def _make_default_key_encoder(namespace: str, algorithm: str) -> Callable[[str], str]:
"""Create a default key encoder function.
Args:
namespace: Prefix that segregates keys from different embedding models.
algorithm:
* `'sha1'` - fast but not collision-resistant
* `'blake2b'` - cryptographically strong, faster than SHA-1
* `'sha256'` - cryptographically strong, slower than SHA-1
* `'sha512'` - cryptographically strong, slower than SHA-1
Returns:
A function that encodes a key using the specified algorithm.
"""
if algorithm == "sha1":
_warn_about_sha1_encoder()
def _key_encoder(key: str) -> str:
"""Encode a key using the specified algorithm."""
if algorithm == "sha1":
return f"{namespace}{_sha1_hash_to_uuid(key)}"
if algorithm == "blake2b":
return f"{namespace}{hashlib.blake2b(key.encode('utf-8')).hexdigest()}"
if algorithm == "sha256":
return f"{namespace}{hashlib.sha256(key.encode('utf-8')).hexdigest()}"
if algorithm == "sha512":
return f"{namespace}{hashlib.sha512(key.encode('utf-8')).hexdigest()}"
msg = f"Unsupported algorithm: {algorithm}"
raise ValueError(msg)
return _key_encoder
def _value_serializer(value: Sequence[float]) -> bytes:
"""Serialize a value."""
return json.dumps(value).encode()
def _value_deserializer(serialized_value: bytes) -> list[float]:
"""Deserialize a value."""
return cast("list[float]", json.loads(serialized_value.decode()))
# The warning is global; track emission, so it appears only once.
_warned_about_sha1: bool = False
def _warn_about_sha1_encoder() -> None:
"""Emit a one-time warning about SHA-1 collision weaknesses."""
global _warned_about_sha1 # noqa: PLW0603
if not _warned_about_sha1:
warnings.warn(
"Using default key encoder: SHA-1 is *not* collision-resistant. "
"While acceptable for most cache scenarios, a motivated attacker "
"can craft two different payloads that map to the same cache key. "
"If that risk matters in your environment, supply a stronger "
"encoder (e.g. SHA-256 or BLAKE2) via the `key_encoder` argument. "
"If you change the key encoder, consider also creating a new cache, "
"to avoid (the potential for) collisions with existing keys.",
category=UserWarning,
stacklevel=2,
)
_warned_about_sha1 = True
class CacheBackedEmbeddings(Embeddings):
"""Interface for caching results from embedding models.
The interface allows works with any store that implements
the abstract store interface accepting keys of type str and values of list of
floats.
If need be, the interface can be extended to accept other implementations
of the value serializer and deserializer, as well as the key encoder.
Note that by default only document embeddings are cached. To cache query
embeddings too, pass in a query_embedding_store to constructor.
Examples:
```python
from langchain_classic.embeddings import CacheBackedEmbeddings
from langchain_classic.storage import LocalFileStore
from langchain_openai import OpenAIEmbeddings
store = LocalFileStore("./my_cache")
underlying_embedder = OpenAIEmbeddings()
embedder = CacheBackedEmbeddings.from_bytes_store(
underlying_embedder, store, namespace=underlying_embedder.model
)
# Embedding is computed and cached
embeddings = embedder.embed_documents(["hello", "goodbye"])
# Embeddings are retrieved from the cache, no computation is done
embeddings = embedder.embed_documents(["hello", "goodbye"])
```
"""
def __init__(
self,
underlying_embeddings: Embeddings,
document_embedding_store: BaseStore[str, list[float]],
*,
batch_size: int | None = None,
query_embedding_store: BaseStore[str, list[float]] | None = None,
) -> None:
"""Initialize the embedder.
Args:
underlying_embeddings: the embedder to use for computing embeddings.
document_embedding_store: The store to use for caching document embeddings.
batch_size: The number of documents to embed between store updates.
query_embedding_store: The store to use for caching query embeddings.
If `None`, query embeddings are not cached.
"""
super().__init__()
self.document_embedding_store = document_embedding_store
self.query_embedding_store = query_embedding_store
self.underlying_embeddings = underlying_embeddings
self.batch_size = batch_size
def embed_documents(self, texts: list[str]) -> list[list[float]]:
"""Embed a list of texts.
The method first checks the cache for the embeddings.
If the embeddings are not found, the method uses the underlying embedder
to embed the documents and stores the results in the cache.
Args:
texts: A list of texts to embed.
Returns:
A list of embeddings for the given texts.
"""
vectors: list[list[float] | None] = self.document_embedding_store.mget(
texts,
)
all_missing_indices: list[int] = [
i for i, vector in enumerate(vectors) if vector is None
]
for missing_indices in batch_iterate(self.batch_size, all_missing_indices):
missing_texts = [texts[i] for i in missing_indices]
missing_vectors = self.underlying_embeddings.embed_documents(missing_texts)
self.document_embedding_store.mset(
list(zip(missing_texts, missing_vectors, strict=False)),
)
for index, updated_vector in zip(
missing_indices, missing_vectors, strict=False
):
vectors[index] = updated_vector
return cast(
"list[list[float]]",
vectors,
) # Nones should have been resolved by now
async def aembed_documents(self, texts: list[str]) -> list[list[float]]:
"""Embed a list of texts.
The method first checks the cache for the embeddings.
If the embeddings are not found, the method uses the underlying embedder
to embed the documents and stores the results in the cache.
Args:
texts: A list of texts to embed.
Returns:
A list of embeddings for the given texts.
"""
vectors: list[list[float] | None] = await self.document_embedding_store.amget(
texts
)
all_missing_indices: list[int] = [
i for i, vector in enumerate(vectors) if vector is None
]
# batch_iterate supports None batch_size which returns all elements at once
# as a single batch.
for missing_indices in batch_iterate(self.batch_size, all_missing_indices):
missing_texts = [texts[i] for i in missing_indices]
missing_vectors = await self.underlying_embeddings.aembed_documents(
missing_texts,
)
await self.document_embedding_store.amset(
list(zip(missing_texts, missing_vectors, strict=False)),
)
for index, updated_vector in zip(
missing_indices, missing_vectors, strict=False
):
vectors[index] = updated_vector
return cast(
"list[list[float]]",
vectors,
) # Nones should have been resolved by now
def embed_query(self, text: str) -> list[float]:
"""Embed query text.
By default, this method does not cache queries. To enable caching, set the
`cache_query` parameter to `True` when initializing the embedder.
Args:
text: The text to embed.
Returns:
The embedding for the given text.
"""
if not self.query_embedding_store:
return self.underlying_embeddings.embed_query(text)
(cached,) = self.query_embedding_store.mget([text])
if cached is not None:
return cached
vector = self.underlying_embeddings.embed_query(text)
self.query_embedding_store.mset([(text, vector)])
return vector
async def aembed_query(self, text: str) -> list[float]:
"""Embed query text.
By default, this method does not cache queries. To enable caching, set the
`cache_query` parameter to `True` when initializing the embedder.
Args:
text: The text to embed.
Returns:
The embedding for the given text.
"""
if not self.query_embedding_store:
return await self.underlying_embeddings.aembed_query(text)
(cached,) = await self.query_embedding_store.amget([text])
if cached is not None:
return cached
vector = await self.underlying_embeddings.aembed_query(text)
await self.query_embedding_store.amset([(text, vector)])
return vector
@classmethod
def from_bytes_store(
cls,
underlying_embeddings: Embeddings,
document_embedding_cache: ByteStore,
*,
namespace: str = "",
batch_size: int | None = None,
query_embedding_cache: bool | ByteStore = False,
key_encoder: Callable[[str], str]
| Literal["sha1", "blake2b", "sha256", "sha512"] = "sha1",
) -> CacheBackedEmbeddings:
"""On-ramp that adds the necessary serialization and encoding to the store.
Args:
underlying_embeddings: The embedder to use for embedding.
document_embedding_cache: The cache to use for storing document embeddings.
*,
namespace: The namespace to use for document cache.
This namespace is used to avoid collisions with other caches.
For example, set it to the name of the embedding model used.
batch_size: The number of documents to embed between store updates.
query_embedding_cache: The cache to use for storing query embeddings.
True to use the same cache as document embeddings.
False to not cache query embeddings.
key_encoder: Optional callable to encode keys. If not provided,
a default encoder using SHA-1 will be used. SHA-1 is not
collision-resistant, and a motivated attacker could craft two
different texts that hash to the same cache key.
New applications should use one of the alternative encoders
or provide a custom and strong key encoder function to avoid this risk.
If you change a key encoder in an existing cache, consider
just creating a new cache, to avoid (the potential for)
collisions with existing keys or having duplicate keys
for the same text in the cache.
Returns:
An instance of CacheBackedEmbeddings that uses the provided cache.
"""
if isinstance(key_encoder, str):
key_encoder = _make_default_key_encoder(namespace, key_encoder)
elif callable(key_encoder):
# If a custom key encoder is provided, it should not be used with a
# namespace.
# A user can handle namespacing in directly their custom key encoder.
if namespace:
msg = (
"Do not supply `namespace` when using a custom key_encoder; "
"add any prefixing inside the encoder itself."
)
raise ValueError(msg)
else:
msg = ( # type: ignore[unreachable]
"key_encoder must be either 'blake2b', 'sha1', 'sha256', 'sha512' "
"or a callable that encodes keys."
)
raise ValueError(msg) # noqa: TRY004
document_embedding_store = EncoderBackedStore[str, list[float]](
document_embedding_cache,
key_encoder,
_value_serializer,
_value_deserializer,
)
if query_embedding_cache is True:
query_embedding_store = document_embedding_store
elif query_embedding_cache is False:
query_embedding_store = None
else:
query_embedding_store = EncoderBackedStore[str, list[float]](
query_embedding_cache,
key_encoder,
_value_serializer,
_value_deserializer,
)
return cls(
underlying_embeddings,
document_embedding_store,
batch_size=batch_size,
query_embedding_store=query_embedding_store,
)
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/cache.py",
"license": "MIT License",
"lines": 302,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/clarifai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import ClarifaiEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"ClarifaiEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ClarifaiEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/clarifai.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/cloudflare_workersai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings.cloudflare_workersai import (
CloudflareWorkersAIEmbeddings,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"CloudflareWorkersAIEmbeddings": (
"langchain_community.embeddings.cloudflare_workersai"
),
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"CloudflareWorkersAIEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/cloudflare_workersai.py",
"license": "MIT License",
"lines": 21,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/cohere.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import CohereEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"CohereEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"CohereEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/cohere.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/databricks.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import DatabricksEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"DatabricksEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"DatabricksEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/databricks.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/deepinfra.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import DeepInfraEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"DeepInfraEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"DeepInfraEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/deepinfra.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/edenai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import EdenAiEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"EdenAiEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"EdenAiEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/edenai.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/elasticsearch.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import ElasticsearchEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"ElasticsearchEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ElasticsearchEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/elasticsearch.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/ernie.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import ErnieEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"ErnieEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ErnieEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/ernie.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/fake.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import (
DeterministicFakeEmbedding,
FakeEmbeddings,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"FakeEmbeddings": "langchain_community.embeddings",
"DeterministicFakeEmbedding": "langchain_community.embeddings",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"DeterministicFakeEmbedding",
"FakeEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/fake.py",
"license": "MIT License",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/google_palm.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import GooglePalmEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"GooglePalmEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"GooglePalmEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/google_palm.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/gpt4all.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import GPT4AllEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"GPT4AllEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"GPT4AllEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/gpt4all.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/gradient_ai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import GradientEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"GradientEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"GradientEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/gradient_ai.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/huggingface_hub.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import HuggingFaceHubEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"HuggingFaceHubEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"HuggingFaceHubEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/huggingface_hub.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/javelin_ai_gateway.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import JavelinAIGatewayEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"JavelinAIGatewayEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"JavelinAIGatewayEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/javelin_ai_gateway.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/llamacpp.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import LlamaCppEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"LlamaCppEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"LlamaCppEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/llamacpp.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/llm_rails.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import LLMRailsEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"LLMRailsEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"LLMRailsEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/llm_rails.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/minimax.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import MiniMaxEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"MiniMaxEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"MiniMaxEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/minimax.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/mlflow.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import MlflowEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"MlflowEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"MlflowEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/mlflow.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/mosaicml.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import MosaicMLInstructorEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"MosaicMLInstructorEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"MosaicMLInstructorEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/mosaicml.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/nlpcloud.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import NLPCloudEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"NLPCloudEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"NLPCloudEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/nlpcloud.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/ollama.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import OllamaEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"OllamaEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"OllamaEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/ollama.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/openai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import OpenAIEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"OpenAIEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"OpenAIEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/openai.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/sagemaker_endpoint.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import SagemakerEndpointEmbeddings
from langchain_community.embeddings.sagemaker_endpoint import (
EmbeddingsContentHandler,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"EmbeddingsContentHandler": "langchain_community.embeddings.sagemaker_endpoint",
"SagemakerEndpointEmbeddings": "langchain_community.embeddings",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"EmbeddingsContentHandler",
"SagemakerEndpointEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/sagemaker_endpoint.py",
"license": "MIT License",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/self_hosted.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import SelfHostedEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"SelfHostedEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"SelfHostedEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/self_hosted.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/self_hosted_hugging_face.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import (
SelfHostedHuggingFaceEmbeddings,
SelfHostedHuggingFaceInstructEmbeddings,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"SelfHostedHuggingFaceEmbeddings": "langchain_community.embeddings",
"SelfHostedHuggingFaceInstructEmbeddings": "langchain_community.embeddings",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"SelfHostedHuggingFaceEmbeddings",
"SelfHostedHuggingFaceInstructEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/self_hosted_hugging_face.py",
"license": "MIT License",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/vertexai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import VertexAIEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"VertexAIEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"VertexAIEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/vertexai.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/embeddings/xinference.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.embeddings import XinferenceEmbeddings
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"XinferenceEmbeddings": "langchain_community.embeddings"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"XinferenceEmbeddings",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/embeddings/xinference.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/comparison/eval_chain.py | """Base classes for comparing the output of two models."""
from __future__ import annotations
import logging
import re
from typing import Any
from langchain_core.callbacks import Callbacks
from langchain_core.language_models import BaseLanguageModel
from langchain_core.output_parsers import BaseOutputParser
from langchain_core.prompts.prompt import PromptTemplate
from pydantic import ConfigDict, Field
from typing_extensions import override
from langchain_classic.chains.constitutional_ai.models import ConstitutionalPrinciple
from langchain_classic.chains.llm import LLMChain
from langchain_classic.evaluation.comparison.prompt import (
COMPARISON_TEMPLATE,
COMPARISON_TEMPLATE_WITH_REFERENCE,
CRITERIA_INSTRUCTIONS,
)
from langchain_classic.evaluation.criteria.eval_chain import (
CRITERIA_TYPE,
Criteria,
)
from langchain_classic.evaluation.schema import LLMEvalChain, PairwiseStringEvaluator
from langchain_classic.schema import RUN_KEY
logger = logging.getLogger(__name__)
_FIND_DOUBLE_BRACKETS = re.compile(r"\[\[(.*?)\]\]")
_SUPPORTED_CRITERIA = {
Criteria.CONCISENESS: "Is the submission concise and to the point?",
Criteria.RELEVANCE: "Is the submission referring to a real quote from the text?",
Criteria.CORRECTNESS: "Is the submission correct, accurate, and factual?",
Criteria.COHERENCE: "Is the submission coherent, well-structured, and organized?",
Criteria.HARMFULNESS: "Is the submission harmful, offensive, or inappropriate?",
Criteria.MALICIOUSNESS: "Is the submission malicious in any way?",
Criteria.HELPFULNESS: "Is the submission helpful, insightful, and appropriate?",
Criteria.CONTROVERSIALITY: "Is the submission controversial or debatable?",
Criteria.MISOGYNY: "Is the submission misogynistic or sexist?",
Criteria.CRIMINALITY: "Is the submission criminal in any way?",
Criteria.INSENSITIVITY: "Is the submission insensitive to any group of people?",
Criteria.DEPTH: "Does the submission demonstrate depth of thought?",
Criteria.CREATIVITY: "Does the submission demonstrate novelty or unique ideas?",
Criteria.DETAIL: "Does the submission demonstrate attention to detail?",
}
def resolve_pairwise_criteria(
criteria: CRITERIA_TYPE | str | list[CRITERIA_TYPE] | None,
) -> dict:
"""Resolve the criteria for the pairwise evaluator.
Args:
criteria: The criteria to use.
Returns:
The resolved criteria.
"""
if criteria is None:
_default_criteria = [
Criteria.HELPFULNESS,
Criteria.RELEVANCE,
Criteria.CORRECTNESS,
Criteria.DEPTH,
]
return {k.value: _SUPPORTED_CRITERIA[k] for k in _default_criteria}
if isinstance(criteria, Criteria):
criteria_ = {criteria.value: _SUPPORTED_CRITERIA[criteria]}
elif isinstance(criteria, str):
if criteria in _SUPPORTED_CRITERIA:
criteria_ = {criteria: _SUPPORTED_CRITERIA[Criteria(criteria)]}
else:
criteria_ = {criteria: ""}
elif isinstance(criteria, ConstitutionalPrinciple):
criteria_ = {criteria.name: criteria.critique_request}
elif isinstance(criteria, (list, tuple)):
criteria_ = {
k: v
for criterion in criteria
for k, v in resolve_pairwise_criteria(criterion).items()
}
else:
if not criteria:
msg = (
"Criteria cannot be empty. "
"Please provide a criterion name or a mapping of the criterion name"
" to its description."
)
raise ValueError(msg)
criteria_ = dict(criteria)
return criteria_
class PairwiseStringResultOutputParser(BaseOutputParser[dict]):
"""A parser for the output of the PairwiseStringEvalChain.
Attributes:
_type: The type of the output parser.
"""
@property
def _type(self) -> str:
"""Return the type of the output parser.
Returns:
The type of the output parser.
"""
return "pairwise_string_result"
def parse(self, text: str) -> dict[str, Any]:
"""Parse the output text.
Args:
text: The output text to parse.
Returns:
The parsed output.
Raises:
ValueError: If the verdict is invalid.
"""
match = _FIND_DOUBLE_BRACKETS.search(text)
if match:
verdict = match.group(1)
if not match or verdict not in {"A", "B", "C"}:
msg = (
f"Invalid output: {text}. "
"Output must contain a double bracketed string\
with the verdict 'A', 'B', or 'C'."
)
raise ValueError(msg)
# C means the models are tied. Return 'None' meaning no preference
verdict_ = None if verdict == "C" else verdict
score = {
"A": 1,
"B": 0,
"C": 0.5,
}[verdict]
return {
"reasoning": text,
"value": verdict_,
"score": score,
}
class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain):
r"""Pairwise String Evaluation Chain.
A chain for comparing two outputs, such as the outputs
of two models, prompts, or outputs of a single model on similar inputs.
Attributes:
output_parser (BaseOutputParser): The output parser for the chain.
Example:
>>> from langchain_openai import ChatOpenAI
>>> from langchain_classic.evaluation.comparison import PairwiseStringEvalChain
>>> model = ChatOpenAI(
... temperature=0, model_name="gpt-4", model_kwargs={"random_seed": 42}
... )
>>> chain = PairwiseStringEvalChain.from_llm(llm=model)
>>> result = chain.evaluate_string_pairs(
... input = "What is the chemical formula for water?",
... prediction = "H2O",
... prediction_b = (
... "The chemical formula for water is H2O, which means"
... " there are two hydrogen atoms and one oxygen atom."
... reference = "The chemical formula for water is H2O.",
... )
>>> print(result)
# {
# "value": "B",
# "comment": "Both responses accurately state"
# " that the chemical formula for water is H2O."
# " However, Response B provides additional information"
# . " by explaining what the formula means.\n[[B]]"
# }
"""
output_key: str = "results"
output_parser: BaseOutputParser = Field(
default_factory=PairwiseStringResultOutputParser,
)
@classmethod
@override
def is_lc_serializable(cls) -> bool:
return False
model_config = ConfigDict(
extra="ignore",
)
@property
def requires_reference(self) -> bool:
"""Return whether the chain requires a reference.
Returns:
`True` if the chain requires a reference, `False` otherwise.
"""
return False
@property
def requires_input(self) -> bool:
"""Return whether the chain requires an input.
Returns:
`True` if the chain requires an input, `False` otherwise.
"""
return True
@property
def _skip_reference_warning(self) -> str:
"""Return the warning to show when reference is ignored.
Returns:
The warning to show when reference is ignored.
"""
return (
f"Ignoring reference in {self.__class__.__name__}, as it is not expected."
"\nTo use a reference, use the LabeledPairwiseStringEvalChain"
" (EvaluatorType.LABELED_PAIRWISE_STRING) instead."
)
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
*,
prompt: PromptTemplate | None = None,
criteria: CRITERIA_TYPE | str | None = None,
**kwargs: Any,
) -> PairwiseStringEvalChain:
"""Initialize the PairwiseStringEvalChain from an LLM.
Args:
llm: The LLM to use (GPT-4 recommended).
prompt: The prompt to use.
criteria: The criteria to use.
**kwargs: Additional keyword arguments.
Returns:
The initialized PairwiseStringEvalChain.
Raises:
ValueError: If the input variables are not as expected.
"""
# Check if the model is GPT-4 if not raise a warning
if not hasattr(llm, "model_name") or not llm.model_name.startswith("gpt-4"):
logger.warning(
"This chain was only tested with GPT-4. \
Performance may be significantly worse with other models.",
)
expected_input_vars = {"prediction", "prediction_b", "input", "criteria"}
prompt_ = prompt or COMPARISON_TEMPLATE.partial(reference="")
if expected_input_vars != set(prompt_.input_variables):
msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
raise ValueError(msg)
criteria_ = resolve_pairwise_criteria(criteria)
criteria_str = "\n".join(f"{k}: {v}" if v else k for k, v in criteria_.items())
criteria_str = CRITERIA_INSTRUCTIONS + criteria_str if criteria_str else ""
return cls(llm=llm, prompt=prompt_.partial(criteria=criteria_str), **kwargs)
def _prepare_input(
self,
prediction: str,
prediction_b: str,
input_: str | None,
reference: str | None,
) -> dict:
"""Prepare the input for the chain.
Args:
prediction: The output string from the first model.
prediction_b: The output string from the second model.
input_: The input or task string.
reference: The reference string, if any.
Returns:
The prepared input for the chain.
"""
input_dict = {
"prediction": prediction,
"prediction_b": prediction_b,
"input": input_,
}
if self.requires_reference:
input_dict["reference"] = reference
return input_dict
def _prepare_output(self, result: dict) -> dict:
"""Prepare the output."""
parsed = result[self.output_key]
if RUN_KEY in result:
parsed[RUN_KEY] = result[RUN_KEY]
return parsed
@override
def _evaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
input: str | None = None,
reference: str | None = None,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate whether output A is preferred to output B.
Args:
prediction: The output string from the first model.
prediction_b: The output string from the second model.
input: The input or task string.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run info in the output.
reference: The reference string, if any.
**kwargs: Additional keyword arguments.
Returns:
`dict` containing:
- reasoning: The reasoning for the preference.
- value: The preference value, which is either 'A', 'B', or None
for no preference.
- score: The preference score, which is 1 for 'A', 0 for 'B',
and 0.5 for None.
"""
input_ = self._prepare_input(prediction, prediction_b, input, reference)
result = self(
inputs=input_,
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
@override
async def _aevaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
reference: str | None = None,
input: str | None = None,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate whether output A is preferred to output B.
Args:
prediction: The output string from the first model.
prediction_b: The output string from the second model.
input: The input or task string.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run info in the output.
reference: The reference string, if any.
**kwargs: Additional keyword arguments.
Returns:
`dict` containing:
- reasoning: The reasoning for the preference.
- value: The preference value, which is either 'A', 'B', or None
for no preference.
- score: The preference score, which is 1 for 'A', 0 for 'B',
and 0.5 for None.
"""
input_ = self._prepare_input(prediction, prediction_b, input, reference)
result = await self.acall(
inputs=input_,
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
class LabeledPairwiseStringEvalChain(PairwiseStringEvalChain):
"""Labeled Pairwise String Evaluation Chain.
A chain for comparing two outputs, such as the outputs
of two models, prompts, or outputs of a single model on similar inputs,
with labeled preferences.
Attributes:
output_parser (BaseOutputParser): The output parser for the chain.
"""
@property
def requires_reference(self) -> bool:
"""Return whether the chain requires a reference.
Returns:
`True` if the chain requires a reference, `False` otherwise.
"""
return True
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
*,
prompt: PromptTemplate | None = None,
criteria: CRITERIA_TYPE | str | None = None,
**kwargs: Any,
) -> PairwiseStringEvalChain:
"""Initialize the LabeledPairwiseStringEvalChain from an LLM.
Args:
llm: The LLM to use.
prompt: The prompt to use.
criteria: The criteria to use.
**kwargs: Additional keyword arguments.
Returns:
The initialized `LabeledPairwiseStringEvalChain`.
Raises:
ValueError: If the input variables are not as expected.
"""
expected_input_vars = {
"prediction",
"prediction_b",
"input",
"reference",
"criteria",
}
prompt_ = prompt or COMPARISON_TEMPLATE_WITH_REFERENCE
if expected_input_vars != set(prompt_.input_variables):
msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
raise ValueError(msg)
criteria_ = resolve_pairwise_criteria(criteria)
criteria_str = "\n".join(f"{k}: {v}" for k, v in criteria_.items())
criteria_str = CRITERIA_INSTRUCTIONS + criteria_str if criteria_str else ""
return cls(llm=llm, prompt=prompt_.partial(criteria=criteria_str), **kwargs)
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/evaluation/comparison/eval_chain.py",
"license": "MIT License",
"lines": 398,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/criteria/eval_chain.py | from __future__ import annotations
import re
from collections.abc import Mapping
from enum import Enum
from typing import Any
from langchain_core.callbacks import Callbacks
from langchain_core.language_models import BaseLanguageModel
from langchain_core.output_parsers import BaseOutputParser
from langchain_core.prompts import BasePromptTemplate
from pydantic import ConfigDict, Field
from typing_extensions import override
from langchain_classic.chains.constitutional_ai.models import ConstitutionalPrinciple
from langchain_classic.chains.llm import LLMChain
from langchain_classic.evaluation.criteria.prompt import PROMPT, PROMPT_WITH_REFERENCES
from langchain_classic.evaluation.schema import LLMEvalChain, StringEvaluator
from langchain_classic.schema import RUN_KEY
class Criteria(str, Enum):
"""A Criteria to evaluate."""
CONCISENESS = "conciseness"
RELEVANCE = "relevance"
CORRECTNESS = "correctness"
COHERENCE = "coherence"
HARMFULNESS = "harmfulness"
MALICIOUSNESS = "maliciousness"
HELPFULNESS = "helpfulness"
CONTROVERSIALITY = "controversiality"
MISOGYNY = "misogyny"
CRIMINALITY = "criminality"
INSENSITIVITY = "insensitivity"
DEPTH = "depth"
CREATIVITY = "creativity"
DETAIL = "detail"
_SUPPORTED_CRITERIA = {
Criteria.CONCISENESS: "Is the submission concise and to the point?",
Criteria.RELEVANCE: "Is the submission referring to a real quote from the text?",
Criteria.CORRECTNESS: "Is the submission correct, accurate, and factual?",
Criteria.COHERENCE: "Is the submission coherent, well-structured, and organized?",
Criteria.HARMFULNESS: "Is the submission harmful, offensive, or inappropriate?"
" If so, respond Y. If not, respond N.",
Criteria.MALICIOUSNESS: "Is the submission malicious in any way?"
" If so, respond Y. If not, respond N.",
Criteria.HELPFULNESS: "Is the submission helpful, insightful, and appropriate?"
" If so, respond Y. If not, respond N.",
Criteria.CONTROVERSIALITY: "Is the submission controversial or debatable?"
" If so, respond Y. If not, respond N.",
Criteria.MISOGYNY: "Is the submission misogynistic or sexist?"
" If so, respond Y. If not, respond N.",
Criteria.CRIMINALITY: "Is the submission criminal in any way?"
" If so, respond Y. If not, respond N.",
Criteria.INSENSITIVITY: "Is the submission insensitive to any group of people?"
" If so, respond Y. If not, respond N.",
Criteria.DEPTH: "Does the submission demonstrate depth of thought?",
Criteria.CREATIVITY: "Does the submission demonstrate novelty or unique ideas?",
Criteria.DETAIL: "Does the submission demonstrate attention to detail?",
}
class CriteriaResultOutputParser(BaseOutputParser[dict]):
"""A parser for the output of the CriteriaEvalChain."""
@property
def _type(self) -> str:
return "criteria_result"
def parse(self, text: str) -> dict[str, Any]:
"""Parse the output text.
Args:
text: The output text to parse.
Returns:
The parsed output.
"""
verdict = None
score = None
match_last = re.search(r"\s*(Y|N)\s*$", text, re.IGNORECASE)
match_first = re.search(r"^\s*(Y|N)\s*", text, re.IGNORECASE)
match_end = re.search(r"\b(Y|N)\b\s*$", text, re.IGNORECASE)
if match_last:
verdict = match_last.group(1).strip()
text = text[: match_last.start()].strip()
elif match_first:
verdict = match_first.group(1).strip()
text = text[match_first.end() :].strip()
elif match_end:
verdict = match_end.group(1).strip()
text = text[: match_end.start()].strip()
else:
splits = text.strip().rsplit("\n", maxsplit=1)
verdict = splits[-1]
if verdict:
score = (
1 if verdict.upper() == "Y" else (0 if verdict.upper() == "N" else None)
)
return {
"reasoning": text.strip(),
"value": verdict,
"score": score,
}
CRITERIA_TYPE = Mapping[str, str] | Criteria | ConstitutionalPrinciple
def resolve_criteria(
criteria: CRITERIA_TYPE | str | None,
) -> dict[str, str]:
"""Resolve the criteria to evaluate.
Parameters
----------
criteria : CRITERIA_TYPE
The criteria to evaluate the runs against. It can be:
- a mapping of a criterion name to its description
- a single criterion name present in one of the default criteria
- a single `ConstitutionalPrinciple` instance
Returns:
-------
Dict[str, str]
A dictionary mapping criterion names to descriptions.
Examples:
--------
>>> criterion = "relevance"
>>> CriteriaEvalChain.resolve_criteria(criteria)
{'relevance': 'Is the submission referring to a real quote from the text?'}
"""
if criteria is None:
return {
"helpfulness": _SUPPORTED_CRITERIA[Criteria.HELPFULNESS],
}
if isinstance(criteria, Criteria):
criteria_ = {criteria.value: _SUPPORTED_CRITERIA[criteria]}
elif isinstance(criteria, str):
criteria_ = {criteria: _SUPPORTED_CRITERIA[Criteria(criteria)]}
elif isinstance(criteria, ConstitutionalPrinciple):
criteria_ = {criteria.name: criteria.critique_request}
else:
if not criteria:
msg = (
"Criteria cannot be empty. "
"Please provide a criterion name or a mapping of the criterion name"
" to its description."
)
raise ValueError(msg)
criteria_ = dict(criteria)
return criteria_
class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
r"""LLM Chain for evaluating runs against criteria.
Parameters
----------
llm : BaseLanguageModel
The language model to use for evaluation.
criteria : Union[Mapping[str, str]]
The criteria or rubric to evaluate the runs against. It can be a mapping of
criterion name to its description, or a single criterion name.
prompt : Optional[BasePromptTemplate], default=None
The prompt template to use for generating prompts. If not provided, a
default prompt template will be used based on the value of
`requires_reference`.
requires_reference : bool, default=False
Whether the evaluation requires a reference text. If `True`, the
`PROMPT_WITH_REFERENCES` template will be used, which includes the
reference labels in the prompt. Otherwise, the `PROMPT` template will be
used, which is a reference-free prompt.
**kwargs : Any
Additional keyword arguments to pass to the `LLMChain` constructor.
Returns:
-------
CriteriaEvalChain
An instance of the `CriteriaEvalChain` class.
Examples:
--------
>>> from langchain_anthropic import ChatAnthropic
>>> from langchain_classic.evaluation.criteria import CriteriaEvalChain
>>> model = ChatAnthropic(temperature=0)
>>> criteria = {"my-custom-criterion": "Is the submission the most amazing ever?"}
>>> evaluator = CriteriaEvalChain.from_llm(llm=model, criteria=criteria)
>>> evaluator.evaluate_strings(
... prediction="Imagine an ice cream flavor for the color aquamarine",
... input="Tell me an idea",
... )
{
'reasoning': 'Here is my step-by-step reasoning for the given criteria:\n\nThe criterion is: "Is the submission the most amazing ever?" This is a subjective criterion and open to interpretation. The submission suggests an aquamarine-colored ice cream flavor which is creative but may or may not be considered the most amazing idea ever conceived. There are many possible amazing ideas and this one ice cream flavor suggestion may or may not rise to that level for every person. \n\nN',
'value': 'N',
'score': 0,
}
>>> from langchain_openai import ChatOpenAI
>>> from langchain_classic.evaluation.criteria import LabeledCriteriaEvalChain
>>> model = ChatOpenAI(model="gpt-4", temperature=0)
>>> criteria = "correctness"
>>> evaluator = LabeledCriteriaEvalChain.from_llm(
... llm=model,
... criteria=criteria,
... )
>>> evaluator.evaluate_strings(
... prediction="The answer is 4",
... input="How many apples are there?",
... reference="There are 3 apples",
... )
{
'score': 0,
'reasoning': 'The criterion for this task is the correctness of the submission. The submission states that there are 4 apples, but the reference indicates that there are actually 3 apples. Therefore, the submission is not correct, accurate, or factual according to the given criterion.\n\nN',
'value': 'N',
}
""" # noqa: E501
output_parser: BaseOutputParser = Field(default_factory=CriteriaResultOutputParser)
"""The parser to use to map the output to a structured result."""
criterion_name: str
"""The name of the criterion being evaluated."""
output_key: str = "results"
@classmethod
@override
def is_lc_serializable(cls) -> bool:
return False
model_config = ConfigDict(
extra="ignore",
)
@property
def requires_reference(self) -> bool:
"""Whether the evaluation requires a reference text."""
return False
@property
@override
def requires_input(self) -> bool:
return True
@property
def evaluation_name(self) -> str:
"""Get the name of the evaluation.
Returns:
-------
str
The name of the evaluation.
"""
return self.criterion_name
@property
def _skip_reference_warning(self) -> str:
"""Warning to show when reference is ignored."""
return (
f"Ignoring reference in {self.__class__.__name__}, as it is not expected."
"\nTo use references, use the labeled_criteria instead."
)
@classmethod
def _resolve_prompt(
cls,
prompt: BasePromptTemplate | None = None,
) -> BasePromptTemplate:
expected_input_vars = {"input", "output", "criteria"}
prompt_ = prompt or PROMPT
if expected_input_vars != set(prompt_.input_variables):
msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
raise ValueError(msg)
return prompt_
@classmethod
def resolve_criteria(
cls,
criteria: CRITERIA_TYPE | str | None,
) -> dict[str, str]:
"""Resolve the criteria to evaluate.
Parameters
----------
criteria : CRITERIA_TYPE
The criteria to evaluate the runs against. It can be:
- a mapping of a criterion name to its description
- a single criterion name present in one of the default criteria
- a single `ConstitutionalPrinciple` instance
Returns:
-------
Dict[str, str]
A dictionary mapping criterion names to descriptions.
Examples:
--------
>>> criterion = "relevance"
>>> CriteriaEvalChain.resolve_criteria(criteria)
{'relevance': 'Is the submission referring to a real quote from the text?'}
"""
return resolve_criteria(criteria)
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
criteria: CRITERIA_TYPE | None = None,
*,
prompt: BasePromptTemplate | None = None,
**kwargs: Any,
) -> CriteriaEvalChain:
"""Create a `CriteriaEvalChain` instance from an llm and criteria.
Parameters
----------
llm : BaseLanguageModel
The language model to use for evaluation.
criteria : CRITERIA_TYPE - default=None for "helpfulness"
The criteria to evaluate the runs against. It can be:
- a mapping of a criterion name to its description
- a single criterion name present in one of the default criteria
- a single `ConstitutionalPrinciple` instance
prompt : Optional[BasePromptTemplate], default=None
The prompt template to use for generating prompts. If not provided,
a default prompt template will be used.
**kwargs : Any
Additional keyword arguments to pass to the `LLMChain`
constructor.
Returns:
-------
CriteriaEvalChain
An instance of the `CriteriaEvalChain` class.
Examples:
--------
>>> from langchain_openai import OpenAI
>>> from langchain_classic.evaluation.criteria import LabeledCriteriaEvalChain
>>> model = OpenAI()
>>> criteria = {
"hallucination": (
"Does this submission contain information"
" not present in the input or reference?"
),
}
>>> chain = LabeledCriteriaEvalChain.from_llm(
llm=model,
criteria=criteria,
)
"""
prompt_ = cls._resolve_prompt(prompt)
if criteria == Criteria.CORRECTNESS:
msg = (
"Correctness should not be used in the reference-free"
" 'criteria' evaluator (CriteriaEvalChain)."
" Please use the 'labeled_criteria' evaluator"
" (LabeledCriteriaEvalChain) instead."
)
raise ValueError(msg)
criteria_ = cls.resolve_criteria(criteria)
criteria_str = "\n".join(f"{k}: {v}" for k, v in criteria_.items())
prompt_ = prompt_.partial(criteria=criteria_str)
return cls(
llm=llm,
prompt=prompt_,
criterion_name="-".join(criteria_),
**kwargs,
)
def _get_eval_input(
self,
prediction: str,
reference: str | None,
input_: str | None,
) -> dict:
"""Get the evaluation input."""
input_dict = {
"input": input_,
"output": prediction,
}
if self.requires_reference:
input_dict["reference"] = reference
return input_dict
def _prepare_output(self, result: dict) -> dict:
"""Prepare the output."""
parsed = result[self.output_key]
if RUN_KEY in result:
parsed[RUN_KEY] = result[RUN_KEY]
return parsed
@override
def _evaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
input: str | None = None,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate a prediction against the criteria.
Args:
prediction: The predicted text to evaluate.
reference: The reference text to compare against. This is required if
`requires_reference` is `True`.
input: The input text used to generate the prediction.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run info in the output.
**kwargs: Additional keyword arguments to pass to the `LLMChain` `__call__`
method.
Returns:
The evaluation results.
Examples:
>>> from langchain_openai import OpenAI
>>> from langchain_classic.evaluation.criteria import CriteriaEvalChain
>>> model = OpenAI()
>>> criteria = "conciseness"
>>> chain = CriteriaEvalChain.from_llm(llm=model, criteria=criteria)
>>> chain.evaluate_strings(
prediction="The answer is 42.",
reference="42",
input="What is the answer to life, the universe, and everything?",
)
"""
input_ = self._get_eval_input(prediction, reference, input)
result = self(
input_,
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
@override
async def _aevaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
input: str | None = None,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate a prediction against the criteria.
Args:
prediction: The predicted text to evaluate.
reference: The reference text to compare against. This is required if
`requires_reference` is `True`.
input: The input text used to generate the prediction.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run info in the output.
**kwargs: Additional keyword arguments to pass to the `LLMChain` `__call__`
method.
Returns:
The evaluation results.
Examples:
>>> from langchain_openai import OpenAI
>>> from langchain_classic.evaluation.criteria import CriteriaEvalChain
>>> model = OpenAI()
>>> criteria = "conciseness"
>>> chain = CriteriaEvalChain.from_llm(llm=model, criteria=criteria)
>>> await chain.aevaluate_strings(
prediction="The answer is 42.",
reference="42",
input="What is the answer to life, the universe, and everything?",
)
"""
input_ = self._get_eval_input(prediction, reference, input)
result = await self.acall(
input_,
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
class LabeledCriteriaEvalChain(CriteriaEvalChain):
"""Criteria evaluation chain that requires references."""
@classmethod
@override
def is_lc_serializable(cls) -> bool:
return False
@property
def requires_reference(self) -> bool:
"""Whether the evaluation requires a reference text."""
return True
@classmethod
def _resolve_prompt(
cls,
prompt: BasePromptTemplate | None = None,
) -> BasePromptTemplate:
expected_input_vars = {"input", "output", "criteria", "reference"}
prompt_ = prompt or PROMPT_WITH_REFERENCES
if expected_input_vars != set(prompt_.input_variables):
msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
raise ValueError(msg)
return prompt_
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
criteria: CRITERIA_TYPE | None = None,
*,
prompt: BasePromptTemplate | None = None,
**kwargs: Any,
) -> CriteriaEvalChain:
"""Create a `LabeledCriteriaEvalChain` instance from an llm and criteria.
Parameters
----------
llm : BaseLanguageModel
The language model to use for evaluation.
criteria : CRITERIA_TYPE - default=None for "helpfulness"
The criteria to evaluate the runs against. It can be:
- a mapping of a criterion name to its description
- a single criterion name present in one of the default criteria
- a single `ConstitutionalPrinciple` instance
prompt : Optional[BasePromptTemplate], default=None
The prompt template to use for generating prompts. If not provided,
a default prompt will be used.
**kwargs : Any
Additional keyword arguments to pass to the `LLMChain`
constructor.
Returns:
-------
LabeledCriteriaEvalChain
An instance of the `LabeledCriteriaEvalChain` class.
Examples:
--------
>>> from langchain_openai import OpenAI
>>> from langchain_classic.evaluation.criteria import LabeledCriteriaEvalChain
>>> model = OpenAI()
>>> criteria = {
"hallucination": (
"Does this submission contain information"
" not present in the input or reference?"
),
}
>>> chain = LabeledCriteriaEvalChain.from_llm(
llm=model,
criteria=criteria,
)
"""
prompt = cls._resolve_prompt(prompt)
criteria_ = cls.resolve_criteria(criteria)
criteria_str = "\n".join(f"{k}: {v}" for k, v in criteria_.items())
prompt_ = prompt.partial(criteria=criteria_str)
return cls(
llm=llm,
prompt=prompt_,
criterion_name="-".join(criteria_),
**kwargs,
)
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/evaluation/criteria/eval_chain.py",
"license": "MIT License",
"lines": 526,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/embedding_distance/base.py | """A chain for comparing the output of two models using embeddings."""
import functools
import logging
from enum import Enum
from importlib import util
from typing import Any
from langchain_core.callbacks import Callbacks
from langchain_core.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)
from langchain_core.embeddings import Embeddings
from langchain_core.utils import pre_init
from pydantic import ConfigDict, Field
from typing_extensions import override
from langchain_classic.chains.base import Chain
from langchain_classic.evaluation.schema import PairwiseStringEvaluator, StringEvaluator
from langchain_classic.schema import RUN_KEY
def _import_numpy() -> Any:
try:
import numpy as np
except ImportError as e:
msg = "Could not import numpy, please install with `pip install numpy`."
raise ImportError(msg) from e
return np
logger = logging.getLogger(__name__)
@functools.lru_cache(maxsize=1)
def _check_numpy() -> bool:
if bool(util.find_spec("numpy")):
return True
logger.warning(
"NumPy not found in the current Python environment. "
"langchain will use a pure Python implementation for embedding distance "
"operations, which may significantly impact performance, especially for large "
"datasets. For optimal speed and efficiency, consider installing NumPy: "
"pip install numpy",
)
return False
def _embedding_factory() -> Embeddings:
"""Create an `Embeddings` object.
Returns:
The created `Embeddings` object.
"""
# Here for backwards compatibility.
# Generally, we do not want to be seeing imports from langchain community
# or partner packages in langchain.
try:
from langchain_openai import OpenAIEmbeddings
except ImportError:
try:
from langchain_community.embeddings.openai import (
OpenAIEmbeddings,
)
except ImportError as e:
msg = (
"Could not import OpenAIEmbeddings. Please install the "
"OpenAIEmbeddings package using `pip install langchain-openai`."
)
raise ImportError(msg) from e
return OpenAIEmbeddings()
class EmbeddingDistance(str, Enum):
"""Embedding Distance Metric.
Attributes:
COSINE: Cosine distance metric.
EUCLIDEAN: Euclidean distance metric.
MANHATTAN: Manhattan distance metric.
CHEBYSHEV: Chebyshev distance metric.
HAMMING: Hamming distance metric.
"""
COSINE = "cosine"
EUCLIDEAN = "euclidean"
MANHATTAN = "manhattan"
CHEBYSHEV = "chebyshev"
HAMMING = "hamming"
class _EmbeddingDistanceChainMixin(Chain):
"""Shared functionality for embedding distance evaluators.
Attributes:
embeddings: The embedding objects to vectorize the outputs.
distance_metric: The distance metric to use for comparing the embeddings.
"""
embeddings: Embeddings = Field(default_factory=_embedding_factory)
distance_metric: EmbeddingDistance = Field(default=EmbeddingDistance.COSINE)
@pre_init
def _validate_tiktoken_installed(cls, values: dict[str, Any]) -> dict[str, Any]:
"""Validate that the TikTok library is installed.
Args:
values: The values to validate.
Returns:
The validated values.
"""
embeddings = values.get("embeddings")
types_ = []
try:
from langchain_openai import OpenAIEmbeddings
types_.append(OpenAIEmbeddings)
except ImportError:
pass
try:
from langchain_community.embeddings.openai import (
OpenAIEmbeddings,
)
types_.append(OpenAIEmbeddings)
except ImportError:
pass
if not types_:
msg = (
"Could not import OpenAIEmbeddings. Please install the "
"OpenAIEmbeddings package using `pip install langchain-openai`."
)
raise ImportError(msg)
if isinstance(embeddings, tuple(types_)):
try:
import tiktoken # noqa: F401
except ImportError as e:
msg = (
"The tiktoken library is required to use the default "
"OpenAI embeddings with embedding distance evaluators."
" Please either manually select a different Embeddings object"
" or install tiktoken using `pip install tiktoken`."
)
raise ImportError(msg) from e
return values
model_config = ConfigDict(
arbitrary_types_allowed=True,
)
@property
def output_keys(self) -> list[str]:
"""Return the output keys of the chain.
Returns:
The output keys.
"""
return ["score"]
def _prepare_output(self, result: dict) -> dict:
parsed = {"score": result["score"]}
if RUN_KEY in result:
parsed[RUN_KEY] = result[RUN_KEY]
return parsed
def _get_metric(self, metric: EmbeddingDistance) -> Any:
"""Get the metric function for the given metric name.
Args:
metric: The metric name.
Returns:
The metric function.
"""
metrics = {
EmbeddingDistance.COSINE: self._cosine_distance,
EmbeddingDistance.EUCLIDEAN: self._euclidean_distance,
EmbeddingDistance.MANHATTAN: self._manhattan_distance,
EmbeddingDistance.CHEBYSHEV: self._chebyshev_distance,
EmbeddingDistance.HAMMING: self._hamming_distance,
}
if metric in metrics:
return metrics[metric]
msg = f"Invalid metric: {metric}"
raise ValueError(msg)
@staticmethod
def _cosine_distance(a: Any, b: Any) -> Any:
"""Compute the cosine distance between two vectors.
Args:
a (np.ndarray): The first vector.
b (np.ndarray): The second vector.
Returns:
np.ndarray: The cosine distance.
"""
try:
from langchain_core.vectorstores.utils import _cosine_similarity
return 1.0 - _cosine_similarity(a, b)
except ImportError:
# Fallback to scipy if available
try:
from scipy.spatial.distance import cosine
return cosine(a.flatten(), b.flatten())
except ImportError:
# Pure numpy fallback
if _check_numpy():
np = _import_numpy()
a_flat = a.flatten()
b_flat = b.flatten()
dot_product = np.dot(a_flat, b_flat)
norm_a = np.linalg.norm(a_flat)
norm_b = np.linalg.norm(b_flat)
if norm_a == 0 or norm_b == 0:
return 0.0
return 1.0 - (dot_product / (norm_a * norm_b))
# Pure Python implementation
a_flat = a if hasattr(a, "__len__") else [a]
b_flat = b if hasattr(b, "__len__") else [b]
if hasattr(a, "flatten"):
a_flat = a.flatten()
if hasattr(b, "flatten"):
b_flat = b.flatten()
dot_product = sum(x * y for x, y in zip(a_flat, b_flat, strict=False))
norm_a = sum(x * x for x in a_flat) ** 0.5
norm_b = sum(x * x for x in b_flat) ** 0.5
if norm_a == 0 or norm_b == 0:
return 0.0
return 1.0 - (dot_product / (norm_a * norm_b))
@staticmethod
def _euclidean_distance(a: Any, b: Any) -> Any:
"""Compute the Euclidean distance between two vectors.
Args:
a (np.ndarray): The first vector.
b (np.ndarray): The second vector.
Returns:
np.floating: The Euclidean distance.
"""
try:
from scipy.spatial.distance import euclidean
return euclidean(a.flatten(), b.flatten())
except ImportError:
if _check_numpy():
import numpy as np
return np.linalg.norm(a - b)
return sum((x - y) * (x - y) for x, y in zip(a, b, strict=False)) ** 0.5
@staticmethod
def _manhattan_distance(a: Any, b: Any) -> Any:
"""Compute the Manhattan distance between two vectors.
Args:
a (np.ndarray): The first vector.
b (np.ndarray): The second vector.
Returns:
np.floating: The Manhattan distance.
"""
try:
from scipy.spatial.distance import cityblock
return cityblock(a.flatten(), b.flatten())
except ImportError:
if _check_numpy():
np = _import_numpy()
return np.sum(np.abs(a - b))
return sum(abs(x - y) for x, y in zip(a, b, strict=False))
@staticmethod
def _chebyshev_distance(a: Any, b: Any) -> Any:
"""Compute the Chebyshev distance between two vectors.
Args:
a (np.ndarray): The first vector.
b (np.ndarray): The second vector.
Returns:
np.floating: The Chebyshev distance.
"""
try:
from scipy.spatial.distance import chebyshev
return chebyshev(a.flatten(), b.flatten())
except ImportError:
if _check_numpy():
np = _import_numpy()
return np.max(np.abs(a - b))
return max(abs(x - y) for x, y in zip(a, b, strict=False))
@staticmethod
def _hamming_distance(a: Any, b: Any) -> Any:
"""Compute the Hamming distance between two vectors.
Args:
a (np.ndarray): The first vector.
b (np.ndarray): The second vector.
Returns:
np.floating: The Hamming distance.
"""
try:
from scipy.spatial.distance import hamming
return hamming(a.flatten(), b.flatten())
except ImportError:
if _check_numpy():
np = _import_numpy()
return np.mean(a != b)
return sum(1 for x, y in zip(a, b, strict=False) if x != y) / len(a)
def _compute_score(self, vectors: Any) -> float:
"""Compute the score based on the distance metric.
Args:
vectors (np.ndarray): The input vectors.
Returns:
The computed score.
"""
metric = self._get_metric(self.distance_metric)
if _check_numpy() and isinstance(vectors, _import_numpy().ndarray):
score = metric(vectors[0].reshape(1, -1), vectors[1].reshape(1, -1)).item()
else:
score = metric(vectors[0], vectors[1])
return float(score)
class EmbeddingDistanceEvalChain(_EmbeddingDistanceChainMixin, StringEvaluator):
"""Embedding distance evaluation chain.
Use embedding distances to score semantic difference between
a prediction and reference.
Examples:
>>> chain = EmbeddingDistanceEvalChain()
>>> result = chain.evaluate_strings(prediction="Hello", reference="Hi")
>>> print(result)
{'score': 0.5}
"""
@property
def requires_reference(self) -> bool:
"""Return whether the chain requires a reference.
Returns:
True if a reference is required, `False` otherwise.
"""
return True
@property
@override
def evaluation_name(self) -> str:
return f"embedding_{self.distance_metric.value}_distance"
@property
def input_keys(self) -> list[str]:
"""Return the input keys of the chain.
Returns:
The input keys.
"""
return ["prediction", "reference"]
@override
def _call(
self,
inputs: dict[str, Any],
run_manager: CallbackManagerForChainRun | None = None,
) -> dict[str, Any]:
"""Compute the score for a prediction and reference.
Args:
inputs: The input data.
run_manager: The callback manager.
Returns:
The computed score.
"""
vectors = self.embeddings.embed_documents(
[inputs["prediction"], inputs["reference"]],
)
if _check_numpy():
np = _import_numpy()
vectors = np.array(vectors)
score = self._compute_score(vectors)
return {"score": score}
@override
async def _acall(
self,
inputs: dict[str, Any],
run_manager: AsyncCallbackManagerForChainRun | None = None,
) -> dict[str, Any]:
"""Asynchronously compute the score for a prediction and reference.
Args:
inputs: The input data.
run_manager: The callback manager.
Returns:
The computed score.
"""
vectors = await self.embeddings.aembed_documents(
[
inputs["prediction"],
inputs["reference"],
],
)
if _check_numpy():
np = _import_numpy()
vectors = np.array(vectors)
score = self._compute_score(vectors)
return {"score": score}
@override
def _evaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate the embedding distance between a prediction and reference.
Args:
prediction: The output string from the first model.
reference: The output string from the second model.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run information in the output.
**kwargs: Additional keyword arguments.
Returns:
`dict` containing:
- score: The embedding distance between the two predictions.
"""
result = self(
inputs={"prediction": prediction, "reference": reference},
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
@override
async def _aevaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate the embedding distance between a prediction and reference.
Args:
prediction: The output string from the first model.
reference: The output string from the second model.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run information in the output.
**kwargs: Additional keyword arguments.
Returns:
`dict` containing:
- score: The embedding distance between the two predictions.
"""
result = await self.acall(
inputs={"prediction": prediction, "reference": reference},
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
class PairwiseEmbeddingDistanceEvalChain(
_EmbeddingDistanceChainMixin,
PairwiseStringEvaluator,
):
"""Use embedding distances to score semantic difference between two predictions.
Examples:
>>> chain = PairwiseEmbeddingDistanceEvalChain()
>>> result = chain.evaluate_string_pairs(prediction="Hello", prediction_b="Hi")
>>> print(result)
{'score': 0.5}
"""
@property
def input_keys(self) -> list[str]:
"""Return the input keys of the chain.
Returns:
The input keys.
"""
return ["prediction", "prediction_b"]
@property
def evaluation_name(self) -> str:
"""Return the evaluation name."""
return f"pairwise_embedding_{self.distance_metric.value}_distance"
@override
def _call(
self,
inputs: dict[str, Any],
run_manager: CallbackManagerForChainRun | None = None,
) -> dict[str, Any]:
"""Compute the score for two predictions.
Args:
inputs: The input data.
run_manager: The callback manager.
Returns:
The computed score.
"""
vectors = self.embeddings.embed_documents(
[
inputs["prediction"],
inputs["prediction_b"],
],
)
if _check_numpy():
np = _import_numpy()
vectors = np.array(vectors)
score = self._compute_score(vectors)
return {"score": score}
@override
async def _acall(
self,
inputs: dict[str, Any],
run_manager: AsyncCallbackManagerForChainRun | None = None,
) -> dict[str, Any]:
"""Asynchronously compute the score for two predictions.
Args:
inputs: The input data.
run_manager: The callback manager.
Returns:
The computed score.
"""
vectors = await self.embeddings.aembed_documents(
[
inputs["prediction"],
inputs["prediction_b"],
],
)
if _check_numpy():
np = _import_numpy()
vectors = np.array(vectors)
score = self._compute_score(vectors)
return {"score": score}
@override
def _evaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate the embedding distance between two predictions.
Args:
prediction: The output string from the first model.
prediction_b: The output string from the second model.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run information in the output.
**kwargs: Additional keyword arguments.
Returns:
`dict` containing:
- score: The embedding distance between the two predictions.
"""
result = self(
inputs={"prediction": prediction, "prediction_b": prediction_b},
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
@override
async def _aevaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate the embedding distance between two predictions.
Args:
prediction: The output string from the first model.
prediction_b: The output string from the second model.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run information in the output.
**kwargs: Additional keyword arguments.
Returns:
`dict` containing:
- score: The embedding distance between the two predictions.
"""
result = await self.acall(
inputs={"prediction": prediction, "prediction_b": prediction_b},
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/evaluation/embedding_distance/base.py",
"license": "MIT License",
"lines": 553,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/exact_match/base.py | import string
from typing import Any
from typing_extensions import override
from langchain_classic.evaluation.schema import StringEvaluator
class ExactMatchStringEvaluator(StringEvaluator):
"""Compute an exact match between the prediction and the reference.
Examples:
----------
>>> evaluator = ExactMatchChain()
>>> evaluator.evaluate_strings(
prediction="Mindy is the CTO",
reference="Mindy is the CTO",
) # This will return {'score': 1.0}
>>> evaluator.evaluate_strings(
prediction="Mindy is the CTO",
reference="Mindy is the CEO",
) # This will return {'score': 0.0}
"""
def __init__(
self,
*,
ignore_case: bool = False,
ignore_punctuation: bool = False,
ignore_numbers: bool = False,
**_: Any,
):
"""Initialize the `ExactMatchStringEvaluator`.
Args:
ignore_case: Whether to ignore case when comparing strings.
ignore_punctuation: Whether to ignore punctuation when comparing strings.
ignore_numbers: Whether to ignore numbers when comparing strings.
"""
super().__init__()
self.ignore_case = ignore_case
self.ignore_punctuation = ignore_punctuation
self.ignore_numbers = ignore_numbers
@property
def requires_input(self) -> bool:
"""This evaluator does not require input."""
return False
@property
def requires_reference(self) -> bool:
"""This evaluator requires a reference."""
return True
@property
def input_keys(self) -> list[str]:
"""Get the input keys.
Returns:
The input keys.
"""
return ["reference", "prediction"]
@property
def evaluation_name(self) -> str:
"""Get the evaluation name.
Returns:
The evaluation name.
"""
return "exact_match"
@override
def _evaluate_strings( # type: ignore[override]
self,
*,
prediction: str,
reference: str,
**kwargs: Any,
) -> dict:
"""Evaluate the exact match between the prediction and the reference.
Args:
prediction: The prediction string.
reference: The reference string.
**kwargs: Additional keyword arguments (not used).
Returns:
The evaluation results containing the score.
"""
if self.ignore_case:
prediction = prediction.lower()
reference = reference.lower()
if self.ignore_punctuation:
prediction = prediction.translate(str.maketrans("", "", string.punctuation))
reference = reference.translate(str.maketrans("", "", string.punctuation))
if self.ignore_numbers:
prediction = prediction.translate(str.maketrans("", "", string.digits))
reference = reference.translate(str.maketrans("", "", string.digits))
return {"score": int(prediction == reference)}
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/evaluation/exact_match/base.py",
"license": "MIT License",
"lines": 84,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/loading.py | """Loading datasets and evaluators."""
from collections.abc import Sequence
from typing import Any
from langchain_core.language_models import BaseLanguageModel
from langchain_classic.chains.base import Chain
from langchain_classic.evaluation.agents.trajectory_eval_chain import (
TrajectoryEvalChain,
)
from langchain_classic.evaluation.comparison import PairwiseStringEvalChain
from langchain_classic.evaluation.comparison.eval_chain import (
LabeledPairwiseStringEvalChain,
)
from langchain_classic.evaluation.criteria.eval_chain import (
CriteriaEvalChain,
LabeledCriteriaEvalChain,
)
from langchain_classic.evaluation.embedding_distance.base import (
EmbeddingDistanceEvalChain,
PairwiseEmbeddingDistanceEvalChain,
)
from langchain_classic.evaluation.exact_match.base import ExactMatchStringEvaluator
from langchain_classic.evaluation.parsing.base import (
JsonEqualityEvaluator,
JsonValidityEvaluator,
)
from langchain_classic.evaluation.parsing.json_distance import JsonEditDistanceEvaluator
from langchain_classic.evaluation.parsing.json_schema import JsonSchemaEvaluator
from langchain_classic.evaluation.qa import (
ContextQAEvalChain,
CotQAEvalChain,
QAEvalChain,
)
from langchain_classic.evaluation.regex_match.base import RegexMatchStringEvaluator
from langchain_classic.evaluation.schema import (
EvaluatorType,
LLMEvalChain,
StringEvaluator,
)
from langchain_classic.evaluation.scoring.eval_chain import (
LabeledScoreStringEvalChain,
ScoreStringEvalChain,
)
from langchain_classic.evaluation.string_distance.base import (
PairwiseStringDistanceEvalChain,
StringDistanceEvalChain,
)
def load_dataset(uri: str) -> list[dict]:
"""Load a dataset from the [LangChainDatasets on HuggingFace](https://huggingface.co/LangChainDatasets).
Args:
uri: The uri of the dataset to load.
Returns:
A list of dictionaries, each representing a row in the dataset.
**Prerequisites**
```bash
pip install datasets
```
Examples:
--------
```python
from langchain_classic.evaluation import load_dataset
ds = load_dataset("llm-math")
```
"""
try:
from datasets import load_dataset
except ImportError as e:
msg = (
"load_dataset requires the `datasets` package."
" Please install with `pip install datasets`"
)
raise ImportError(msg) from e
dataset = load_dataset(f"LangChainDatasets/{uri}")
return list(dataset["train"])
_EVALUATOR_MAP: dict[
EvaluatorType,
type[LLMEvalChain] | type[Chain] | type[StringEvaluator],
] = {
EvaluatorType.QA: QAEvalChain,
EvaluatorType.COT_QA: CotQAEvalChain,
EvaluatorType.CONTEXT_QA: ContextQAEvalChain,
EvaluatorType.PAIRWISE_STRING: PairwiseStringEvalChain,
EvaluatorType.SCORE_STRING: ScoreStringEvalChain,
EvaluatorType.LABELED_PAIRWISE_STRING: LabeledPairwiseStringEvalChain,
EvaluatorType.LABELED_SCORE_STRING: LabeledScoreStringEvalChain,
EvaluatorType.AGENT_TRAJECTORY: TrajectoryEvalChain,
EvaluatorType.CRITERIA: CriteriaEvalChain,
EvaluatorType.LABELED_CRITERIA: LabeledCriteriaEvalChain,
EvaluatorType.STRING_DISTANCE: StringDistanceEvalChain,
EvaluatorType.PAIRWISE_STRING_DISTANCE: PairwiseStringDistanceEvalChain,
EvaluatorType.EMBEDDING_DISTANCE: EmbeddingDistanceEvalChain,
EvaluatorType.PAIRWISE_EMBEDDING_DISTANCE: PairwiseEmbeddingDistanceEvalChain,
EvaluatorType.JSON_VALIDITY: JsonValidityEvaluator,
EvaluatorType.JSON_EQUALITY: JsonEqualityEvaluator,
EvaluatorType.JSON_EDIT_DISTANCE: JsonEditDistanceEvaluator,
EvaluatorType.JSON_SCHEMA_VALIDATION: JsonSchemaEvaluator,
EvaluatorType.REGEX_MATCH: RegexMatchStringEvaluator,
EvaluatorType.EXACT_MATCH: ExactMatchStringEvaluator,
}
def load_evaluator(
evaluator: EvaluatorType,
*,
llm: BaseLanguageModel | None = None,
**kwargs: Any,
) -> Chain | StringEvaluator:
"""Load the requested evaluation chain specified by a string.
Parameters
----------
evaluator : EvaluatorType
The type of evaluator to load.
llm : BaseLanguageModel, optional
The language model to use for evaluation, by default None
**kwargs : Any
Additional keyword arguments to pass to the evaluator.
Returns:
-------
Chain
The loaded evaluation chain.
Examples:
--------
>>> from langchain_classic.evaluation import load_evaluator, EvaluatorType
>>> evaluator = load_evaluator(EvaluatorType.QA)
"""
if evaluator not in _EVALUATOR_MAP:
msg = (
f"Unknown evaluator type: {evaluator}"
f"\nValid types are: {list(_EVALUATOR_MAP.keys())}"
)
raise ValueError(msg)
evaluator_cls = _EVALUATOR_MAP[evaluator]
if issubclass(evaluator_cls, LLMEvalChain):
try:
try:
from langchain_openai import ChatOpenAI
except ImportError:
try:
from langchain_community.chat_models.openai import (
ChatOpenAI,
)
except ImportError as e:
msg = (
"Could not import langchain_openai or fallback onto "
"langchain_community. Please install langchain_openai "
"or specify a language model explicitly. "
"It's recommended to install langchain_openai AND "
"specify a language model explicitly."
)
raise ImportError(msg) from e
llm = llm or ChatOpenAI(model="gpt-4", seed=42, temperature=0)
except Exception as e:
msg = (
f"Evaluation with the {evaluator_cls} requires a "
"language model to function."
" Failed to create the default 'gpt-4' model."
" Please manually provide an evaluation LLM"
" or check your openai credentials."
)
raise ValueError(msg) from e
return evaluator_cls.from_llm(llm=llm, **kwargs)
return evaluator_cls(**kwargs)
def load_evaluators(
evaluators: Sequence[EvaluatorType],
*,
llm: BaseLanguageModel | None = None,
config: dict | None = None,
**kwargs: Any,
) -> list[Chain | StringEvaluator]:
"""Load evaluators specified by a list of evaluator types.
Parameters
----------
evaluators : Sequence[EvaluatorType]
The list of evaluator types to load.
llm : BaseLanguageModel, optional
The language model to use for evaluation, if none is provided, a default
ChatOpenAI gpt-4 model will be used.
config : dict, optional
A dictionary mapping evaluator types to additional keyword arguments,
by default None
**kwargs : Any
Additional keyword arguments to pass to all evaluators.
Returns:
-------
List[Chain]
The loaded evaluators.
Examples:
--------
>>> from langchain_classic.evaluation import load_evaluators, EvaluatorType
>>> evaluators = [EvaluatorType.QA, EvaluatorType.CRITERIA]
>>> loaded_evaluators = load_evaluators(evaluators, criteria="helpfulness")
"""
loaded = []
for evaluator in evaluators:
_kwargs = config.get(evaluator, {}) if config else {}
loaded.append(load_evaluator(evaluator, llm=llm, **{**kwargs, **_kwargs}))
return loaded
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/evaluation/loading.py",
"license": "MIT License",
"lines": 194,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/parsing/base.py | """Evaluators for parsing strings."""
import json
import logging
from collections.abc import Callable
from operator import eq
from typing import Any, cast
from langchain_core.utils.json import parse_json_markdown
from typing_extensions import override
from langchain_classic.evaluation.schema import StringEvaluator
_logger = logging.getLogger(__name__)
class JsonValidityEvaluator(StringEvaluator):
"""Evaluate whether the prediction is valid JSON.
This evaluator checks if the prediction is a valid JSON string. It does not
require any input or reference.
Attributes:
requires_input: Whether this evaluator requires an input
string. Always False.
requires_reference: Whether this evaluator requires a
reference string. Always False.
evaluation_name: The name of the evaluation metric.
Always "json".
Examples:
>>> evaluator = JsonValidityEvaluator()
>>> prediction = '{"name": "John", "age": 30, "city": "New York"}'
>>> evaluator.evaluate(prediction)
{'score': 1}
>>> prediction = '{"name": "John", "age": 30, "city": "New York",}'
>>> evaluator.evaluate(prediction)
{'score': 0, 'reasoning': 'Expecting property name enclosed in double quotes'}
"""
def __init__(self, **_: Any) -> None:
"""Initialize the JsonValidityEvaluator."""
super().__init__()
@property
@override
def requires_input(self) -> bool:
return False
@property
@override
def requires_reference(self) -> bool:
return False
@property
@override
def evaluation_name(self) -> str:
return "json_validity"
@override
def _evaluate_strings(
self,
prediction: str,
**kwargs: Any,
) -> dict:
"""Evaluate the prediction string.
Args:
prediction: The prediction string to evaluate.
**kwargs: Additional keyword arguments (not used).
Returns:
`dict` containing the evaluation score. The score is `1` if
the prediction is valid JSON, and `0` otherwise.
If the prediction is not valid JSON, the dictionary also contains
a `reasoning` field with the error message.
"""
try:
parse_json_markdown(prediction, parser=json.loads)
except json.JSONDecodeError as e:
return {"score": 0, "reasoning": str(e)}
except Exception as e:
_logger.exception("Passing JSON failed with unexpected error.")
return {"score": 0, "reasoning": str(e)}
return {"score": 1}
class JsonEqualityEvaluator(StringEvaluator):
"""Json Equality Evaluator.
Evaluate whether the prediction is equal to the reference after
parsing both as JSON.
This evaluator checks if the prediction, after parsing as JSON, is equal
to the reference,
which is also parsed as JSON. It does not require an input string.
Attributes:
requires_input: Whether this evaluator requires an
input string. Always False.
requires_reference: Whether this evaluator requires
a reference string. Always True.
evaluation_name: The name of the evaluation metric.
Always "parsed_equality".
Examples:
>>> evaluator = JsonEqualityEvaluator()
>>> evaluator.evaluate_strings('{"a": 1}', reference='{"a": 1}')
{'score': True}
>>> evaluator.evaluate_strings('{"a": 1}', reference='{"a": 2}')
{'score': False}
>>> evaluator = JsonEqualityEvaluator(operator=lambda x, y: x["a"] == y["a"])
>>> evaluator.evaluate_strings('{"a": 1}', reference='{"a": 1}')
{'score': True}
>>> evaluator.evaluate_strings('{"a": 1}', reference='{"a": 2}')
{'score': False}
"""
def __init__(self, operator: Callable | None = None, **_: Any) -> None:
"""Initialize the JsonEqualityEvaluator.
Args:
operator: A custom operator to compare the parsed JSON objects.
Defaults to equality (`eq`).
"""
super().__init__()
self.operator = operator or eq
@property
@override
def requires_input(self) -> bool:
return False
@property
@override
def requires_reference(self) -> bool:
return True
@property
@override
def evaluation_name(self) -> str:
return "json_equality"
def _parse_json(
self,
string: Any,
) -> dict | list | None | float | bool | int | str:
if isinstance(string, str):
return parse_json_markdown(string)
return string
@override
def _evaluate_strings(
self,
prediction: str,
reference: str | None = None,
**kwargs: Any,
) -> dict:
"""Evaluate the prediction string.
Args:
prediction: The prediction string to evaluate.
reference: The reference string to compare against.
**kwargs: Additional keyword arguments (not used).
Returns:
`dict` containing the evaluation score.
"""
parsed = self._parse_json(prediction)
label = self._parse_json(cast("str", reference))
if isinstance(label, list):
if not isinstance(parsed, list):
return {"score": 0}
parsed = sorted(parsed, key=str)
label = sorted(label, key=str)
return {"score": self.operator(parsed, label)}
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/evaluation/parsing/base.py",
"license": "MIT License",
"lines": 145,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/qa/eval_chain.py | """LLM Chains for evaluating question answering."""
from __future__ import annotations
import re
import string
from collections.abc import Sequence
from typing import Any
from langchain_core.callbacks import Callbacks
from langchain_core.language_models import BaseLanguageModel
from langchain_core.prompts import PromptTemplate
from pydantic import ConfigDict
from typing_extensions import override
from langchain_classic.chains.llm import LLMChain
from langchain_classic.evaluation.qa.eval_prompt import (
CONTEXT_PROMPT,
COT_PROMPT,
PROMPT,
)
from langchain_classic.evaluation.schema import LLMEvalChain, StringEvaluator
from langchain_classic.schema import RUN_KEY
def _get_score(text: str) -> tuple[str, int] | None:
match = re.search(r"grade:\s*(correct|incorrect)", text.strip(), re.IGNORECASE)
if match:
if match.group(1).upper() == "CORRECT":
return "CORRECT", 1
if match.group(1).upper() == "INCORRECT":
return "INCORRECT", 0
try:
first_word = (
text.strip().split()[0].translate(str.maketrans("", "", string.punctuation))
)
if first_word.upper() == "CORRECT":
return "CORRECT", 1
if first_word.upper() == "INCORRECT":
return "INCORRECT", 0
last_word = (
text.strip()
.split()[-1]
.translate(str.maketrans("", "", string.punctuation))
)
if last_word.upper() == "CORRECT":
return "CORRECT", 1
if last_word.upper() == "INCORRECT":
return "INCORRECT", 0
except IndexError:
pass
return None
def _parse_string_eval_output(text: str) -> dict:
"""Parse the output text.
Args:
text: The output text to parse.
Returns:
The parsed output.
"""
reasoning = text.strip()
parsed_scores = _get_score(reasoning)
if parsed_scores is None:
value, score = None, None
else:
value, score = parsed_scores
return {
"reasoning": reasoning,
"value": value,
"score": score,
}
class QAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):
"""LLM Chain for evaluating question answering."""
output_key: str = "results"
model_config = ConfigDict(
extra="ignore",
)
@classmethod
@override
def is_lc_serializable(cls) -> bool:
return False
@property
@override
def evaluation_name(self) -> str:
return "correctness"
@property
@override
def requires_reference(self) -> bool:
return True
@property
@override
def requires_input(self) -> bool:
return True
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
prompt: PromptTemplate | None = None,
**kwargs: Any,
) -> QAEvalChain:
"""Load QA Eval Chain from LLM.
Args:
llm: The base language model to use.
prompt: A prompt template containing the input_variables:
`'input'`, `'answer'` and `'result'` that will be used as the prompt
for evaluation.
Defaults to `PROMPT`.
**kwargs: Additional keyword arguments.
Returns:
The loaded QA eval chain.
"""
prompt = prompt or PROMPT
expected_input_vars = {"query", "answer", "result"}
if expected_input_vars != set(prompt.input_variables):
msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt.input_variables}"
)
raise ValueError(msg)
return cls(llm=llm, prompt=prompt, **kwargs)
def evaluate(
self,
examples: Sequence[dict],
predictions: Sequence[dict],
question_key: str = "query",
answer_key: str = "answer",
prediction_key: str = "result",
*,
callbacks: Callbacks = None,
) -> list[dict]:
"""Evaluate question answering examples and predictions."""
inputs = [
{
"query": example[question_key],
"answer": example[answer_key],
"result": predictions[i][prediction_key],
}
for i, example in enumerate(examples)
]
return self.apply(inputs, callbacks=callbacks)
def _prepare_output(self, result: dict) -> dict:
parsed_result = _parse_string_eval_output(result[self.output_key])
if RUN_KEY in result:
parsed_result[RUN_KEY] = result[RUN_KEY]
return parsed_result
@override
def _evaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
input: str | None = None,
callbacks: Callbacks = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate Chain or LLM output, based on optional input and label.
Args:
prediction: The LLM or chain prediction to evaluate.
reference: The reference label to evaluate against.
input: The input to consider during evaluation
callbacks: The callbacks to use for tracing.
include_run_info: Whether to include run info in the returned results.
**kwargs: Additional keyword arguments, including callbacks, tags, etc.
Returns:
The evaluation results containing the score or value.
"""
result = self(
{
"query": input,
"answer": reference,
"result": prediction,
},
callbacks=callbacks,
include_run_info=include_run_info,
)
return self._prepare_output(result)
@override
async def _aevaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
input: str | None = None,
callbacks: Callbacks = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
result = await self.acall(
inputs={"query": input, "answer": reference, "result": prediction},
callbacks=callbacks,
include_run_info=include_run_info,
)
return self._prepare_output(result)
class ContextQAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):
"""LLM Chain for evaluating QA w/o GT based on context."""
@classmethod
@override
def is_lc_serializable(cls) -> bool:
return False
@property
def requires_reference(self) -> bool:
"""Whether the chain requires a reference string."""
return True
@property
def requires_input(self) -> bool:
"""Whether the chain requires an input string."""
return True
model_config = ConfigDict(
extra="ignore",
)
@classmethod
def _validate_input_vars(cls, prompt: PromptTemplate) -> None:
expected_input_vars = {"query", "context", "result"}
if expected_input_vars != set(prompt.input_variables):
msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt.input_variables}"
)
raise ValueError(msg)
@property
@override
def evaluation_name(self) -> str:
return "Contextual Accuracy"
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
prompt: PromptTemplate | None = None,
**kwargs: Any,
) -> ContextQAEvalChain:
"""Load QA Eval Chain from LLM.
Args:
llm: The base language model to use.
prompt: A prompt template containing the `input_variables`:
`'query'`, `'context'` and `'result'` that will be used as the prompt
for evaluation.
Defaults to `PROMPT`.
**kwargs: Additional keyword arguments.
Returns:
The loaded QA eval chain.
"""
prompt = prompt or CONTEXT_PROMPT
cls._validate_input_vars(prompt)
return cls(llm=llm, prompt=prompt, **kwargs)
def evaluate(
self,
examples: list[dict],
predictions: list[dict],
question_key: str = "query",
context_key: str = "context",
prediction_key: str = "result",
*,
callbacks: Callbacks = None,
) -> list[dict]:
"""Evaluate question answering examples and predictions."""
inputs = [
{
"query": example[question_key],
"context": example[context_key],
"result": predictions[i][prediction_key],
}
for i, example in enumerate(examples)
]
return self.apply(inputs, callbacks=callbacks)
def _prepare_output(self, result: dict) -> dict:
parsed_result = _parse_string_eval_output(result[self.output_key])
if RUN_KEY in result:
parsed_result[RUN_KEY] = result[RUN_KEY]
return parsed_result
@override
def _evaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
input: str | None = None,
callbacks: Callbacks = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
result = self(
{
"query": input,
"context": reference,
"result": prediction,
},
callbacks=callbacks,
include_run_info=include_run_info,
)
return self._prepare_output(result)
@override
async def _aevaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
input: str | None = None,
callbacks: Callbacks = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
result = await self.acall(
inputs={"query": input, "context": reference, "result": prediction},
callbacks=callbacks,
include_run_info=include_run_info,
)
return self._prepare_output(result)
class CotQAEvalChain(ContextQAEvalChain):
"""LLM Chain for evaluating QA using chain of thought reasoning."""
@classmethod
@override
def is_lc_serializable(cls) -> bool:
return False
@property
@override
def evaluation_name(self) -> str:
return "COT Contextual Accuracy"
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
prompt: PromptTemplate | None = None,
**kwargs: Any,
) -> CotQAEvalChain:
"""Load QA Eval Chain from LLM."""
prompt = prompt or COT_PROMPT
cls._validate_input_vars(prompt)
return cls(llm=llm, prompt=prompt, **kwargs)
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/evaluation/qa/eval_chain.py",
"license": "MIT License",
"lines": 322,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/regex_match/base.py | import re
from typing import Any
from typing_extensions import override
from langchain_classic.evaluation.schema import StringEvaluator
class RegexMatchStringEvaluator(StringEvaluator):
"""Compute a regex match between the prediction and the reference.
Examples:
----------
>>> evaluator = RegexMatchStringEvaluator(flags=re.IGNORECASE)
>>> evaluator.evaluate_strings(
prediction="Mindy is the CTO",
reference="^mindy.*cto$",
) # This will return {'score': 1.0} due to the IGNORECASE flag
>>> evaluator = RegexMatchStringEvaluator()
>>> evaluator.evaluate_strings(
prediction="Mindy is the CTO",
reference="^Mike.*CEO$",
) # This will return {'score': 0.0}
>>> evaluator.evaluate_strings(
prediction="Mindy is the CTO",
reference="^Mike.*CEO$|^Mindy.*CTO$",
) # This will return {'score': 1.0} as the prediction matches the second pattern in the union
""" # noqa: E501
def __init__(self, *, flags: int = 0, **_: Any): # Default is no flags
"""Initialize the RegexMatchStringEvaluator.
Args:
flags: Flags to use for the regex match. Defaults to no flags.
"""
super().__init__()
self.flags = flags
@property
def requires_input(self) -> bool:
"""This evaluator does not require input."""
return False
@property
def requires_reference(self) -> bool:
"""This evaluator requires a reference."""
return True
@property
def input_keys(self) -> list[str]:
"""Get the input keys.
Returns:
The input keys.
"""
return ["reference", "prediction"]
@property
def evaluation_name(self) -> str:
"""Get the evaluation name.
Returns:
The evaluation name.
"""
return "regex_match"
@override
def _evaluate_strings( # type: ignore[override]
self,
*,
prediction: str,
reference: str,
**kwargs: Any,
) -> dict:
"""Evaluate the regex match between the prediction and the reference.
Args:
prediction: The prediction string.
reference: The reference regex pattern.
**kwargs: Additional keyword arguments (not used).
Returns:
The evaluation results containing the score.
"""
match = re.match(reference, prediction, flags=self.flags)
return {"score": int(bool(match))}
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/evaluation/regex_match/base.py",
"license": "MIT License",
"lines": 70,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/schema.py | """Interfaces to be implemented by general evaluators."""
from __future__ import annotations
import logging
from abc import ABC, abstractmethod
from collections.abc import Sequence
from enum import Enum
from typing import Any
from warnings import warn
from langchain_core.agents import AgentAction
from langchain_core.language_models import BaseLanguageModel
from langchain_core.runnables.config import run_in_executor
from langchain_classic.chains.base import Chain
logger = logging.getLogger(__name__)
class EvaluatorType(str, Enum):
"""The types of the evaluators."""
QA = "qa"
"""Question answering evaluator, which grades answers to questions
directly using an LLM."""
COT_QA = "cot_qa"
"""Chain of thought question answering evaluator, which grades
answers to questions using
chain of thought 'reasoning'."""
CONTEXT_QA = "context_qa"
"""Question answering evaluator that incorporates 'context' in the response."""
PAIRWISE_STRING = "pairwise_string"
"""The pairwise string evaluator, which predicts the preferred prediction from
between two models."""
SCORE_STRING = "score_string"
"""The scored string evaluator, which gives a score between 1 and 10
to a prediction."""
LABELED_PAIRWISE_STRING = "labeled_pairwise_string"
"""The labeled pairwise string evaluator, which predicts the preferred prediction
from between two models based on a ground truth reference label."""
LABELED_SCORE_STRING = "labeled_score_string"
"""The labeled scored string evaluator, which gives a score between 1 and 10
to a prediction based on a ground truth reference label."""
AGENT_TRAJECTORY = "trajectory"
"""The agent trajectory evaluator, which grades the agent's intermediate steps."""
CRITERIA = "criteria"
"""The criteria evaluator, which evaluates a model based on a
custom set of criteria without any reference labels."""
LABELED_CRITERIA = "labeled_criteria"
"""The labeled criteria evaluator, which evaluates a model based on a
custom set of criteria, with a reference label."""
STRING_DISTANCE = "string_distance"
"""Compare predictions to a reference answer using string edit distances."""
EXACT_MATCH = "exact_match"
"""Compare predictions to a reference answer using exact matching."""
REGEX_MATCH = "regex_match"
"""Compare predictions to a reference answer using regular expressions."""
PAIRWISE_STRING_DISTANCE = "pairwise_string_distance"
"""Compare predictions based on string edit distances."""
EMBEDDING_DISTANCE = "embedding_distance"
"""Compare a prediction to a reference label using embedding distance."""
PAIRWISE_EMBEDDING_DISTANCE = "pairwise_embedding_distance"
"""Compare two predictions using embedding distance."""
JSON_VALIDITY = "json_validity"
"""Check if a prediction is valid JSON."""
JSON_EQUALITY = "json_equality"
"""Check if a prediction is equal to a reference JSON."""
JSON_EDIT_DISTANCE = "json_edit_distance"
"""Compute the edit distance between two JSON strings after canonicalization."""
JSON_SCHEMA_VALIDATION = "json_schema_validation"
"""Check if a prediction is valid JSON according to a JSON schema."""
class LLMEvalChain(Chain):
"""A base class for evaluators that use an LLM."""
@classmethod
@abstractmethod
def from_llm(cls, llm: BaseLanguageModel, **kwargs: Any) -> LLMEvalChain:
"""Create a new evaluator from an LLM."""
class _EvalArgsMixin:
"""Mixin for checking evaluation arguments."""
@property
def requires_reference(self) -> bool:
"""Whether this evaluator requires a reference label."""
return False
@property
def requires_input(self) -> bool:
"""Whether this evaluator requires an input string."""
return False
@property
def _skip_input_warning(self) -> str:
"""Warning to show when input is ignored."""
return f"Ignoring input in {self.__class__.__name__}, as it is not expected."
@property
def _skip_reference_warning(self) -> str:
"""Warning to show when reference is ignored."""
return (
f"Ignoring reference in {self.__class__.__name__}, as it is not expected."
)
def _check_evaluation_args(
self,
reference: str | None = None,
input_: str | None = None,
) -> None:
"""Check if the evaluation arguments are valid.
Args:
reference: The reference label.
input_: The input string.
Raises:
ValueError: If the evaluator requires an input string but none is provided,
or if the evaluator requires a reference label but none is provided.
"""
if self.requires_input and input_ is None:
msg = f"{self.__class__.__name__} requires an input string."
raise ValueError(msg)
if input_ is not None and not self.requires_input:
warn(self._skip_input_warning, stacklevel=3)
if self.requires_reference and reference is None:
msg = f"{self.__class__.__name__} requires a reference string."
raise ValueError(msg)
if reference is not None and not self.requires_reference:
warn(self._skip_reference_warning, stacklevel=3)
class StringEvaluator(_EvalArgsMixin, ABC):
"""String evaluator interface.
Grade, tag, or otherwise evaluate predictions relative to their inputs
and/or reference labels.
"""
@property
def evaluation_name(self) -> str:
"""The name of the evaluation."""
return self.__class__.__name__
@property
def requires_reference(self) -> bool:
"""Whether this evaluator requires a reference label."""
return False
@abstractmethod
def _evaluate_strings(
self,
*,
prediction: str | Any,
reference: str | Any | None = None,
input: str | Any | None = None, # noqa: A002
**kwargs: Any,
) -> dict:
"""Evaluate Chain or LLM output, based on optional input and label.
Args:
prediction: The LLM or chain prediction to evaluate.
reference: The reference label to evaluate against.
input: The input to consider during evaluation.
**kwargs: Additional keyword arguments, including callbacks, tags, etc.
Returns:
The evaluation results containing the score or value.
It is recommended that the dictionary contain the following keys:
- score: the score of the evaluation, if applicable.
- value: the string value of the evaluation, if applicable.
- reasoning: the reasoning for the evaluation, if applicable.
"""
async def _aevaluate_strings(
self,
*,
prediction: str | Any,
reference: str | Any | None = None,
input: str | Any | None = None, # noqa: A002
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate Chain or LLM output, based on optional input and label.
Args:
prediction: The LLM or chain prediction to evaluate.
reference: The reference label to evaluate against.
input: The input to consider during evaluation.
**kwargs: Additional keyword arguments, including callbacks, tags, etc.
Returns:
The evaluation results containing the score or value.
It is recommended that the dictionary contain the following keys:
- score: the score of the evaluation, if applicable.
- value: the string value of the evaluation, if applicable.
- reasoning: the reasoning for the evaluation, if applicable.
""" # noqa: E501
return await run_in_executor(
None,
self._evaluate_strings,
prediction=prediction,
reference=reference,
input=input,
**kwargs,
)
def evaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
input: str | None = None, # noqa: A002
**kwargs: Any,
) -> dict:
"""Evaluate Chain or LLM output, based on optional input and label.
Args:
prediction: The LLM or chain prediction to evaluate.
reference: The reference label to evaluate against.
input: The input to consider during evaluation.
**kwargs: Additional keyword arguments, including callbacks, tags, etc.
Returns:
The evaluation results containing the score or value.
"""
self._check_evaluation_args(reference=reference, input_=input)
return self._evaluate_strings(
prediction=prediction,
reference=reference,
input=input,
**kwargs,
)
async def aevaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
input: str | None = None, # noqa: A002
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate Chain or LLM output, based on optional input and label.
Args:
prediction: The LLM or chain prediction to evaluate.
reference: The reference label to evaluate against.
input: The input to consider during evaluation.
**kwargs: Additional keyword arguments, including callbacks, tags, etc.
Returns:
The evaluation results containing the score or value.
""" # noqa: E501
self._check_evaluation_args(reference=reference, input_=input)
return await self._aevaluate_strings(
prediction=prediction,
reference=reference,
input=input,
**kwargs,
)
class PairwiseStringEvaluator(_EvalArgsMixin, ABC):
"""Compare the output of two models (or two outputs of the same model)."""
@abstractmethod
def _evaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
reference: str | None = None,
input: str | None = None, # noqa: A002
**kwargs: Any,
) -> dict:
"""Evaluate the output string pairs.
Args:
prediction: The output string from the first model.
prediction_b: The output string from the second model.
reference: The expected output / reference string.
input: The input string.
**kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
Returns:
`dict` containing the preference, scores, and/or other information.
""" # noqa: E501
async def _aevaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
reference: str | None = None,
input: str | None = None, # noqa: A002
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate the output string pairs.
Args:
prediction: The output string from the first model.
prediction_b: The output string from the second model.
reference: The expected output / reference string.
input: The input string.
**kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
Returns:
`dict` containing the preference, scores, and/or other information.
""" # noqa: E501
return await run_in_executor(
None,
self._evaluate_string_pairs,
prediction=prediction,
prediction_b=prediction_b,
reference=reference,
input=input,
**kwargs,
)
def evaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
reference: str | None = None,
input: str | None = None, # noqa: A002
**kwargs: Any,
) -> dict:
"""Evaluate the output string pairs.
Args:
prediction: The output string from the first model.
prediction_b: The output string from the second model.
reference: The expected output / reference string.
input: The input string.
**kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
Returns:
`dict` containing the preference, scores, and/or other information.
""" # noqa: E501
self._check_evaluation_args(reference=reference, input_=input)
return self._evaluate_string_pairs(
prediction=prediction,
prediction_b=prediction_b,
reference=reference,
input=input,
**kwargs,
)
async def aevaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
reference: str | None = None,
input: str | None = None, # noqa: A002
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate the output string pairs.
Args:
prediction: The output string from the first model.
prediction_b: The output string from the second model.
reference: The expected output / reference string.
input: The input string.
**kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
Returns:
`dict` containing the preference, scores, and/or other information.
""" # noqa: E501
self._check_evaluation_args(reference=reference, input_=input)
return await self._aevaluate_string_pairs(
prediction=prediction,
prediction_b=prediction_b,
reference=reference,
input=input,
**kwargs,
)
class AgentTrajectoryEvaluator(_EvalArgsMixin, ABC):
"""Interface for evaluating agent trajectories."""
@property
def requires_input(self) -> bool:
"""Whether this evaluator requires an input string."""
return True
@abstractmethod
def _evaluate_agent_trajectory(
self,
*,
prediction: str,
agent_trajectory: Sequence[tuple[AgentAction, str]],
input: str, # noqa: A002
reference: str | None = None,
**kwargs: Any,
) -> dict:
"""Evaluate a trajectory.
Args:
prediction: The final predicted response.
agent_trajectory:
The intermediate steps forming the agent trajectory.
input: The input to the agent.
reference: The reference answer.
**kwargs: Additional keyword arguments.
Returns:
The evaluation result.
"""
async def _aevaluate_agent_trajectory(
self,
*,
prediction: str,
agent_trajectory: Sequence[tuple[AgentAction, str]],
input: str, # noqa: A002
reference: str | None = None,
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate a trajectory.
Args:
prediction: The final predicted response.
agent_trajectory:
The intermediate steps forming the agent trajectory.
input: The input to the agent.
reference: The reference answer.
**kwargs: Additional keyword arguments.
Returns:
The evaluation result.
"""
return await run_in_executor(
None,
self._evaluate_agent_trajectory,
prediction=prediction,
agent_trajectory=agent_trajectory,
reference=reference,
input=input,
**kwargs,
)
def evaluate_agent_trajectory(
self,
*,
prediction: str,
agent_trajectory: Sequence[tuple[AgentAction, str]],
input: str, # noqa: A002
reference: str | None = None,
**kwargs: Any,
) -> dict:
"""Evaluate a trajectory.
Args:
prediction: The final predicted response.
agent_trajectory:
The intermediate steps forming the agent trajectory.
input: The input to the agent.
reference: The reference answer.
**kwargs: Additional keyword arguments.
Returns:
The evaluation result.
"""
self._check_evaluation_args(reference=reference, input_=input)
return self._evaluate_agent_trajectory(
prediction=prediction,
input=input,
agent_trajectory=agent_trajectory,
reference=reference,
**kwargs,
)
async def aevaluate_agent_trajectory(
self,
*,
prediction: str,
agent_trajectory: Sequence[tuple[AgentAction, str]],
input: str, # noqa: A002
reference: str | None = None,
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate a trajectory.
Args:
prediction: The final predicted response.
agent_trajectory:
The intermediate steps forming the agent trajectory.
input: The input to the agent.
reference: The reference answer.
**kwargs: Additional keyword arguments.
Returns:
The evaluation result.
"""
self._check_evaluation_args(reference=reference, input_=input)
return await self._aevaluate_agent_trajectory(
prediction=prediction,
input=input,
agent_trajectory=agent_trajectory,
reference=reference,
**kwargs,
)
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/evaluation/schema.py",
"license": "MIT License",
"lines": 441,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/scoring/eval_chain.py | """Base classes for scoring the output of a model on a scale of 1-10."""
from __future__ import annotations
import logging
import re
from typing import Any
from langchain_core.callbacks import Callbacks
from langchain_core.language_models import BaseLanguageModel
from langchain_core.output_parsers import BaseOutputParser
from langchain_core.prompts.prompt import PromptTemplate
from pydantic import ConfigDict, Field
from typing_extensions import override
from langchain_classic.chains.constitutional_ai.models import ConstitutionalPrinciple
from langchain_classic.chains.llm import LLMChain
from langchain_classic.evaluation.criteria.eval_chain import (
CRITERIA_TYPE,
Criteria,
)
from langchain_classic.evaluation.schema import LLMEvalChain, StringEvaluator
from langchain_classic.evaluation.scoring.prompt import (
CRITERIA_INSTRUCTIONS,
DEFAULT_CRITERIA,
SCORING_TEMPLATE,
SCORING_TEMPLATE_WITH_REFERENCE,
)
from langchain_classic.schema import RUN_KEY
logger = logging.getLogger(__name__)
_FIND_DOUBLE_BRACKETS = re.compile(r"\[\[(.*?)\]\]")
_SUPPORTED_CRITERIA = {
Criteria.CONCISENESS: "Is the submission concise and to the point?",
Criteria.RELEVANCE: "Is the submission referring to a real quote from the text?",
Criteria.CORRECTNESS: "Is the submission correct, accurate, and factual?",
Criteria.COHERENCE: "Is the submission coherent, well-structured, and organized?",
Criteria.HARMFULNESS: "Is the submission harmful, offensive, or inappropriate?",
Criteria.MALICIOUSNESS: "Is the submission malicious in any way?",
Criteria.HELPFULNESS: "Is the submission helpful, insightful, and appropriate?",
Criteria.CONTROVERSIALITY: "Is the submission controversial or debatable?",
Criteria.MISOGYNY: "Is the submission misogynistic or sexist?",
Criteria.CRIMINALITY: "Is the submission criminal in any way?",
Criteria.INSENSITIVITY: "Is the submission insensitive to any group of people?",
Criteria.DEPTH: "Does the submission demonstrate depth of thought?",
Criteria.CREATIVITY: "Does the submission demonstrate novelty or unique ideas?",
Criteria.DETAIL: "Does the submission demonstrate attention to detail?",
}
def resolve_criteria(
criteria: CRITERIA_TYPE | str | list[CRITERIA_TYPE] | None,
) -> dict:
"""Resolve the criteria for the pairwise evaluator.
Args:
criteria: The criteria to use.
Returns:
The resolved criteria.
"""
if criteria is None:
_default_criteria = [
Criteria.HELPFULNESS,
Criteria.RELEVANCE,
Criteria.CORRECTNESS,
Criteria.DEPTH,
]
return {k.value: _SUPPORTED_CRITERIA[k] for k in _default_criteria}
if isinstance(criteria, Criteria):
criteria_ = {criteria.value: _SUPPORTED_CRITERIA[criteria]}
elif isinstance(criteria, str):
if criteria in _SUPPORTED_CRITERIA:
criteria_ = {criteria: _SUPPORTED_CRITERIA[Criteria(criteria)]}
else:
criteria_ = {criteria: ""}
elif isinstance(criteria, ConstitutionalPrinciple):
criteria_ = {criteria.name: criteria.critique_request}
elif isinstance(criteria, (list, tuple)):
criteria_ = {
k: v
for criterion in criteria
for k, v in resolve_criteria(criterion).items()
}
else:
if not criteria:
msg = (
"Criteria cannot be empty. "
"Please provide a criterion name or a mapping of the criterion name"
" to its description."
)
raise ValueError(msg)
criteria_ = dict(criteria)
return criteria_
class ScoreStringResultOutputParser(BaseOutputParser[dict]):
"""A parser for the output of the ScoreStringEvalChain.
Attributes:
_type: The type of the output parser.
"""
@property
def _type(self) -> str:
"""Return the type of the output parser.
Returns:
The type of the output parser.
"""
return "pairwise_string_result"
def parse(self, text: str) -> dict[str, Any]:
"""Parse the output text.
Args:
text: The output text to parse.
Returns:
The parsed output.
Raises:
ValueError: If the verdict is invalid.
"""
match = _FIND_DOUBLE_BRACKETS.search(text)
if match:
verdict = match.group(1)
if not match or verdict not in [*list("123456789"), "10"]:
msg = (
f"Invalid output: {text}. "
"Output must contain a double bracketed string\
with the verdict between 1 and 10."
)
raise ValueError(msg)
return {
"reasoning": text,
"score": int(verdict),
}
class ScoreStringEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
"""A chain for scoring on a scale of 1-10 the output of a model.
Attributes:
output_parser (BaseOutputParser): The output parser for the chain.
Example:
>>> from langchain_openai import ChatOpenAI
>>> from langchain_classic.evaluation.scoring import ScoreStringEvalChain
>>> model = ChatOpenAI(temperature=0, model_name="gpt-4")
>>> chain = ScoreStringEvalChain.from_llm(llm=model)
>>> result = chain.evaluate_strings(
... input="What is the chemical formula for water?",
... prediction="H2O",
... reference="The chemical formula for water is H2O.",
... )
>>> print(result)
# {
# "score": 8,
# "comment": "The response accurately states "
# "that the chemical formula for water is H2O."
# "However, it does not provide an explanation of what the formula means."
# }
"""
output_key: str = "results"
output_parser: BaseOutputParser = Field(
default_factory=ScoreStringResultOutputParser,
)
normalize_by: float | None = None
"""The value to normalize the score by, if specified."""
criterion_name: str
"""The name of the criterion being evaluated."""
model_config = ConfigDict(
extra="ignore",
)
@classmethod
@override
def is_lc_serializable(cls) -> bool:
return False
@property
def requires_reference(self) -> bool:
"""Return whether the chain requires a reference.
Returns:
`True` if the chain requires a reference, `False` otherwise.
"""
return False
@property
def requires_input(self) -> bool:
"""Return whether the chain requires an input.
Returns:
`True` if the chain requires an input, `False` otherwise.
"""
return True
@property
def evaluation_name(self) -> str:
"""Get the name of the evaluation.
Returns:
-------
str
The name of the evaluation.
"""
return f"score_string:{self.criterion_name}"
@property
def _skip_reference_warning(self) -> str:
"""Return the warning to show when reference is ignored.
Returns:
The warning to show when reference is ignored.
"""
return (
f"Ignoring reference in {self.__class__.__name__}, as it is not expected."
"\nTo use a reference, use the LabeledScoreStringEvalChain instead."
" (EvaluatorType.LABELED_SCORE_STRING) instead."
)
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
*,
prompt: PromptTemplate | None = None,
criteria: CRITERIA_TYPE | str | None = None,
normalize_by: float | None = None,
**kwargs: Any,
) -> ScoreStringEvalChain:
"""Initialize the ScoreStringEvalChain from an LLM.
Args:
llm: The LLM to use (GPT-4 recommended).
prompt: The prompt to use.
criteria: The criteria to use.
normalize_by: The value to normalize the score by.
**kwargs: Additional keyword arguments.
Returns:
The initialized ScoreStringEvalChain.
Raises:
ValueError: If the input variables are not as expected.
"""
if not (hasattr(llm, "model_name") and not llm.model_name.startswith("gpt-4")):
logger.warning(
"This chain was only tested with GPT-4. \
Performance may be significantly worse with other models.",
)
expected_input_vars = {"prediction", "input", "criteria"}
prompt_ = prompt or SCORING_TEMPLATE.partial(reference="")
if expected_input_vars != set(prompt_.input_variables):
msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
raise ValueError(msg)
criteria_ = resolve_criteria(criteria)
criteria_str = "\n".join(
f"{k}: {v}" if v else k for k, v in criteria_.items()
).strip()
criteria_str = (
CRITERIA_INSTRUCTIONS + f"{criteria_str}\n"
if criteria_str
else DEFAULT_CRITERIA
)
return cls(
llm=llm,
prompt=prompt_.partial(criteria=criteria_str),
normalize_by=normalize_by,
criterion_name="-".join(criteria_),
**kwargs,
)
def _prepare_input(
self,
prediction: str,
input_: str | None,
reference: str | None,
) -> dict:
"""Prepare the input for the chain.
Args:
prediction: The output string from the first model.
prediction_b: The output string from the second model.
input_: The input or task string.
reference: The reference string, if any.
Returns:
The prepared input for the chain.
"""
input_dict = {
"prediction": prediction,
"input": input_,
}
if self.requires_reference:
input_dict["reference"] = reference
return input_dict
def _prepare_output(self, result: dict) -> dict:
"""Prepare the output."""
parsed = result[self.output_key]
if RUN_KEY in result:
parsed[RUN_KEY] = result[RUN_KEY]
if "score" in parsed and self.normalize_by is not None:
parsed["score"] = parsed["score"] / self.normalize_by
return parsed
@override
def _evaluate_strings(
self,
*,
prediction: str,
input: str | None = None,
reference: str | None = None,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Score the output string.
Args:
prediction: The output string from the first model.
input: The input or task string.
callbacks: The callbacks to use.
tags: Optional tags to use.
metadata: Optional metadata to use.
include_run_info: Whether to include run information in the output.
reference: The reference string, if any.
**kwargs: Additional keyword arguments.
Returns:
`dict` containing:
- reasoning: The reasoning for the preference.
- score: A score between 1 and 10.
"""
input_ = self._prepare_input(prediction, input, reference)
result = self(
inputs=input_,
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
@override
async def _aevaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
input: str | None = None,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Asynchronously score the output string.
Args:
prediction: The output string from the first model.
input: The input or task string.
callbacks: The callbacks to use.
tags: Optional tags to use.
metadata: Optional metadata to use.
include_run_info: Whether to include run information in the output.
reference: The reference string, if any.
**kwargs: Additional keyword arguments.
Returns:
`dict` containing:
- reasoning: The reasoning for the preference.
- score: A score between 1 and 10.
"""
input_ = self._prepare_input(prediction, input, reference)
result = await self.acall(
inputs=input_,
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
class LabeledScoreStringEvalChain(ScoreStringEvalChain):
"""A chain for scoring the output of a model on a scale of 1-10.
Attributes:
output_parser (BaseOutputParser): The output parser for the chain.
"""
@property
def requires_reference(self) -> bool:
"""Return whether the chain requires a reference.
Returns:
`True` if the chain requires a reference, `False` otherwise.
"""
return True
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
*,
prompt: PromptTemplate | None = None,
criteria: CRITERIA_TYPE | str | None = None,
normalize_by: float | None = None,
**kwargs: Any,
) -> LabeledScoreStringEvalChain:
"""Initialize the LabeledScoreStringEvalChain from an LLM.
Args:
llm: The LLM to use.
prompt: The prompt to use.
criteria: The criteria to use.
normalize_by: The value to normalize the score by.
**kwargs: Additional keyword arguments.
Returns:
The initialized LabeledScoreStringEvalChain.
Raises:
ValueError: If the input variables are not as expected.
"""
expected_input_vars = {
"prediction",
"input",
"reference",
"criteria",
}
prompt_ = prompt or SCORING_TEMPLATE_WITH_REFERENCE
if expected_input_vars != set(prompt_.input_variables):
msg = (
f"Input variables should be {expected_input_vars}, "
f"but got {prompt_.input_variables}"
)
raise ValueError(msg)
criteria_ = resolve_criteria(criteria)
criteria_str = "\n".join(f"{k}: {v}" for k, v in criteria_.items()).strip()
criteria_str = (
CRITERIA_INSTRUCTIONS + f"{criteria_str}\n"
if criteria_str
else DEFAULT_CRITERIA
)
return cls(
llm=llm,
prompt=prompt_.partial(criteria=criteria_str),
normalize_by=normalize_by,
criterion_name="-".join(criteria_),
**kwargs,
)
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/evaluation/scoring/eval_chain.py",
"license": "MIT License",
"lines": 407,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/string_distance/base.py | """String distance evaluators based on the RapidFuzz library."""
from collections.abc import Callable
from enum import Enum
from typing import Any
from langchain_core.callbacks import Callbacks
from langchain_core.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)
from langchain_core.utils import pre_init
from pydantic import Field
from typing_extensions import override
from langchain_classic.chains.base import Chain
from langchain_classic.evaluation.schema import PairwiseStringEvaluator, StringEvaluator
from langchain_classic.schema import RUN_KEY
def _load_rapidfuzz() -> Any:
"""Load the RapidFuzz library.
Raises:
ImportError: If the rapidfuzz library is not installed.
Returns:
The `rapidfuzz.distance` module.
"""
try:
import rapidfuzz
except ImportError as e:
msg = (
"Please install the rapidfuzz library to use the FuzzyMatchStringEvaluator."
"Please install it with `pip install rapidfuzz`."
)
raise ImportError(msg) from e
return rapidfuzz.distance
class StringDistance(str, Enum):
"""Distance metric to use.
Attributes:
`DAMERAU_LEVENSHTEIN`: The Damerau-Levenshtein distance.
`LEVENSHTEIN`: The Levenshtein distance.
`JARO`: The Jaro distance.
`JARO_WINKLER`: The Jaro-Winkler distance.
`HAMMING`: The Hamming distance.
`INDEL`: The Indel distance.
"""
DAMERAU_LEVENSHTEIN = "damerau_levenshtein"
LEVENSHTEIN = "levenshtein"
JARO = "jaro"
JARO_WINKLER = "jaro_winkler"
HAMMING = "hamming"
INDEL = "indel"
class _RapidFuzzChainMixin(Chain):
"""Shared methods for the rapidfuzz string distance evaluators."""
distance: StringDistance = Field(default=StringDistance.JARO_WINKLER)
normalize_score: bool = Field(default=True)
"""Whether to normalize the score to a value between `0` and `1`.
Applies only to the Levenshtein and Damerau-Levenshtein distances."""
@pre_init
def validate_dependencies(cls, values: dict[str, Any]) -> dict[str, Any]:
"""Validate that the rapidfuzz library is installed.
Args:
values: The input values.
Returns:
The validated values.
"""
_load_rapidfuzz()
return values
@property
def output_keys(self) -> list[str]:
"""Get the output keys.
Returns:
The output keys.
"""
return ["score"]
def _prepare_output(self, result: dict[str, Any]) -> dict[str, Any]:
"""Prepare the output dictionary.
Args:
result: The evaluation results.
Returns:
The prepared output dictionary.
"""
result = {"score": result["score"]}
if RUN_KEY in result:
result[RUN_KEY] = result[RUN_KEY].dict()
return result
@staticmethod
def _get_metric(distance: str, *, normalize_score: bool = False) -> Callable:
"""Get the distance metric function based on the distance type.
Args:
distance: The distance type.
normalize_score: Whether to normalize the score.
Returns:
The distance metric function.
Raises:
ValueError: If the distance metric is invalid.
"""
from rapidfuzz import distance as rf_distance
module_map: dict[str, Any] = {
StringDistance.DAMERAU_LEVENSHTEIN: rf_distance.DamerauLevenshtein,
StringDistance.LEVENSHTEIN: rf_distance.Levenshtein,
StringDistance.JARO: rf_distance.Jaro,
StringDistance.JARO_WINKLER: rf_distance.JaroWinkler,
StringDistance.HAMMING: rf_distance.Hamming,
StringDistance.INDEL: rf_distance.Indel,
}
if distance not in module_map:
msg = (
f"Invalid distance metric: {distance}"
f"\nMust be one of: {list(StringDistance)}"
)
raise ValueError(msg)
module = module_map[distance]
if normalize_score:
return module.normalized_distance
return module.distance
@property
def metric(self) -> Callable:
"""Get the distance metric function.
Returns:
The distance metric function.
"""
return _RapidFuzzChainMixin._get_metric(
self.distance,
normalize_score=self.normalize_score,
)
def compute_metric(self, a: str, b: str) -> float:
"""Compute the distance between two strings.
Args:
a: The first string.
b: The second string.
Returns:
The distance between the two strings.
"""
return self.metric(a, b)
class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):
"""Compute string distances between the prediction and the reference.
Examples:
----------
>>> from langchain_classic.evaluation import StringDistanceEvalChain
>>> evaluator = StringDistanceEvalChain()
>>> evaluator.evaluate_strings(
prediction="Mindy is the CTO",
reference="Mindy is the CEO",
)
Using the `load_evaluator` function:
>>> from langchain_classic.evaluation import load_evaluator
>>> evaluator = load_evaluator("string_distance")
>>> evaluator.evaluate_strings(
prediction="The answer is three",
reference="three",
)
"""
@property
def requires_input(self) -> bool:
"""This evaluator does not require input."""
return False
@property
def requires_reference(self) -> bool:
"""This evaluator does not require a reference."""
return True
@property
def input_keys(self) -> list[str]:
"""Get the input keys.
Returns:
The input keys.
"""
return ["reference", "prediction"]
@property
def evaluation_name(self) -> str:
"""Get the evaluation name.
Returns:
The evaluation name.
"""
return f"{self.distance.value}_distance"
@override
def _call(
self,
inputs: dict[str, Any],
run_manager: CallbackManagerForChainRun | None = None,
) -> dict[str, Any]:
"""Compute the string distance between the prediction and the reference.
Args:
inputs: The input values.
run_manager: The callback manager.
Returns:
The evaluation results containing the score.
"""
return {"score": self.compute_metric(inputs["reference"], inputs["prediction"])}
@override
async def _acall(
self,
inputs: dict[str, Any],
run_manager: AsyncCallbackManagerForChainRun | None = None,
) -> dict[str, Any]:
"""Compute the string distance between the prediction and the reference.
Args:
inputs: The input values.
run_manager: The callback manager.
Returns:
The evaluation results containing the score.
"""
return {"score": self.compute_metric(inputs["reference"], inputs["prediction"])}
@override
def _evaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
input: str | None = None,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate the string distance between the prediction and the reference.
Args:
prediction: The prediction string.
reference: The reference string.
input: The input string.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run info in the output.
**kwargs: Additional keyword arguments.
Returns:
The evaluation results containing the score.
"""
result = self(
inputs={"prediction": prediction, "reference": reference},
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
@override
async def _aevaluate_strings(
self,
*,
prediction: str,
reference: str | None = None,
input: str | None = None,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate the string distance between the prediction and the reference.
Args:
prediction: The prediction string.
reference: The reference string.
input: The input string.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to apply.
include_run_info: Whether to include run info in the output.
**kwargs: Additional keyword arguments.
Returns:
The evaluation results containing the score.
"""
result = await self.acall(
inputs={"prediction": prediction, "reference": reference},
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMixin):
"""Compute string edit distances between two predictions."""
@property
def input_keys(self) -> list[str]:
"""Get the input keys.
Returns:
The input keys.
"""
return ["prediction", "prediction_b"]
@property
def evaluation_name(self) -> str:
"""Get the evaluation name.
Returns:
The evaluation name.
"""
return f"pairwise_{self.distance.value}_distance"
@override
def _call(
self,
inputs: dict[str, Any],
run_manager: CallbackManagerForChainRun | None = None,
) -> dict[str, Any]:
"""Compute the string distance between two predictions.
Args:
inputs: The input values.
run_manager: The callback manager.
Returns:
The evaluation results containing the score.
"""
return {
"score": self.compute_metric(inputs["prediction"], inputs["prediction_b"]),
}
@override
async def _acall(
self,
inputs: dict[str, Any],
run_manager: AsyncCallbackManagerForChainRun | None = None,
) -> dict[str, Any]:
"""Asynchronously compute the string distance between two predictions.
Args:
inputs: The input values.
run_manager: The callback manager.
Returns:
The evaluation results containing the score.
"""
return {
"score": self.compute_metric(inputs["prediction"], inputs["prediction_b"]),
}
@override
def _evaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate the string distance between two predictions.
Args:
prediction: The first prediction string.
prediction_b: The second prediction string.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run info in the output.
**kwargs: Additional keyword arguments.
Returns:
The evaluation results containing the score.
"""
result = self(
inputs={"prediction": prediction, "prediction_b": prediction_b},
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
@override
async def _aevaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
callbacks: Callbacks = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate the string distance between two predictions.
Args:
prediction: The first prediction string.
prediction_b: The second prediction string.
callbacks: The callbacks to use.
tags: The tags to apply.
metadata: The metadata to use.
include_run_info: Whether to include run info in the output.
**kwargs: Additional keyword arguments.
Returns:
The evaluation results containing the score.
"""
result = await self.acall(
inputs={"prediction": prediction, "prediction_b": prediction_b},
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/evaluation/string_distance/base.py",
"license": "MIT License",
"lines": 378,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
langchain-ai/langchain:libs/langchain/langchain_classic/graphs/hugegraph.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.graphs import HugeGraph
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"HugeGraph": "langchain_community.graphs"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"HugeGraph",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/graphs/hugegraph.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/indexes/vectorstore.py | """Vectorstore stubs for the indexing api."""
from typing import Any
from langchain_core.document_loaders import BaseLoader
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.language_models import BaseLanguageModel
from langchain_core.vectorstores import VectorStore
from langchain_text_splitters import RecursiveCharacterTextSplitter, TextSplitter
from pydantic import BaseModel, ConfigDict, Field
from langchain_classic.chains.qa_with_sources.retrieval import (
RetrievalQAWithSourcesChain,
)
from langchain_classic.chains.retrieval_qa.base import RetrievalQA
def _get_default_text_splitter() -> TextSplitter:
"""Return the default text splitter used for chunking documents."""
return RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
class VectorStoreIndexWrapper(BaseModel):
"""Wrapper around a `VectorStore` for easy access."""
vectorstore: VectorStore
model_config = ConfigDict(
arbitrary_types_allowed=True,
extra="forbid",
)
def query(
self,
question: str,
llm: BaseLanguageModel | None = None,
retriever_kwargs: dict[str, Any] | None = None,
**kwargs: Any,
) -> str:
"""Query the `VectorStore` using the provided LLM.
Args:
question: The question or prompt to query.
llm: The language model to use. Must not be `None`.
retriever_kwargs: Optional keyword arguments for the retriever.
**kwargs: Additional keyword arguments forwarded to the chain.
Returns:
The result string from the RetrievalQA chain.
"""
if llm is None:
msg = (
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"model = OpenAI(temperature=0)"
)
raise NotImplementedError(msg)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQA.from_chain_type(
llm,
retriever=self.vectorstore.as_retriever(**retriever_kwargs),
**kwargs,
)
return chain.invoke({chain.input_key: question})[chain.output_key]
async def aquery(
self,
question: str,
llm: BaseLanguageModel | None = None,
retriever_kwargs: dict[str, Any] | None = None,
**kwargs: Any,
) -> str:
"""Asynchronously query the `VectorStore` using the provided LLM.
Args:
question: The question or prompt to query.
llm: The language model to use. Must not be `None`.
retriever_kwargs: Optional keyword arguments for the retriever.
**kwargs: Additional keyword arguments forwarded to the chain.
Returns:
The asynchronous result string from the RetrievalQA chain.
"""
if llm is None:
msg = (
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"model = OpenAI(temperature=0)"
)
raise NotImplementedError(msg)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQA.from_chain_type(
llm,
retriever=self.vectorstore.as_retriever(**retriever_kwargs),
**kwargs,
)
return (await chain.ainvoke({chain.input_key: question}))[chain.output_key]
def query_with_sources(
self,
question: str,
llm: BaseLanguageModel | None = None,
retriever_kwargs: dict[str, Any] | None = None,
**kwargs: Any,
) -> dict:
"""Query the `VectorStore` and retrieve the answer along with sources.
Args:
question: The question or prompt to query.
llm: The language model to use. Must not be `None`.
retriever_kwargs: Optional keyword arguments for the retriever.
**kwargs: Additional keyword arguments forwarded to the chain.
Returns:
`dict` containing the answer and source documents.
"""
if llm is None:
msg = (
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"model = OpenAI(temperature=0)"
)
raise NotImplementedError(msg)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQAWithSourcesChain.from_chain_type(
llm,
retriever=self.vectorstore.as_retriever(**retriever_kwargs),
**kwargs,
)
return chain.invoke({chain.question_key: question})
async def aquery_with_sources(
self,
question: str,
llm: BaseLanguageModel | None = None,
retriever_kwargs: dict[str, Any] | None = None,
**kwargs: Any,
) -> dict:
"""Asynchronously query the `VectorStore` and retrieve the answer and sources.
Args:
question: The question or prompt to query.
llm: The language model to use. Must not be `None`.
retriever_kwargs: Optional keyword arguments for the retriever.
**kwargs: Additional keyword arguments forwarded to the chain.
Returns:
`dict` containing the answer and source documents.
"""
if llm is None:
msg = (
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"model = OpenAI(temperature=0)"
)
raise NotImplementedError(msg)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQAWithSourcesChain.from_chain_type(
llm,
retriever=self.vectorstore.as_retriever(**retriever_kwargs),
**kwargs,
)
return await chain.ainvoke({chain.question_key: question})
def _get_in_memory_vectorstore() -> type[VectorStore]:
"""Get the `InMemoryVectorStore`."""
import warnings
try:
from langchain_community.vectorstores.inmemory import InMemoryVectorStore
except ImportError as e:
msg = "Please install langchain-community to use the InMemoryVectorStore."
raise ImportError(msg) from e
warnings.warn(
"Using InMemoryVectorStore as the default vectorstore."
"This memory store won't persist data. You should explicitly"
"specify a VectorStore when using VectorstoreIndexCreator",
stacklevel=3,
)
return InMemoryVectorStore
class VectorstoreIndexCreator(BaseModel):
"""Logic for creating indexes."""
vectorstore_cls: type[VectorStore] = Field(
default_factory=_get_in_memory_vectorstore,
)
embedding: Embeddings
text_splitter: TextSplitter = Field(default_factory=_get_default_text_splitter)
vectorstore_kwargs: dict = Field(default_factory=dict)
model_config = ConfigDict(
arbitrary_types_allowed=True,
extra="forbid",
)
def from_loaders(self, loaders: list[BaseLoader]) -> VectorStoreIndexWrapper:
"""Create a `VectorStore` index from a list of loaders.
Args:
loaders: A list of `BaseLoader` instances to load documents.
Returns:
A `VectorStoreIndexWrapper` containing the constructed vectorstore.
"""
docs = []
for loader in loaders:
docs.extend(loader.load())
return self.from_documents(docs)
async def afrom_loaders(self, loaders: list[BaseLoader]) -> VectorStoreIndexWrapper:
"""Asynchronously create a `VectorStore` index from a list of loaders.
Args:
loaders: A list of `BaseLoader` instances to load documents.
Returns:
A `VectorStoreIndexWrapper` containing the constructed vectorstore.
"""
docs = []
for loader in loaders:
docs.extend([doc async for doc in loader.alazy_load()])
return await self.afrom_documents(docs)
def from_documents(self, documents: list[Document]) -> VectorStoreIndexWrapper:
"""Create a `VectorStore` index from a list of documents.
Args:
documents: A list of `Document` objects.
Returns:
A `VectorStoreIndexWrapper` containing the constructed vectorstore.
"""
sub_docs = self.text_splitter.split_documents(documents)
vectorstore = self.vectorstore_cls.from_documents(
sub_docs,
self.embedding,
**self.vectorstore_kwargs,
)
return VectorStoreIndexWrapper(vectorstore=vectorstore)
async def afrom_documents(
self,
documents: list[Document],
) -> VectorStoreIndexWrapper:
"""Asynchronously create a `VectorStore` index from a list of documents.
Args:
documents: A list of `Document` objects.
Returns:
A `VectorStoreIndexWrapper` containing the constructed vectorstore.
"""
sub_docs = self.text_splitter.split_documents(documents)
vectorstore = await self.vectorstore_cls.afrom_documents(
sub_docs,
self.embedding,
**self.vectorstore_kwargs,
)
return VectorStoreIndexWrapper(vectorstore=vectorstore)
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/indexes/vectorstore.py",
"license": "MIT License",
"lines": 231,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/aleph_alpha.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import AlephAlpha
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"AlephAlpha": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"AlephAlpha",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/aleph_alpha.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/anthropic.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import Anthropic
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"Anthropic": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"Anthropic",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/anthropic.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/anyscale.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import Anyscale
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"Anyscale": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"Anyscale",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/anyscale.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/arcee.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import Arcee
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"Arcee": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"Arcee",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/arcee.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/azureml_endpoint.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import AzureMLOnlineEndpoint
from langchain_community.llms.azureml_endpoint import (
AzureMLEndpointClient,
ContentFormatterBase,
CustomOpenAIContentFormatter,
DollyContentFormatter,
GPT2ContentFormatter,
HFContentFormatter,
OSSContentFormatter,
)
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"AzureMLEndpointClient": "langchain_community.llms.azureml_endpoint",
"ContentFormatterBase": "langchain_community.llms.azureml_endpoint",
"GPT2ContentFormatter": "langchain_community.llms.azureml_endpoint",
"OSSContentFormatter": "langchain_community.llms.azureml_endpoint",
"HFContentFormatter": "langchain_community.llms.azureml_endpoint",
"DollyContentFormatter": "langchain_community.llms.azureml_endpoint",
"CustomOpenAIContentFormatter": "langchain_community.llms.azureml_endpoint",
"AzureMLOnlineEndpoint": "langchain_community.llms",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"AzureMLEndpointClient",
"AzureMLOnlineEndpoint",
"ContentFormatterBase",
"CustomOpenAIContentFormatter",
"DollyContentFormatter",
"GPT2ContentFormatter",
"HFContentFormatter",
"OSSContentFormatter",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/azureml_endpoint.py",
"license": "MIT License",
"lines": 40,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/baidu_qianfan_endpoint.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import QianfanLLMEndpoint
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"QianfanLLMEndpoint": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"QianfanLLMEndpoint",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/baidu_qianfan_endpoint.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/bedrock.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import Bedrock
from langchain_community.llms.bedrock import BedrockBase
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"BedrockBase": "langchain_community.llms.bedrock",
"Bedrock": "langchain_community.llms",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"Bedrock",
"BedrockBase",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/bedrock.py",
"license": "MIT License",
"lines": 20,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/clarifai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import Clarifai
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"Clarifai": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"Clarifai",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/clarifai.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/cloudflare_workersai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms.cloudflare_workersai import CloudflareWorkersAI
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"CloudflareWorkersAI": "langchain_community.llms.cloudflare_workersai",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"CloudflareWorkersAI",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/cloudflare_workersai.py",
"license": "MIT License",
"lines": 17,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/cohere.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import Cohere
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"Cohere": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"Cohere",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/cohere.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/databricks.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import Databricks
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"Databricks": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"Databricks",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/databricks.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/deepinfra.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import DeepInfra
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"DeepInfra": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"DeepInfra",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/deepinfra.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/edenai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import EdenAI
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"EdenAI": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"EdenAI",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/edenai.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/fake.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms.fake import FakeStreamingListLLM
from langchain_core.language_models import FakeListLLM
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"FakeListLLM": "langchain_community.llms",
"FakeStreamingListLLM": "langchain_community.llms.fake",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"FakeListLLM",
"FakeStreamingListLLM",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/fake.py",
"license": "MIT License",
"lines": 20,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/fireworks.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import Fireworks
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"Fireworks": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"Fireworks",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/fireworks.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/gigachat.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import GigaChat
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"GigaChat": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"GigaChat",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/gigachat.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/google_palm.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import GooglePalm
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"GooglePalm": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"GooglePalm",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/google_palm.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/gpt4all.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import GPT4All
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"GPT4All": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"GPT4All",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/gpt4all.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/gradient_ai.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import GradientLLM
from langchain_community.llms.gradient_ai import TrainResult
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"TrainResult": "langchain_community.llms.gradient_ai",
"GradientLLM": "langchain_community.llms",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"GradientLLM",
"TrainResult",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/gradient_ai.py",
"license": "MIT License",
"lines": 20,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
langchain-ai/langchain:libs/langchain/langchain_classic/llms/huggingface_hub.py | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.llms import HuggingFaceHub
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {"HuggingFaceHub": "langchain_community.llms"}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"HuggingFaceHub",
]
| {
"repo_id": "langchain-ai/langchain",
"file_path": "libs/langchain/langchain_classic/llms/huggingface_hub.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.