id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
a8412a8751d5-3 | " Please manually provide an evaluation LLM"
" or check your openai credentials."
) from e
return evaluator_cls.from_llm(llm=llm, **kwargs)
else:
return evaluator_cls(**kwargs)
[docs]def load_evaluators(
evaluators: Sequence[EvaluatorType],
*,
llm: Optional[Ba... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/loading.html |
3c007fc02beb-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.... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3c007fc02beb-1 | Criteria.HELPFULNESS: "Is the submission helpful, insightful, and appropriate?",
Criteria.CONTROVERSIALITY: "Is the submission controversial or debatable?",
Criteria.MISOGYNY: "Is the submission misogynistic? If so, respond Y.",
Criteria.CRIMINALITY: "Is the submission criminal in any way?",
Criteria.IN... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3c007fc02beb-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3c007fc02beb-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": ... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3c007fc02beb-4 | # {
# "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_k... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3c007fc02beb-5 | cls,
llm: BaseLanguageModel,
*,
prompt: Optional[PromptTemplate] = None,
criteria: Optional[Union[CRITERIA_TYPE, str]] = None,
**kwargs: Any,
) -> PairwiseStringEvalChain:
"""Initialize the PairwiseStringEvalChain from an LLM.
Args:
llm (BaseChatMo... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3c007fc02beb-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],
)... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3c007fc02beb-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.
... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3c007fc02beb-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
3c007fc02beb-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/comparison/eval_chain.html |
2720f41d54c0-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/exact_match/base.html |
2720f41d54c0-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:
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/exact_match/base.html |
5f0e30983f05-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/generate_chain.html |
d9466d8ca3c4-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
d9466d8ca3c4-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
d9466d8ca3c4-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 = {... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
d9466d8ca3c4-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
d9466d8ca3c4-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
... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
d9466d8ca3c4-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
d9466d8ca3c4-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/qa/eval_chain.html |
69e380a405cc-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(... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html |
69e380a405cc-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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html |
69e380a405cc-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html |
69e380a405cc-3 | """
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=lambda x: str(x))
label = sorted(label, key=la... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/parsing/base.html |
26849e61e899-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/regex_match/base.html |
26849e61e899-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/regex_match/base.html |
4d6810b4ddd3-0 | Source code for langchain.evaluation.criteria.eval_chain
from __future__ import annotations
import re
from enum import Enum
from typing import Any, Dict, List, Mapping, Optional, Union
from langchain.callbacks.manager import Callbacks
from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-1 | 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: "... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-2 | """Parse the output text.
Args:
text (str): The output text to parse.
Returns:
Dict: 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*", te... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-3 | ) -> 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 crit... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-4 | 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=... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-5 | {
'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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-6 | """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" #: :meta private:
class Config:
"""Configuration for the QAEvalChain."""
extra = Extra.ignore
@property
def requires... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-7 | ) -> 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 presen... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-8 | 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
--------
>>> fro... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-9 | input_ = {
"input": input,
"output": prediction,
}
if self.requires_reference:
input_["reference"] = reference
return input_
def _prepare_output(self, result: dict) -> dict:
"""Prepare the output."""
parsed = result[self.output_key]
... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-10 | >>> 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(
... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-11 | >>> llm = OpenAI()
>>> criteria = "conciseness"
>>> chain = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)
>>> await chain.aevaluate_strings(
prediction="The answer is 42.",
reference="42",
input="What is the answer to life, the universe, a... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-12 | **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"
... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
4d6810b4ddd3-13 | prompt_ = prompt.partial(criteria=criteria_str)
return cls(
llm=llm,
prompt=prompt_,
criterion_name="-".join(criteria_),
**kwargs,
) | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
0ddff32de2fa-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
0ddff32de2fa-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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
0ddff32de2fa-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
0ddff32de2fa-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
0ddff32de2fa-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(
... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
0ddff32de2fa-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"
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
0ddff32de2fa-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
0ddff32de2fa-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: ... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
0ddff32de2fa-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html |
7491fe66d907-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
7491fe66d907-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 |
7491fe66d907-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 |
7491fe66d907-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 |
7491fe66d907-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
7491fe66d907-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
7491fe66d907-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
7491fe66d907-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
7491fe66d907-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html |
def84e05a652-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
def84e05a652-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
def84e05a652-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.... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
def84e05a652-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
def84e05a652-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
def84e05a652-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
def84e05a652-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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
def84e05a652-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]): ... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
def84e05a652-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... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
def84e05a652-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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html |
37e94ef1535e-0 | Source code for langchain.callbacks.arthur_callback
"""ArthurAI's Callback Handler."""
from __future__ import annotations
import os
import uuid
from collections import defaultdict
from datetime import datetime
from time import time
from typing import TYPE_CHECKING, Any, DefaultDict, Dict, List, Optional
import numpy as... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
37e94ef1535e-1 | """
[docs] def __init__(
self,
arthur_model: ArthurModel,
) -> None:
"""Initialize callback handler."""
super().__init__()
arthurai = _lazy_load_arthur()
Stage = arthurai.common.constants.Stage
ValueType = arthurai.common.constants.ValueType
self.ar... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
37e94ef1535e-2 | arthur_url: Optional[str] = "https://app.arthur.ai",
arthur_login: Optional[str] = None,
arthur_password: Optional[str] = None,
) -> ArthurCallbackHandler:
"""Initialize callback handler from Arthur credentials.
Args:
model_id (str): The ID of the arthur model to log to.
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
37e94ef1535e-3 | )
# get model from Arthur by the provided model ID
try:
arthur_model = arthur.get_model(model_id)
except ResponseClientError:
raise ValueError(
f"Was unable to retrieve model with id {model_id} from Arthur."
" Make sure the ID corresponds t... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
37e94ef1535e-4 | " Restart and try running the LLM again"
) from e
# mark the duration time between on_llm_start() and on_llm_end()
time_from_start_to_end = time() - run_map_data["start_time"]
# create inferences to log to Arthur
inferences = []
for i, generations in enumerate(respons... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
37e94ef1535e-5 | # add token usage counts to the inference if the
# ArthurModel was registered to monitor token usage
if (
isinstance(response.llm_output, dict)
and TOKEN_USAGE in response.llm_output
):
token_usage = response.llm... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
37e94ef1535e-6 | """On new token, pass."""
[docs] def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
"""Do nothing when LLM chain outputs an error."""
[docs] def on_tool_start(
self,
serialized: Dict[str, Any],
input_str: str,
**kwargs: Any,
) -> None:
"""Do ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
7212e377e232-0 | Source code for langchain.callbacks.flyte_callback
"""FlyteKit callback handler."""
from __future__ import annotations
import logging
from copy import deepcopy
from typing import TYPE_CHECKING, Any, Dict, List, Tuple
from langchain.callbacks.base import BaseCallbackHandler
from langchain.callbacks.utils import (
Ba... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
7212e377e232-1 | Returns:
(dict): A dictionary containing the complexity metrics and visualization
files serialized to HTML string.
"""
resp: Dict[str, Any] = {}
if textstat is not None:
text_complexity_metrics = {
"flesch_reading_ease": textstat.flesch_reading_ease(text),
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
7212e377e232-2 | dep_out = spacy.displacy.render( # type: ignore
doc, style="dep", jupyter=False, page=True
)
ent_out = spacy.displacy.render( # type: ignore
doc, style="ent", jupyter=False, page=True
)
text_visualizations = {
"dependency_tree": dep_out,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
7212e377e232-3 | " for certain metrics. To download,"
" run the following command in your terminal:"
" `python -m spacy download en_core_web_sm`"
)
self.table_renderer = renderer.TableRenderer
self.markdown_renderer = renderer.MarkdownRenderer
self.deck = f... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
7212e377e232-4 | self.ends += 1
resp: Dict[str, Any] = {}
resp.update({"action": "on_llm_end"})
resp.update(flatten_dict(response.llm_output or {}))
resp.update(self.get_custom_callback_meta())
self.deck.append(self.markdown_renderer().to_html("### LLM End"))
self.deck.append(self.table_r... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
7212e377e232-5 | )
self.deck.append(self.markdown_renderer().to_html(generation.text))
[docs] def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
"""Run when LLM errors."""
self.step += 1
self.errors += 1
[docs] def on_chain_start(
self, serialized: Dict[str, An... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
7212e377e232-6 | resp.update(self.get_custom_callback_meta())
self.deck.append(self.markdown_renderer().to_html("### Chain End"))
self.deck.append(
self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
)
[docs] def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
7212e377e232-7 | self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
)
[docs] def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
"""Run when tool errors."""
self.step += 1
self.errors += 1
[docs] def on_text(self, text: str, **kwargs: Any) -> None:
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
7212e377e232-8 | """Run on agent action."""
self.step += 1
self.tool_starts += 1
self.starts += 1
resp: Dict[str, Any] = {}
resp.update(
{
"action": "on_agent_action",
"tool": action.tool,
"tool_input": action.tool_input,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
9f945d1106b6-0 | Source code for langchain.callbacks.arize_callback
from datetime import datetime
from typing import Any, Dict, List, Optional
from langchain.callbacks.base import BaseCallbackHandler
from langchain.callbacks.utils import import_pandas
from langchain.schema import AgentAction, AgentFinish, LLMResult
[docs]class ArizeCal... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
9f945d1106b6-1 | self.arize_client = Client(space_key=SPACE_KEY, api_key=API_KEY)
if SPACE_KEY == "SPACE_KEY" or API_KEY == "API_KEY":
raise ValueError("❌ CHANGE SPACE AND API KEYS")
else:
print("✅ Arize client setup done! Now you can start using Arize!")
[docs] def on_llm_start(
self,... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
9f945d1106b6-2 | for generations in response.generations:
for generation in generations:
prompt = self.prompt_records[self.step]
self.step = self.step + 1
prompt_embedding = pd.Series(
self.generator.generate_embeddings(
text_col=pd.... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
9f945d1106b6-3 | "completion_token",
"total_token",
],
prompt_column_names=prompt_columns,
response_column_names=response_columns,
)
response_from_arize = self.arize_client.log(
dataframe=df,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
9f945d1106b6-4 | output: str,
observation_prefix: Optional[str] = None,
llm_prefix: Optional[str] = None,
**kwargs: Any,
) -> None:
pass
[docs] def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
pass
[docs] def on_text(self, text: str, **kwargs: Any) -> None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
9c3ef4382793-0 | Source code for langchain.callbacks.comet_ml_callback
import tempfile
from copy import deepcopy
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence
import langchain
from langchain.callbacks.base import BaseCallbackHandler
from langchain.callbacks.utils import (
BaseMetadataCall... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
9c3ef4382793-1 | "smog_index": textstat.smog_index(text),
"coleman_liau_index": textstat.coleman_liau_index(text),
"automated_readability_index": textstat.automated_readability_index(text),
"dale_chall_readability_score": textstat.dale_chall_readability_score(text),
"difficult_words": textstat.difficult_... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
9c3ef4382793-2 | task_name (str): Name of the comet_ml task
visualize (bool): Whether to visualize the run.
complexity_metrics (bool): Whether to log complexity metrics
stream_logs (bool): Whether to stream callback actions to Comet
This handler will utilize the associated callback method and formats
the... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
9c3ef4382793-3 | self.experiment.set_name(self.name)
warning = (
"The comet_ml callback is currently in beta and is subject to change "
"based on updates to `langchain`. Please report any issues to "
"https://github.com/comet-ml/issue-tracking/issues with the tag "
"`langchain`."
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
9c3ef4382793-4 | """Run when LLM generates a new token."""
self.step += 1
self.llm_streams += 1
resp = self._init_resp()
resp.update({"action": "on_llm_new_token", "token": token})
resp.update(self.get_custom_callback_meta())
self.action_records.append(resp)
[docs] def on_llm_end(self,... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
9c3ef4382793-5 | self._log_text_metrics(output_complexity_metrics, step=self.step)
self._log_text_metrics(output_custom_metrics, step=self.step)
[docs] def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
"""Run when LLM errors."""
self.step += 1
self.errors += 1
[docs] def on_chain... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
9c3ef4382793-6 | resp.update(self.get_custom_callback_meta())
for chain_output_key, chain_output_val in outputs.items():
if isinstance(chain_output_val, str):
output_resp = deepcopy(resp)
if self.stream_logs:
self._log_stream(chain_output_val, resp, self.step)
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
9c3ef4382793-7 | self.ends += 1
resp = self._init_resp()
resp.update({"action": "on_tool_end"})
resp.update(self.get_custom_callback_meta())
if self.stream_logs:
self._log_stream(output, resp, self.step)
resp.update({"output": output})
self.action_records.append(resp)
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
9c3ef4382793-8 | resp.update({"output": output})
self.action_records.append(resp)
[docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
"""Run on agent action."""
self.step += 1
self.tool_starts += 1
self.starts += 1
tool = action.tool
tool_input = str(ac... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
9c3ef4382793-9 | """
resp = {}
if self.custom_metrics:
custom_metrics = self.custom_metrics(generation, prompt_idx, gen_idx)
resp.update(custom_metrics)
return resp
[docs] def flush_tracker(
self,
langchain_asset: Any = None,
task_type: Optional[str] = "inferenc... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.