id
stringlengths
14
15
text
stringlengths
49
2.47k
source
stringlengths
61
166
a228a16b6200-1
""" [docs] def __init__( self, connection_string: str, embedding_function: Embeddings, embedding_dimension: int = _LANGCHAIN_DEFAULT_EMBEDDING_DIM, collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, pre_delete_collection: bool = False, logger: Optional[...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
a228a16b6200-2
Table( self.collection_name, Base.metadata, Column("id", TEXT, primary_key=True, default=uuid.uuid4), Column("embedding", ARRAY(REAL)), Column("document", String, nullable=True), Column("metadata", JSON, nullable=True), extend_existing=...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
a228a16b6200-3
metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, batch_size: int = 500, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
a228a16b6200-4
conn.execute(insert(chunks_table).values(chunks_table_data)) # Clear the chunks_table_data list for the next batch chunks_table_data.clear() # Insert any remaining records that didn't make up a full batch if chunks_table_data: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
a228a16b6200-5
List of Documents most similar to the query and score for each """ embedding = self.embedding_function.embed_query(query) docs = self.similarity_search_with_score_by_vector( embedding=embedding, k=k, filter=filter ) return docs [docs] def similarity_search_with_sco...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
a228a16b6200-6
Document( page_content=result.document, metadata=result.metadata, ), result.distance if self.embedding_function is not None else None, ) for result in results ] return documents_with_scores [docs] def simi...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
a228a16b6200-7
) try: with self.engine.connect() as conn: with conn.begin(): delete_condition = chunks_table.c.id.in_(ids) conn.execute(chunks_table.delete().where(delete_condition)) return True except Exception as e: p...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
a228a16b6200-8
data=kwargs, key="connection_string", env_key="PG_CONNECTION_STRING", ) if not connection_string: raise ValueError( "Postgres connection string is required" "Either pass it as a parameter" "or set the PG_CONNECTION_STRIN...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
a228a16b6200-9
cls, driver: str, host: str, port: int, database: str, user: str, password: str, ) -> str: """Return connection string from database parameters.""" return f"postgresql+{driver}://{user}:{password}@{host}:{port}/{database}"
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
df97436ddf64-0
Source code for langchain.vectorstores.usearch """Wrapper around USearch vector database.""" from __future__ import annotations from typing import Any, Dict, Iterable, List, Optional, Tuple import numpy as np from langchain.docstore.base import AddableMixin, Docstore from langchain.docstore.document import Document fro...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html
df97436ddf64-1
Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of unique IDs. Returns: List of ids from adding the texts into the vectorstore. """ if not isinstance(se...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html
df97436ddf64-2
matches = self.index.search(np.array(query_embedding), k) docs_with_scores: List[Tuple[Document, float]] = [] for id, score in zip(matches.keys, matches.distances): doc = self.docstore.search(str(id)) if not isinstance(doc, Document): raise ValueError(f"Could not ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html
df97436ddf64-3
This is a user friendly interface that: 1. Embeds documents. 2. Creates an in memory docstore 3. Initializes the USearch database This is intended to be a quick way to get started. Example: .. code-block:: python from langchain.vectorstores...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/usearch.html
261e3a672496-0
Source code for langchain.vectorstores.pgembedding """VectorStore wrapper around a Postgres database.""" from __future__ import annotations import logging import uuid from typing import Any, Dict, Iterable, List, Optional, Tuple, Type import sqlalchemy from sqlalchemy import func from sqlalchemy.dialects.postgresql imp...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
261e3a672496-1
""" created = False collection = cls.get_by_name(session, name) if collection: return collection, created collection = cls(name=name, cmetadata=cmetadata) session.add(collection) session.commit() created = True return collection, created [docs]...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
261e3a672496-2
The tables will be created when initializing the store (if not exists) So, make sure the user has the right permissions to create tables. - `distance_strategy` is the distance strategy to use. (default: EUCLIDEAN) - `EUCLIDEAN` is the euclidean distance. - `pre_delete_collection` if True, wi...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
261e3a672496-3
statement = sqlalchemy.text("CREATE EXTENSION IF NOT EXISTS embedding") session.execute(statement) session.commit() except Exception as e: self.logger.exception(e) [docs] def create_tables_if_not_exists(self) -> None: with self._conn.begin(): Ba...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
261e3a672496-4
session.commit() print("HNSW extension and index created successfully.") except Exception as e: print(f"Failed to create HNSW extension or index: {e}") [docs] def delete_collection(self) -> None: self.logger.debug("Trying to delete collection") with Session(self._conn)...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
261e3a672496-5
) return store [docs] def add_embeddings( self, texts: List[str], embeddings: List[List[float]], metadatas: List[dict], ids: List[str], **kwargs: Any, ) -> None: with Session(self._conn) as session: collection = self.get_collection(sessi...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
261e3a672496-6
cmetadata=metadata, custom_id=id, ) collection.embeddings.append(embedding_store) session.add(embedding_store) session.commit() return ids [docs] def similarity_search( self, query: str, k: int = 4, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
261e3a672496-7
filter_clauses = [] for key, value in filter.items(): IN = "in" if isinstance(value, dict) and IN in map(str.lower, value): value_case_insensitive = { k.lower(): v for k, v in value.items() ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
261e3a672496-8
filter: Optional[dict] = None, **kwargs: Any, ) -> List[Document]: docs_and_scores = self.similarity_search_with_score_by_vector( embedding=embedding, k=k, filter=filter ) return [doc for doc, _ in docs_and_scores] [docs] @classmethod def from_texts( cls: T...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
261e3a672496-9
texts, embeddings, embedding, metadatas=metadatas, ids=ids, collection_name=collection_name, pre_delete_collection=pre_delete_collection, **kwargs, ) [docs] @classmethod def from_existing_index( cls: Type[PGEmbedd...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
261e3a672496-10
texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] connection_string = cls.get_connection_string(kwargs) kwargs["connection_string"] = connection_string return cls.from_texts( texts=texts, pre_delete_collection=pre_delete_colle...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/pgembedding.html
1560d88cc7ae-0
Source code for langchain.vectorstores.utils """Utility functions for working with vectors and vectorstores.""" from enum import Enum from typing import List import numpy as np from langchain.utils.math import cosine_similarity [docs]class DistanceStrategy(str, Enum): """Enumerator of the Distance strategies for ca...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/utils.html
1560d88cc7ae-1
lambda_mult * query_score - (1 - lambda_mult) * redundant_score ) if equation_score > best_score: best_score = equation_score idx_to_add = i idxs.append(idx_to_add) selected = np.append(selected, [embedding_list[idx_to_add]], axis=0) return idx...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/utils.html
690d40f85fff-0
Source code for langchain.vectorstores.deeplake """Wrapper around Activeloop Deep Lake.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union import numpy as np try: import deeplake from deeplake.core.fast_forwarding import version_co...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-1
vectorstore = DeepLake("langchain_store", embeddings.embed_query) """ _LANGCHAIN_DEFAULT_DEEPLAKE_PATH = "./deeplake/" [docs] def __init__( self, dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH, token: Optional[str] = None, embedding: Optional[Embeddings] = None, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-2
either documents or query. Optional. embedding_function (Embeddings, optional): Function to convert either documents or query. Optional. Deprecated: keeping this parameter for backwards compatibility. read_only (bool): Open dataset in read-only mode. Default is Fa...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-3
""" self.ingestion_batch_size = ingestion_batch_size self.num_workers = num_workers self.verbose = verbose if _DEEPLAKE_INSTALLED is False: raise ValueError( "Could not import deeplake python package. " "Please install it with `pip install deep...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-4
**kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Examples: >>> ids = deeplake_vectorstore.add_texts( ... texts = <list_of_texts>, ... metadatas = <list_of_metadata_jsons>, ... ids = <list_o...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-5
return self.vectorstore.add( text=texts, metadata=metadatas, embedding_data=texts, embedding_tensor="embedding", embedding_function=self._embedding_function.embed_documents, # type: ignore return_ids=True, **kwargs, ) def _...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-6
""" result = self.vectorstore.search( query=tql, exec_option=exec_option, ) metadatas = result["metadata"] texts = result["text"] docs = [ Document( page_content=text, metadata=metadata, ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-7
into embedding. k (int): Number of Documents to return. distance_metric (str): `L2` for Euclidean, `L1` for Nuclear, `max` for L-infinity distance, `cos` for cosine similarity, 'dot' for dot product. filter (Union[Dict, Callable], optional): Additional...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-8
if return_score True, return a tuple of (Document, score) Raises: ValueError: if both `embedding` and `embedding_function` are not specified. """ if kwargs.get("tql"): return self._search_tql( tql=kwargs["tql"], exec_option=exec_option, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-9
) scores = result["score"] embeddings = result["embedding"] metadatas = result["metadata"] texts = result["text"] if use_maximal_marginal_relevance: lambda_mult = kwargs.get("lambda_mult", 0.5) indices = maximal_marginal_relevance( # type: ignore ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-10
... exec_option="compute_engine", ... ) Args: k (int): Number of Documents to return. Defaults to 4. query (str): Text to look up similar documents. **kwargs: Additional keyword arguments include: embedding (Callable): Embedding function to use...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-11
k=k, use_maximal_marginal_relevance=False, return_score=False, **kwargs, ) [docs] def similarity_search_by_vector( self, embedding: Union[List[float], np.ndarray], k: int = 4, **kwargs: Any, ) -> List[Document]: """ Retur...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-12
- "compute_engine" - Performant C++ implementation of the Deep Lake Compute Engine. Runs on the client and can be used for any data stored in or connected to Deep Lake. It cannot be used with in-memory or local datasets. - "tens...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-13
... ) Args: query (str): Query text to search for. k (int): Number of results to return. Defaults to 4. **kwargs: Additional keyword arguments. Some of these arguments are: distance_metric: `L2` for Euclidean, `L1` for Nuclear, `max` L-infinity ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-14
text with distance in float.""" return self._search( query=query, k=k, return_score=True, **kwargs, ) [docs] def max_marginal_relevance_search_by_vector( self, embedding: List[float], k: int = 4, fetch_k: int = 20, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-15
option with big datasets is discouraged due to potential memory issues. - "compute_engine" - Performant C++ implementation of the Deep Lake Compute Engine. Runs on the client and can be used for any data stored in or connected to Deep Lake. It ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-16
... embedding_function = <embedding_function_for_query>, ... k = <number_of_items_to_return>, ... exec_option = <preferred_exec_option>, ... ) Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-17
"For MMR search, you must specify an embedding function on" " `creation` or during add call." ) return self._search( query=query, k=k, fetch_k=fetch_k, use_maximal_marginal_relevance=True, lambda_mult=lambda_mult, ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-18
(use 'activeloop login' from command line) - AWS S3 path of the form ``s3://bucketname/path/to/dataset``. Credentials are required in either the environment - Google Cloud Storage path of the form ``gcs://bucketname/path/to/dataset`` Credentials ar...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
690d40f85fff-19
Defaults to None. **kwargs: Other keyword arguments that subclasses might use. - filter (Optional[Dict[str, str]], optional): The filter to delete by. - delete_all (Optional[bool], optional): Whether to drop the dataset. Returns: bool: Whether the delete o...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
6d17fcab96b4-0
Source code for langchain.vectorstores.docarray.in_memory """Wrapper around in-memory storage.""" from __future__ import annotations from typing import Any, Dict, List, Literal, Optional from langchain.embeddings.base import Embeddings from langchain.vectorstores.docarray.base import ( DocArrayIndex, _check_doc...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html
6d17fcab96b4-1
[docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, **kwargs: Any, ) -> DocArrayInMemorySearch: """Create an DocArrayInMemorySearch store and insert data. Args: ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html
010a2af88363-0
Source code for langchain.vectorstores.docarray.base from abc import ABC from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type import numpy as np from pydantic import Field from langchain.embeddings.base import Embeddings from langchain.schema import Document from langchain.vectorstores import Ve...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html
010a2af88363-1
from docarray import BaseDoc from docarray.typing import NdArray class DocArrayDoc(BaseDoc): text: Optional[str] embedding: Optional[NdArray] = Field(**embeddings_params) metadata: Optional[dict] return DocArrayDoc @property def doc_cls(self) -> Type["...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html
010a2af88363-2
Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of documents most similar to the query text and cosine distance in float for each. Lower score represents more similarity. """ ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html
010a2af88363-3
""" raise NotImplementedError() [docs] def similarity_search_by_vector( self, embedding: List[float], k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs most similar to embedding vector. Args: embedding: Embedding to look up documents similar to. ...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html
010a2af88363-4
Returns: List of Documents selected by maximal marginal relevance. """ query_embedding = self.embedding.embed_query(query) query_doc = self.doc_cls(embedding=query_embedding) # type: ignore docs = self.doc_index.find( query_doc, search_field="embedding", limit=fe...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/base.html
23ed39564530-0
Source code for langchain.vectorstores.docarray.hnsw """Wrapper around Hnswlib store.""" from __future__ import annotations from typing import Any, List, Literal, Optional from langchain.embeddings.base import Embeddings from langchain.vectorstores.docarray.base import ( DocArrayIndex, _check_docarray_import, )...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
23ed39564530-1
"cosine", "ip", and "l2". Defaults to "cosine". max_elements (int): Maximum number of vectors that can be stored. Defaults to 1024. index (bool): Whether an index should be built for this field. Defaults to True. ef_construction (int): defines a constr...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
23ed39564530-2
work_dir: Optional[str] = None, n_dim: Optional[int] = None, **kwargs: Any, ) -> DocArrayHnswSearch: """Create an DocArrayHnswSearch store and insert data. Args: texts (List[str]): Text data. embedding (Embeddings): Embedding function. metadatas (O...
https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
2e87736f77b4-0
Source code for langchain.storage.in_memory """In memory store that is not thread safe and has no eviction policy. This is a simple implementation of the BaseStore using a dictionary that is useful primarily for unit testing purposes. """ from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple from lang...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/in_memory.html
2e87736f77b4-1
""" return [self.store.get(key) for key in keys] [docs] def mset(self, key_value_pairs: Sequence[Tuple[str, Any]]) -> None: """Set the values for the given keys. Args: key_value_pairs (Sequence[Tuple[str, V]]): A sequence of key-value pairs. Returns: None ...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/in_memory.html
4575267863d3-0
Source code for langchain.storage.file_system import re from pathlib import Path from typing import Iterator, List, Optional, Sequence, Tuple, Union from langchain.schema import BaseStore from langchain.storage.exceptions import InvalidKeyException [docs]class LocalFileStore(BaseStore[str, bytes]): """BaseStore int...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html
4575267863d3-1
Returns: Path: The full path for the given key. """ if not re.match(r"^[a-zA-Z0-9_.\-/]+$", key): raise InvalidKeyException(f"Invalid characters in key: {key}") return self.root_path / key [docs] def mget(self, keys: Sequence[str]) -> List[Optional[bytes]]: """...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html
4575267863d3-2
for key in keys: full_path = self._get_full_path(key) if full_path.exists(): full_path.unlink() [docs] def yield_keys(self, prefix: Optional[str] = None) -> Iterator[str]: """Get an iterator over keys that match the given prefix. Args: prefix (Optio...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html
6083b6367f0b-0
Source code for langchain.storage.encoder_backed from typing import ( Any, Callable, Iterator, List, Optional, Sequence, Tuple, TypeVar, Union, ) from langchain.schema import BaseStore K = TypeVar("K") V = TypeVar("V") [docs]class EncoderBackedStore(BaseStore[K, V]): """Wraps a s...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/encoder_backed.html
6083b6367f0b-1
value_serializer: Callable[[V], bytes], value_deserializer: Callable[[Any], V], ) -> None: """Initialize an EncodedStore.""" self.store = store self.key_encoder = key_encoder self.value_serializer = value_serializer self.value_deserializer = value_deserializer [docs] ...
https://api.python.langchain.com/en/latest/_modules/langchain/storage/encoder_backed.html
5bab5632d843-0
Source code for langchain.storage.exceptions from langchain.schema import LangChainException [docs]class InvalidKeyException(LangChainException): """Raised when a key is invalid; e.g., uses incorrect characters."""
https://api.python.langchain.com/en/latest/_modules/langchain/storage/exceptions.html
4a28b03e9de4-0
Source code for langchain.evaluation.loading """Loading datasets and evaluators.""" from typing import Any, Dict, List, Optional, Sequence, Type, Union from langchain.chains.base import Chain from langchain.chat_models.openai import ChatOpenAI from langchain.evaluation.agents.trajectory_eval_chain import TrajectoryEval...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html
4a28b03e9de4-1
""" # noqa: E501 try: from datasets import load_dataset except ImportError: raise ImportError( "load_dataset requires the `datasets` package." " Please install with `pip install datasets`" ) dataset = load_dataset(f"LangChainDatasets/{uri}") return [d for...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html
4a28b03e9de4-2
---------- 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 e...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html
4a28b03e9de4-3
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 l...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html
12c6aef45733-0
Source code for langchain.evaluation.schema """Interfaces to be implemented by general evaluators.""" from __future__ import annotations import logging from abc import ABC, abstractmethod from enum import Enum from typing import Any, Optional, Sequence, Tuple from warnings import warn from langchain.chains.base import ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html
12c6aef45733-1
STRING_DISTANCE = "string_distance" """Compare predictions to a reference answer using string edit distances.""" PAIRWISE_STRING_DISTANCE = "pairwise_string_distance" """Compare predictions based on string edit distances.""" EMBEDDING_DISTANCE = "embedding_distance" """Compare a prediction to a refe...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html
12c6aef45733-2
input: Optional[str] = None, ) -> None: """Check if the evaluation arguments are valid. Args: reference (Optional[str], optional): The reference label. input (Optional[str], optional): The input string. Raises: ValueError: If the evaluator requires an inpu...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html
12c6aef45733-3
reference (Optional[str], optional): The reference label to evaluate against. input (Optional[str], optional): The input to consider during evaluation. **kwargs: Additional keyword arguments, including callbacks, tags, etc. Returns: dict: The evaluation results containing the...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html
12c6aef45733-4
) [docs] def evaluate_strings( self, *, prediction: str, reference: Optional[str] = None, input: Optional[str] = None, **kwargs: Any, ) -> dict: """Evaluate Chain or LLM output, based on optional input and label. Args: prediction (str): ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html
12c6aef45733-5
self._check_evaluation_args(reference=reference, input=input) return await self._aevaluate_strings( prediction=prediction, reference=reference, input=input, **kwargs ) [docs]class PairwiseStringEvaluator(_EvalArgsMixin, ABC): """Compare the output of two models (or two outputs of the sam...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html
12c6aef45733-6
input (Optional[str], optional): The input string. **kwargs: Additional keyword arguments, such as callbacks and optional reference strings. Returns: dict: A dictionary containing the preference, scores, and/or other information. """ # noqa: E501 raise NotImplementedErro...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html
12c6aef45733-7
**kwargs: Any, ) -> dict: """Asynchronously evaluate the output string pairs. Args: prediction (str): The output string from the first model. prediction_b (str): The output string from the second model. reference (Optional[str], optional): The expected output / re...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html
12c6aef45733-8
Returns: dict: The evaluation result. """ async def _aevaluate_agent_trajectory( self, *, prediction: str, agent_trajectory: Sequence[Tuple[AgentAction, str]], input: str, reference: Optional[str] = None, **kwargs: Any, ) -> dict: ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html
12c6aef45733-9
prediction=prediction, input=input, agent_trajectory=agent_trajectory, reference=reference, **kwargs, ) [docs] async def aevaluate_agent_trajectory( self, *, prediction: str, agent_trajectory: Sequence[Tuple[AgentAction, str]], ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html
ca03e1c9c2a8-0
Source code for langchain.evaluation.qa.eval_chain """LLM Chains for evaluating question answering.""" from __future__ import annotations import re from typing import Any, List, Optional, Sequence from pydantic import Extra from langchain import PromptTemplate from langchain.callbacks.manager import Callbacks from lang...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html
ca03e1c9c2a8-1
"""LLM Chain for evaluating question answering.""" output_key: str = "results" #: :meta private: class Config: """Configuration for the QAEvalChain.""" extra = Extra.ignore @property def evaluation_name(self) -> str: return "correctness" @property def requires_reference(...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html
ca03e1c9c2a8-2
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...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html
ca03e1c9c2a8-3
Returns: dict: The evaluation results containing the score or value. """ result = self( { "query": input, "answer": reference, "result": prediction, }, callbacks=callbacks, include_run_info=includ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html
ca03e1c9c2a8-4
raise ValueError( f"Input variables should be {expected_input_vars}, " f"but got {prompt.input_variables}" ) @property def evaluation_name(self) -> str: return "Contextual Accuracy" [docs] @classmethod def from_llm( cls, llm: BaseLanguag...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html
ca03e1c9c2a8-5
} 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[R...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html
ca03e1c9c2a8-6
@property def evaluation_name(self) -> str: return "COT Contextual Accuracy" [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, prompt: Optional[PromptTemplate] = None, **kwargs: Any, ) -> CotQAEvalChain: """Load QA Eval Chain from LLM.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html
489e5445709b-0
Source code for langchain.evaluation.qa.generate_chain """LLM Chain for generating examples for question answering.""" from __future__ import annotations from typing import Any from pydantic import Field from langchain.chains.llm import LLMChain from langchain.evaluation.qa.generate_prompt import PROMPT from langchain....
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/generate_chain.html
9edb81f744bf-0
Source code for langchain.evaluation.comparison.eval_chain """Base classes for comparing the output of two models.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Union from pydantic import Extra, Field from langchain.callbacks.manager import Callbacks from langchain.chains.constitut...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html
9edb81f744bf-1
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?", } [d...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html
9edb81f744bf-2
if not criteria: raise ValueError( "Criteria cannot be empty. " "Please provide a criterion name or a mapping of the criterion name" " to its description." ) criteria_ = dict(criteria) return criteria_ [docs]class PairwiseStringResultOu...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html
9edb81f744bf-3
score = { "A": 1, "B": 0, None: 0.5, }.get(verdict_) return { "reasoning": reasoning, "value": verdict_, "score": score, } [docs]class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain): """A chain ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html
9edb81f744bf-4
# } """ output_key: str = "results" #: :meta private: output_parser: BaseOutputParser = Field( default_factory=PairwiseStringResultOutputParser ) class Config: """Configuration for the PairwiseStringEvalChain.""" extra = Extra.ignore @property def requires_reference(...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html
9edb81f744bf-5
Args: llm (BaseLanguageModel): The LLM to use. prompt (PromptTemplate, optional): The prompt to use. **kwargs (Any): Additional keyword arguments. Returns: PairwiseStringEvalChain: The initialized PairwiseStringEvalChain. Raises: ValueError: If...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html
9edb81f744bf-6
"input": input, } if self.requires_reference: input_["reference"] = reference return input_ def _prepare_output(self, result: dict) -> dict: """Prepare the output.""" parsed = result[self.output_key] if RUN_KEY in result: parsed[RUN_KEY] = resu...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html
9edb81f744bf-7
result = self( inputs=input_, callbacks=callbacks, tags=tags, metadata=metadata, include_run_info=include_run_info, ) return self._prepare_output(result) async def _aevaluate_string_pairs( self, *, prediction: str, ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html
9edb81f744bf-8
callbacks=callbacks, tags=tags, metadata=metadata, include_run_info=include_run_info, ) return self._prepare_output(result) [docs]class LabeledPairwiseStringEvalChain(PairwiseStringEvalChain): """A chain for comparing two outputs, such as the outputs of two m...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html
9edb81f744bf-9
expected_input_vars = { "prediction", "prediction_b", "input", "reference", "criteria", } prompt_ = prompt or PROMPT_WITH_REFERENCE if expected_input_vars != set(prompt_.input_variables): raise ValueError( f"...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html
94c9c3e1d429-0
Source code for langchain.evaluation.string_distance.base """String distance evaluators based on the RapidFuzz library.""" from enum import Enum from typing import Any, Callable, Dict, List, Optional from pydantic import Field, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html
94c9c3e1d429-1
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) ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html
94c9c3e1d429-2
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 (str): The distance type. Returns: Callable: The distance metric function...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html
94c9c3e1d429-3
Args: a (str): The first string. b (str): The second string. Returns: float: The distance between the two strings. """ return self.metric(a, b) [docs]class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin): """Compute string distances between ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html