id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
5aeb50531ce9-1 | if (curr - start).total_seconds() * 1000 > timeout:
raise TimeoutError(f"{method} timed out at {timeout} ms")
sleep(RocksetChatMessageHistory.SLEEP_INTERVAL_MS / 1000)
def _query(self, query: str, **query_params: Any) -> List[Any]:
"""Executes an SQL statement and returns the res... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html |
5aeb50531ce9-2 | """Sleeps until the collection for this message history is ready
to be queried
"""
self._wait_until(
lambda: self._collection_is_ready(),
RocksetChatMessageHistory.CREATE_TIMEOUT_MS,
)
def _wait_until_message_added(self, message_id: str) -> None:
"""Sl... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html |
5aeb50531ce9-3 | """Constructs a new RocksetChatMessageHistory.
Args:
- session_id: The ID of the chat session
- client: The RocksetClient object to use to query
- collection: The name of the collection to use to store chat
messages. If a collection with the given na... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html |
5aeb50531ce9-4 | self.location = f'"{self.workspace}"."{self.collection}"'
self.rockset = rockset
self.messages_key = messages_key
self.message_uuid_method = message_uuid_method
self.sync = sync
try:
self.client.set_application("langchain")
except AttributeError:
#... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html |
5aeb50531ce9-5 | value=_message_to_dict(message),
)
],
)
],
)
if self.sync:
self._wait_until_message_added(message.additional_kwargs["id"])
[docs] def clear(self) -> None:
"""Removes all messages from the chat history"""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html |
9082a30b07fd-0 | Source code for langchain.memory.chat_message_histories.elasticsearch
import json
import logging
from time import time
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from langchain.schema import BaseChatMessageHistory
from langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict
i... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/elasticsearch.html |
9082a30b07fd-1 | headers={"user-agent": self.get_user_agent()}
)
elif es_url is not None or es_cloud_id is not None:
self.client = ElasticsearchChatMessageHistory.connect_to_elasticsearch(
es_url=es_url,
username=es_user,
password=es_password,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/elasticsearch.html |
9082a30b07fd-2 | raise ImportError(
"Could not import elasticsearch python package. "
"Please install it with `pip install elasticsearch`."
)
if es_url and cloud_id:
raise ValueError(
"Both es_url and cloud_id are defined. Please provide only one."
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/elasticsearch.html |
9082a30b07fd-3 | items = [
json.loads(document["_source"]["history"])
for document in result["hits"]["hits"]
]
else:
items = []
return messages_from_dict(items)
[docs] def add_message(self, message: BaseMessage) -> None:
"""Add a message to the chat sess... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/elasticsearch.html |
8c580c7bf577-0 | Source code for langchain.memory.chat_message_histories.streamlit
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import BaseMessage
[docs]class StreamlitChatMessageHistory(BaseChatMessageHistory):
"""
Chat message history that stores messages ... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/streamlit.html |
cda58335f02f-0 | Source code for langchain.memory.chat_message_histories.redis
import json
import logging
from typing import List, Optional
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict
from langchain.utilities.redis import get_client... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
cda58335f02f-1 | [docs] def add_message(self, message: BaseMessage) -> None:
"""Append the message to the record in Redis"""
self.redis_client.lpush(self.key, json.dumps(_message_to_dict(message)))
if self.ttl:
self.redis_client.expire(self.key, self.ttl)
[docs] def clear(self) -> None:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
f2df2cab9cb5-0 | Source code for langchain.memory.chat_message_histories.cosmos_db
"""Azure CosmosDB Memory History."""
from __future__ import annotations
import logging
from types import TracebackType
from typing import TYPE_CHECKING, Any, List, Optional, Type
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
f2df2cab9cb5-1 | :param credential: The credential to use to authenticate to Azure Cosmos DB.
:param connection_string: The connection string to use to authenticate.
:param ttl: The time to live (in seconds) to use for documents in the container.
:param cosmos_client_kwargs: Additional kwargs to pass to the Cosm... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
f2df2cab9cb5-2 | """Prepare the CosmosDB client.
Use this function or the context manager to make sure your database is ready.
"""
try:
from azure.cosmos import ( # pylint: disable=import-outside-toplevel # noqa: E501
PartitionKey,
)
except ImportError as exc:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
f2df2cab9cb5-3 | CosmosHttpResponseError,
)
except ImportError as exc:
raise ImportError(
"You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501
"Please install it with `pip install azure-cosmos`."
) from exc
tr... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
8786fcfb3886-0 | Source code for langchain.memory.chat_message_histories.momento
from __future__ import annotations
import json
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Optional
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import BaseMessage, _message_to_dict, ... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
8786fcfb3886-1 | Note: to instantiate the cache client passed to MomentoChatMessageHistory,
you must have a Momento account at https://gomomento.com/.
Args:
session_id (str): The session ID to use for this chat session.
cache_client (CacheClient): The Momento cache client.
cache_name ... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
8786fcfb3886-2 | def from_client_params(
cls,
session_id: str,
cache_name: str,
ttl: timedelta,
*,
configuration: Optional[momento.config.Configuration] = None,
api_key: Optional[str] = None,
auth_token: Optional[str] = None, # for backwards compatibility
**kwargs... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
8786fcfb3886-3 | fetch_response = self.cache_client.list_fetch(self.cache_name, self.key)
if isinstance(fetch_response, CacheListFetch.Hit):
items = [json.loads(m) for m in fetch_response.value_list_string]
return messages_from_dict(items)
elif isinstance(fetch_response, CacheListFetch.Miss):
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
8786fcfb3886-4 | raise delete_response.inner_exception
else:
raise Exception(f"Unexpected response: {delete_response}") | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
f94f450e8110-0 | Source code for langchain.memory.chat_message_histories.in_memory
from typing import List
from langchain.pydantic_v1 import BaseModel, Field
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import BaseMessage
[docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel):
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html |
86b5fd59dcdd-0 | Source code for langchain.evaluation.schema
"""Interfaces to be implemented by general evaluators."""
from __future__ import annotations
import asyncio
import logging
from abc import ABC, abstractmethod
from enum import Enum
from functools import partial
from typing import Any, Optional, Sequence, Tuple, Union
from war... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html |
86b5fd59dcdd-1 | 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"
"""... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html |
86b5fd59dcdd-2 | [docs] @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 t... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html |
86b5fd59dcdd-3 | warn(self._skip_input_warning)
if self.requires_reference and reference is None:
raise ValueError(f"{self.__class__.__name__} requires a reference string.")
elif reference is not None and not self.requires_reference:
warn(self._skip_reference_warning)
[docs]class StringEvaluator(... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html |
86b5fd59dcdd-4 | """ # noqa: E501
async def _aevaluate_strings(
self,
*,
prediction: Union[str, Any],
reference: Optional[Union[str, Any]] = None,
input: Optional[Union[str, Any]] = None,
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate Chain or LLM output, based on o... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html |
86b5fd59dcdd-5 | Args:
prediction (str): The LLM or chain prediction to evaluate.
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 callb... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html |
86b5fd59dcdd-6 | @abstractmethod
def _evaluate_string_pairs(
self,
*,
prediction: str,
prediction_b: str,
reference: Optional[str] = None,
input: Optional[str] = None,
**kwargs: Any,
) -> dict:
"""Evaluate the output string pairs.
Args:
predicti... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html |
86b5fd59dcdd-7 | None,
partial(
self._evaluate_string_pairs,
prediction=prediction,
prediction_b=prediction_b,
reference=reference,
input=input,
**kwargs,
),
)
[docs] def evaluate_string_pairs(
self... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html |
86b5fd59dcdd-8 | 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 / reference string.
input (Optional[str], optional): The input string.
**kwarg... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html |
86b5fd59dcdd-9 | self,
*,
prediction: str,
agent_trajectory: Sequence[Tuple[AgentAction, str]],
input: str,
reference: Optional[str] = None,
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate a trajectory.
Args:
prediction (str): The final predicted respo... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html |
86b5fd59dcdd-10 | 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]],
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/schema.html |
a9cbf5c3f5ad-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html |
a9cbf5c3f5ad-1 | [docs]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**... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html |
a9cbf5c3f5ad-2 | EvaluatorType.CRITERIA: CriteriaEvalChain,
EvaluatorType.LABELED_CRITERIA: LabeledCriteriaEvalChain,
EvaluatorType.STRING_DISTANCE: StringDistanceEvalChain,
EvaluatorType.PAIRWISE_STRING_DISTANCE: PairwiseStringDistanceEvalChain,
EvaluatorType.EMBEDDING_DISTANCE: EmbeddingDistanceEvalChain,
Evaluato... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html |
a9cbf5c3f5ad-3 | raise ValueError(
f"Unknown evaluator type: {evaluator}"
f"\nValid types are: {list(_EVALUATOR_MAP.keys())}"
)
evaluator_cls = _EVALUATOR_MAP[evaluator]
if issubclass(evaluator_cls, LLMEvalChain):
try:
llm = llm or ChatOpenAI(
model="gpt-4", mo... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html |
a9cbf5c3f5ad-4 | by default None
**kwargs : Any
Additional keyword arguments to pass to all evaluators.
Returns
-------
List[Chain]
The loaded evaluators.
Examples
--------
>>> from langchain.evaluation import load_evaluators, EvaluatorType
>>> evaluators = [EvaluatorType.QA, EvaluatorTyp... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html |
3dc5fdf3e1e8-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 langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
Callb... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
3dc5fdf3e1e8-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)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
3dc5fdf3e1e8-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
3dc5fdf3e1e8-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 ... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
3dc5fdf3e1e8-4 | def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
"""
Compute the string distance between the prediction and the reference.
Args:
inputs (Dict[str, Any]): The input values.
r... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
3dc5fdf3e1e8-5 | """
Evaluate the string distance between the prediction and the reference.
Args:
prediction (str): The prediction string.
reference (Optional[str], optional): The reference string.
input (Optional[str], optional): The input string.
callbacks (Callbacks, op... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
3dc5fdf3e1e8-6 | callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
return self._prepare_output(result)
[docs]class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMixin):
"""Compute string edit distances between two pre... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
3dc5fdf3e1e8-7 | Args:
inputs (Dict[str, Any]): The input values.
run_manager (AsyncCallbackManagerForChainRun , optional):
The callback manager.
Returns:
Dict[str, Any]: The evaluation results containing the score.
"""
return {
"score": self.comput... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
3dc5fdf3e1e8-8 | callbacks: Callbacks = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""
Asynchronously evaluate the string distance between two predictions.
Args:
predi... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
3bc9df128157-0 | Source code for langchain.evaluation.comparison.eval_chain
"""Base classes for comparing the output of two models."""
from __future__ import annotations
import logging
import re
from typing import Any, Dict, List, Optional, Union
from langchain.callbacks.manager import Callbacks
from langchain.chains.constitutional_ai.... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3bc9df128157-1 | 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.INSENSITIV... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3bc9df128157-2 | 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(c... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3bc9df128157-3 | "Output must contain a double bracketed string\
with the verdict 'A', 'B', or 'C'."
)
# C means the models are tied. Return 'None' meaning no preference
verdict_ = None if verdict == "C" else verdict
score = {
"A": 1,
"B": 0,
"C": ... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3bc9df128157-4 | ... )
>>> 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.\\... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3bc9df128157-5 | [docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
*,
prompt: Optional[PromptTemplate] = None,
criteria: Optional[Union[CRITERIA_TYPE, str]] = None,
**kwargs: Any,
) -> PairwiseStringEvalChain:
"""Initialize the PairwiseStringEvalChain from ... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3bc9df128157-6 | 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: Optional[str],
reference: Optional[str],
)... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3bc9df128157-7 | **kwargs: Any,
) -> dict:
"""Evaluate whether output A is preferred to output B.
Args:
prediction (str): The output string from the first model.
prediction_b (str): The output string from the second model.
input (str, optional): The input or task string.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3bc9df128157-8 | """Asynchronously evaluate whether output A is preferred to output B.
Args:
prediction (str): The output string from the first model.
prediction_b (str): The output string from the second model.
input (str, optional): The input or task string.
callbacks (Callbacks... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3bc9df128157-9 | """
return True
[docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
*,
prompt: Optional[PromptTemplate] = None,
criteria: Optional[Union[CRITERIA_TYPE, str]] = None,
**kwargs: Any,
) -> PairwiseStringEvalChain:
"""Initialize the Label... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
7d58fe4017eb-0 | Source code for langchain.evaluation.parsing.json_schema
from typing import Any, Union
from langchain.evaluation.schema import StringEvaluator
from langchain.output_parsers.json import parse_json_markdown
[docs]class JsonSchemaEvaluator(StringEvaluator):
"""An evaluator that validates a JSON prediction against a JS... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/json_schema.html |
7d58fe4017eb-1 | )
@property
def requires_input(self) -> bool:
"""Returns whether the evaluator requires input."""
return False
@property
def requires_reference(self) -> bool:
"""Returns whether the evaluator requires reference."""
return True
@property
def evaluation_name(self) -... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/json_schema.html |
4133235ad712-0 | Source code for langchain.evaluation.parsing.base
"""Evaluators for parsing strings."""
from operator import eq
from typing import Any, Callable, Optional, Union, cast
from langchain.evaluation.schema import StringEvaluator
from langchain.output_parsers.json import parse_json_markdown
[docs]class JsonValidityEvaluator(... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html |
4133235ad712-1 | self,
prediction: str,
input: Optional[str] = None,
reference: Optional[str] = None,
**kwargs: Any,
) -> dict:
"""Evaluate the prediction string.
Args:
prediction (str): The prediction string to evaluate.
input (str, optional): Not used in this... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html |
4133235ad712-2 | {'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.e... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html |
4133235ad712-3 | Returns:
dict: A dictionary 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}
parse... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html |
43e34e9ab91b-0 | Source code for langchain.evaluation.parsing.json_distance
import json
from typing import Any, Callable, Optional, Union
from langchain.evaluation.schema import StringEvaluator
from langchain.output_parsers.json import parse_json_markdown
[docs]class JsonEditDistanceEvaluator(StringEvaluator):
"""
An evaluator ... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/json_distance.html |
43e34e9ab91b-1 | """ # noqa: E501
[docs] def __init__(
self,
string_distance: Optional[Callable[[str, str], float]] = None,
canonicalize: Optional[Callable[[Any], Any]] = None,
**kwargs: Any,
) -> None:
super().__init__()
if string_distance is not None:
self._string_di... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/json_distance.html |
43e34e9ab91b-2 | input: Optional[str] = None,
reference: Optional[str] = None,
**kwargs: Any,
) -> dict:
parsed = self._canonicalize(self._parse_json(prediction))
label = self._canonicalize(self._parse_json(reference))
distance = self._string_distance(parsed, label)
return {"score": d... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/json_distance.html |
029eae01d414-0 | Source code for langchain.evaluation.exact_match.base
import string
from typing import Any, List
from langchain.evaluation.schema import StringEvaluator
[docs]class ExactMatchStringEvaluator(StringEvaluator):
"""Compute an exact match between the prediction and the reference.
Examples
----------
>>> eva... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/exact_match/base.html |
029eae01d414-1 | """
Get the evaluation name.
Returns:
str: The evaluation name.
"""
return "exact_match"
def _evaluate_strings( # type: ignore[arg-type,override]
self,
*,
prediction: str,
reference: str,
**kwargs: Any,
) -> dict:
"""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/exact_match/base.html |
7acbff31c661-0 | Source code for langchain.evaluation.agents.trajectory_eval_chain
"""A chain for evaluating ReAct style agents.
This chain is used to evaluate ReAct style agents by reasoning about
the sequence of actions taken and their outcomes. It uses a language model
chain (LLMChain) to generate the reasoning and scores.
"""
impor... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
7acbff31c661-1 | [docs] def parse(self, text: str) -> TrajectoryEval:
"""Parse the output text and extract the score and reasoning.
Args:
text (str): The output text to parse.
Returns:
TrajectoryEval: A named tuple containing the normalized score and reasoning.
Raises:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
7acbff31c661-2 | # If the score is not in the range 1-5, raise an exception.
if not 1 <= score <= 5:
raise OutputParserException(
f"Score is not a digit in the range 1-5: {text}"
)
normalized_score = (score - 1) / 4
return TrajectoryEval(score=normalized_score, reasoning=r... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
7acbff31c661-3 | )
result = eval_chain.evaluate_agent_trajectory(
input=question,
agent_trajectory=response["intermediate_steps"],
prediction=response["output"],
reference="Paris",
)
print(result["score"])
# 0
""" # noqa: E501
agent_tools: Optional... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
7acbff31c661-4 | """Get the agent trajectory as a formatted string.
Args:
steps (Union[str, List[Tuple[AgentAction, str]]]): The agent trajectory.
Returns:
str: The formatted agent trajectory.
"""
if isinstance(steps, str):
return steps
return "\n\n".join(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
7acbff31c661-5 | used to parse the chain output into a score.
Returns:
TrajectoryEvalChain: The TrajectoryEvalChain object.
"""
if not isinstance(llm, BaseChatModel):
raise NotImplementedError(
"Only chat models supported by the current trajectory eval"
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
7acbff31c661-6 | """Run the chain and generate the output.
Args:
inputs (Dict[str, str]): The input values for the chain.
run_manager (Optional[CallbackManagerForChainRun]): The callback
manager for the chain run.
Returns:
Dict[str, Any]: The output values of the chain... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
7acbff31c661-7 | self,
*,
prediction: str,
input: str,
agent_trajectory: Sequence[Tuple[AgentAction, str]],
reference: Optional[str] = None,
callbacks: Callbacks = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
include_run_info: ... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
7acbff31c661-8 | metadata: Optional[Dict[str, Any]] = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate a trajectory.
Args:
prediction (str): The final predicted response.
input (str): The input to the agent.
agent_trajector... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
223891f83663-0 | Source code for langchain.evaluation.embedding_distance.base
"""A chain for comparing the output of two models using embeddings."""
from enum import Enum
from typing import Any, Dict, List, Optional
import numpy as np
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForC... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
223891f83663-1 | distance_metric: EmbeddingDistance = Field(default=EmbeddingDistance.COSINE)
@root_validator(pre=False)
def _validate_tiktoken_installed(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that the TikTok library is installed.
Args:
values (Dict[str, Any]): The values to vali... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
223891f83663-2 | Returns:
Any: The metric function.
"""
metrics = {
EmbeddingDistance.COSINE: self._cosine_distance,
EmbeddingDistance.EUCLIDEAN: self._euclidean_distance,
EmbeddingDistance.MANHATTAN: self._manhattan_distance,
EmbeddingDistance.CHEBYSHEV: self.... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
223891f83663-3 | Returns:
np.floating: The Manhattan distance.
"""
return np.sum(np.abs(a - b))
@staticmethod
def _chebyshev_distance(a: np.ndarray, b: np.ndarray) -> np.floating:
"""Compute the Chebyshev distance between two vectors.
Args:
a (np.ndarray): The first vector... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
223891f83663-4 | >>> print(result)
{'score': 0.5}
"""
@property
def requires_reference(self) -> bool:
"""Return whether the chain requires a reference.
Returns:
bool: True if a reference is required, False otherwise.
"""
return True
@property
def evaluation_name(se... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
223891f83663-5 | run_manager (AsyncCallbackManagerForChainRun, optional):
The callback manager.
Returns:
Dict[str, Any]: The computed score.
"""
embedded = await self.embeddings.aembed_documents(
[inputs["prediction"], inputs["reference"]]
)
vectors = np.ar... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
223891f83663-6 | callbacks: Callbacks = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Asynchronously evaluate the embedding distance between
a prediction and reference.
Args:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
223891f83663-7 | return f"pairwise_embedding_{self.distance_metric.value}_distance"
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
"""Compute the score for two predictions.
Args:
inputs (Dict[str, Any]): ... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
223891f83663-8 | callbacks: Callbacks = None,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dict:
"""Evaluate the embedding distance between two predictions.
Args:
prediction (str): The outp... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
223891f83663-9 | callbacks (Callbacks, optional): The callbacks to use.
tags (List[str], optional): Tags to apply to traces
metadata (Dict[str, Any], optional): metadata to apply to traces
**kwargs (Any): Additional keyword arguments.
Returns:
dict: A dictionary containing:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
49e32f8ff2cc-0 | Source code for langchain.evaluation.regex_match.base
import re
from typing import Any, List
from langchain.evaluation.schema import StringEvaluator
[docs]class RegexMatchStringEvaluator(StringEvaluator):
"""Compute a regex match between the prediction and the reference.
Examples
----------
>>> evaluato... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/regex_match/base.html |
49e32f8ff2cc-1 | Returns:
List[str]: The input keys.
"""
return ["reference", "prediction"]
@property
def evaluation_name(self) -> str:
"""
Get the evaluation name.
Returns:
str: The evaluation name.
"""
return "regex_match"
def _evaluate_string... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/regex_match/base.html |
d8bcc8e353a1-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 langchain.chains.llm import LLMChain
from langchain.evaluation.qa.generate_prompt import PROMPT
from langchain.output_parsers.regex import... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/generate_chain.html |
09b95eef0b89-0 | Source code for langchain.evaluation.qa.eval_chain
"""LLM Chains for evaluating question answering."""
from __future__ import annotations
import re
import string
from typing import Any, List, Optional, Sequence, Tuple
from langchain.callbacks.manager import Callbacks
from langchain.chains.llm import LLMChain
from langc... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
09b95eef0b89-1 | return "INCORRECT", 0
except IndexError:
pass
return None
def _parse_string_eval_output(text: str) -> dict:
"""Parse the output text.
Args:
text (str): The output text to parse.
Returns:
Any: The parsed output.
"""
reasoning = text.strip()
parsed_scores = _get_sco... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
09b95eef0b89-2 | 'input', 'answer' and 'result' that will be used as the prompt
for evaluation.
Defaults to PROMPT.
**kwargs: additional keyword arguments.
Returns:
QAEvalChain: the loaded QA eval chain.
"""
prompt = prompt or PROMPT
expected_input_vars = {... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
09b95eef0b89-3 | reference: Optional[str] = None,
input: Optional[str] = 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 (str): the LLM or chai... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
09b95eef0b89-4 | )
return self._prepare_output(result)
[docs]class ContextQAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):
"""LLM Chain for evaluating QA w/o GT based on context"""
@property
def requires_reference(self) -> bool:
"""Whether the chain requires a reference string."""
return True
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
09b95eef0b89-5 | ContextQAEvalChain: the loaded QA eval chain.
"""
prompt = prompt or CONTEXT_PROMPT
cls._validate_input_vars(prompt)
return cls(llm=llm, prompt=prompt, **kwargs)
[docs] def evaluate(
self,
examples: List[dict],
predictions: List[dict],
question_key: str... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
09b95eef0b89-6 | )
return self._prepare_output(result)
async def _aevaluate_strings(
self,
*,
prediction: str,
reference: Optional[str] = None,
input: Optional[str] = None,
callbacks: Callbacks = None,
include_run_info: bool = False,
**kwargs: Any,
) -> dic... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
3cdc96e5712c-0 | Source code for langchain.evaluation.scoring.eval_chain
"""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, Dict, List, Optional, Union
from langchain.callbacks.manager import Callbacks
from langchain.chains.constit... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html |
3cdc96e5712c-1 | 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.CRIMINA... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html |
3cdc96e5712c-2 | 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_c... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.