id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
1a31b8ea94ee-1 | about this alternative if provided.
pending : bool, optional
If True, uses a PendingDeprecationWarning instead of a
DeprecationWarning. Cannot be used together with removal.
obj_type : str, optional
The object type being deprecated.
addendum : str, optional
... | https://api.python.langchain.com/en/latest/_modules/langchain/_api/deprecation.html |
1a31b8ea94ee-2 | warning = warning_cls(message)
warnings.warn(warning, category=LangChainDeprecationWarning, stacklevel=2)
# PUBLIC API
T = TypeVar("T", Type, Callable)
[docs]def deprecated(
since: str,
*,
message: str = "",
name: str = "",
alternative: str = "",
pending: bool = False,
obj_type: str = ""... | https://api.python.langchain.com/en/latest/_modules/langchain/_api/deprecation.html |
1a31b8ea94ee-3 | Override the default deprecation message. The %(since)s,
%(name)s, %(alternative)s, %(obj_type)s, %(addendum)s,
and %(removal)s format specifiers will be replaced by the
values of the respective arguments passed to this function.
name : str, optional
The name of t... | https://api.python.langchain.com/en/latest/_modules/langchain/_api/deprecation.html |
1a31b8ea94ee-4 | if isinstance(obj, type):
if not _obj_type:
_obj_type = "class"
wrapped = obj.__init__ # type: ignore
_name = _name or obj.__name__
old_doc = obj.__doc__
def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
"""Finalize... | https://api.python.langchain.com/en/latest/_modules/langchain/_api/deprecation.html |
1a31b8ea94ee-5 | if _name == "<lambda>":
_name = set_name
def finalize(_: Any, new_doc: str) -> Any: # type: ignore
"""Finalize the property."""
return _deprecated_property(
fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc
)... | https://api.python.langchain.com/en/latest/_modules/langchain/_api/deprecation.html |
1a31b8ea94ee-6 | The return value of the function being wrapped.
"""
emit_warning()
return wrapped(*args, **kwargs)
old_doc = inspect.cleandoc(old_doc or "").strip("\n")
if not old_doc:
new_doc = "[*Deprecated*]"
else:
new_doc = f"[*Deprecated*] {old_d... | https://api.python.langchain.com/en/latest/_modules/langchain/_api/deprecation.html |
f2fdcb0656a9-0 | Source code for langchain.indexes.graph
"""Graph Index Creator."""
from typing import Optional, Type
from pydantic import BaseModel
from langchain import BasePromptTemplate
from langchain.chains.llm import LLMChain
from langchain.graphs.networkx_graph import NetworkxEntityGraph, parse_triples
from langchain.indexes.pro... | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/graph.html |
f2fdcb0656a9-1 | chain = LLMChain(llm=self.llm, prompt=prompt)
output = await chain.apredict(text=text)
knowledge = parse_triples(output)
for triple in knowledge:
graph.add_triple(triple)
return graph | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/graph.html |
b2483446cd11-0 | Source code for langchain.indexes.vectorstore
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseModel, Extra, Field
from langchain.chains.qa_with_sources.retrieval import RetrievalQAWithSourcesChain
from langchain.chains.retrieval_qa.base import RetrievalQA
from langchain.document_loaders.base... | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html |
b2483446cd11-1 | )
return chain.run(question)
[docs] def query_with_sources(
self,
question: str,
llm: Optional[BaseLanguageModel] = None,
retriever_kwargs: Optional[Dict[str, Any]] = None,
**kwargs: Any
) -> dict:
"""Query the vectorstore and get back sources."""
l... | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html |
b2483446cd11-2 | vectorstore = self.vectorstore_cls.from_documents(
sub_docs, self.embedding, **self.vectorstore_kwargs
)
return VectorStoreIndexWrapper(vectorstore=vectorstore) | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html |
cd23f6397dd5-0 | Source code for langchain.load.load
import importlib
import json
import os
from typing import Any, Dict, List, Optional
from langchain.load.serializable import Serializable
[docs]class Reviver:
"""Reviver for JSON objects."""
[docs] def __init__(
self,
secrets_map: Optional[Dict[str, str]] = None... | https://api.python.langchain.com/en/latest/_modules/langchain/load/load.html |
cd23f6397dd5-1 | )
if (
value.get("lc", None) == 1
and value.get("type", None) == "constructor"
and value.get("id", None) is not None
):
[*namespace, name] = value["id"]
if namespace[0] not in self.valid_namespaces:
raise ValueError(f"Invalid na... | https://api.python.langchain.com/en/latest/_modules/langchain/load/load.html |
cd23f6397dd5-2 | [docs]def load(
obj: Any,
*,
secrets_map: Optional[Dict[str, str]] = None,
valid_namespaces: Optional[List[str]] = None,
) -> Any:
"""Revive a LangChain class from a JSON object. Use this if you already
have a parsed JSON object, eg. from `json.load` or `orjson.loads`.
Args:
obj: The... | https://api.python.langchain.com/en/latest/_modules/langchain/load/load.html |
8862b45a94fd-0 | Source code for langchain.load.serializable
from abc import ABC
from typing import Any, Dict, List, Literal, TypedDict, Union, cast
from pydantic import BaseModel, PrivateAttr
[docs]class BaseSerialized(TypedDict):
"""Base class for serialized objects."""
lc: int
id: List[str]
[docs]class SerializedConstruc... | https://api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html |
8862b45a94fd-1 | """
return {}
class Config:
extra = "ignore"
_lc_kwargs = PrivateAttr(default_factory=dict)
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self._lc_kwargs = kwargs
[docs] def to_json(self) -> Union[SerializedConstructor, SerializedNotImplemented]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html |
8862b45a94fd-2 | return {
"lc": 1,
"type": "constructor",
"id": [*self.lc_namespace, self.__class__.__name__],
"kwargs": lc_kwargs
if not secrets
else _replace_secrets(lc_kwargs, secrets),
}
[docs] def to_json_not_implemented(self) -> SerializedNotImplem... | https://api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html |
8862b45a94fd-3 | except Exception:
pass
return {
"lc": 1,
"type": "not_implemented",
"id": _id,
} | https://api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html |
269bbfcb3398-0 | Source code for langchain.load.dump
import json
from typing import Any, Dict
from langchain.load.serializable import Serializable, to_json_not_implemented
[docs]def default(obj: Any) -> Any:
"""Return a default value for a Serializable object or
a SerializedNotImplemented object."""
if isinstance(obj, Seria... | https://api.python.langchain.com/en/latest/_modules/langchain/load/dump.html |
dd521dbffa75-0 | Source code for langchain.output_parsers.list
from __future__ import annotations
from abc import abstractmethod
from typing import List
from langchain.schema import BaseOutputParser
[docs]class ListOutputParser(BaseOutputParser[List[str]]):
"""Parse the output of an LLM call to a list."""
@property
def _typ... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html |
ec2c22c2f0fa-0 | Source code for langchain.output_parsers.boolean
from langchain.schema import BaseOutputParser
[docs]class BooleanOutputParser(BaseOutputParser[bool]):
"""Parse the output of an LLM call to a boolean."""
true_val: str = "YES"
"""The string value that should be parsed as True."""
false_val: str = "NO"
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/boolean.html |
3ee931da1ebe-0 | Source code for langchain.output_parsers.structured
from __future__ import annotations
from typing import Any, List
from pydantic import BaseModel
from langchain.output_parsers.format_instructions import (
STRUCTURED_FORMAT_INSTRUCTIONS,
STRUCTURED_FORMAT_SIMPLE_INSTRUCTIONS,
)
from langchain.output_parsers.jso... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html |
3ee931da1ebe-1 | response_schemas = [
ResponseSchema(
name="foo",
description="a list of strings",
type="List[string]"
),
ResponseSchema(
name="bar",
description="a string",
type="string"
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html |
d525f4c7d129-0 | Source code for langchain.output_parsers.retry
from __future__ import annotations
from typing import TypeVar
from langchain.chains.llm import LLMChain
from langchain.prompts.prompt import PromptTemplate
from langchain.schema import (
BaseOutputParser,
BasePromptTemplate,
OutputParserException,
PromptVal... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
d525f4c7d129-1 | ) -> RetryOutputParser[T]:
chain = LLMChain(llm=llm, prompt=prompt)
return cls(parser=parser, retry_chain=chain)
[docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:
"""Parse the output of an LLM call using a wrapped parser.
Args:
completion... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
d525f4c7d129-2 | return self.parser.get_format_instructions()
@property
def _type(self) -> str:
return "retry"
[docs]class RetryWithErrorOutputParser(BaseOutputParser[T]):
"""Wraps a parser and tries to fix parsing errors.
Does this by passing the original prompt, the completion, AND the error
that was raise... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
d525f4c7d129-3 | except OutputParserException as e:
new_completion = self.retry_chain.run(
prompt=prompt_value.to_string(), completion=completion, error=repr(e)
)
parsed_completion = self.parser.parse(new_completion)
return parsed_completion
[docs] async def aparse_with_pro... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
e327bd2b3830-0 | Source code for langchain.output_parsers.openai_functions
import copy
import json
from typing import Any, Dict, List, Type, Union
from pydantic import BaseModel, root_validator
from langchain.schema import (
ChatGeneration,
Generation,
OutputParserException,
)
from langchain.schema.output_parser import Base... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html |
e327bd2b3830-1 | return function_call_info
[docs]class JsonKeyOutputFunctionsParser(JsonOutputFunctionsParser):
"""Parse an output as the element of the Json object."""
key_name: str
"""The name of the key to return."""
[docs] def parse_result(self, result: List[Generation]) -> Any:
res = super().parse_result(res... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html |
e327bd2b3830-2 | return pydantic_args
[docs]class PydanticAttrOutputFunctionsParser(PydanticOutputFunctionsParser):
"""Parse an output as an attribute of a pydantic object."""
attr_name: str
"""The name of the attribute to return."""
[docs] def parse_result(self, result: List[Generation]) -> Any:
result = super()... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html |
01284bacca4e-0 | Source code for langchain.output_parsers.combining
from __future__ import annotations
from typing import Any, Dict, List
from pydantic import root_validator
from langchain.schema import BaseOutputParser
[docs]class CombiningOutputParser(BaseOutputParser):
"""Combine multiple output parsers into one."""
@propert... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/combining.html |
01284bacca4e-1 | texts = text.split("\n\n")
output = dict()
for txt, parser in zip(texts, self.parsers):
output.update(parser.parse(txt.strip()))
return output | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/combining.html |
6a7da42a96a0-0 | Source code for langchain.output_parsers.loading
from langchain.output_parsers.regex import RegexParser
[docs]def load_output_parser(config: dict) -> dict:
"""Load an output parser.
Args:
config: config dict
Returns:
config dict with output parser loaded
"""
if "output_parsers" in co... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/loading.html |
a5c1a980f393-0 | Source code for langchain.output_parsers.pydantic
import json
import re
from typing import Type, TypeVar
from pydantic import BaseModel, ValidationError
from langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS
from langchain.schema import BaseOutputParser, OutputParserException
T = TypeVar(... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
a5c1a980f393-1 | schema_str = json.dumps(reduced_schema)
return PYDANTIC_FORMAT_INSTRUCTIONS.format(schema=schema_str)
@property
def _type(self) -> str:
return "pydantic" | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
d694bdc8a240-0 | Source code for langchain.output_parsers.fix
from __future__ import annotations
from typing import TypeVar
from langchain.chains.llm import LLMChain
from langchain.output_parsers.prompts import NAIVE_FIX_PROMPT
from langchain.schema import BaseOutputParser, BasePromptTemplate, OutputParserException
from langchain.schem... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html |
d694bdc8a240-1 | )
parsed_completion = self.parser.parse(new_completion)
return parsed_completion
[docs] async def aparse(self, completion: str) -> T:
try:
parsed_completion = self.parser.parse(completion)
except OutputParserException as e:
new_completion = await self.retry... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html |
f94b7aa441dd-0 | Source code for langchain.output_parsers.json
from __future__ import annotations
import json
import re
from json import JSONDecodeError
from typing import Any, List
from langchain.schema import BaseOutputParser, OutputParserException
def _replace_new_line(match: re.Match[str]) -> str:
value = match.group(2)
val... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html |
f94b7aa441dd-1 | """
# Try to find JSON string within triple backticks
match = re.search(r"```(json)?(.*)```", json_string, re.DOTALL)
# If no match found, assume the entire string is a JSON string
if match is None:
json_str = json_string
else:
# If match found, use the content within the backticks
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html |
f94b7aa441dd-2 | """Parse the output of an LLM call to a JSON object."""
[docs] def parse(self, text: str) -> Any:
text = text.strip()
try:
return json.loads(text)
except JSONDecodeError as e:
raise OutputParserException(f"Invalid json output: {text}") from e
@property
def _typ... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html |
9d90557bce25-0 | Source code for langchain.output_parsers.datetime
import random
from datetime import datetime, timedelta
from typing import List
from langchain.schema import BaseOutputParser, OutputParserException
from langchain.utils import comma_list
def _generate_random_datetime_strings(
pattern: str,
n: int = 3,
start_... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html |
9d90557bce25-1 | return datetime.strptime(response.strip(), self.format)
except ValueError as e:
raise OutputParserException(
f"Could not parse datetime string: {response}"
) from e
@property
def _type(self) -> str:
return "datetime" | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html |
a2c8f3968f66-0 | Source code for langchain.output_parsers.regex_dict
from __future__ import annotations
import re
from typing import Dict, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexDictParser(BaseOutputParser):
"""Parse the output of an LLM call into a Dictionary using a regex."""
regex_pattern: st... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html |
a2c8f3968f66-1 | continue
else:
result[output_key] = matches[0]
return result | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html |
c2dd755b6d1c-0 | Source code for langchain.output_parsers.rail_parser
from __future__ import annotations
from typing import Any, Callable, Dict, Optional
from langchain.schema import BaseOutputParser
[docs]class GuardrailsOutputParser(BaseOutputParser):
"""Parse the output of an LLM call using Guardrails."""
guard: Any
"""T... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html |
c2dd755b6d1c-1 | guard=Guard.from_rail(rail_file, num_reasks=num_reasks),
api=api,
args=args,
kwargs=kwargs,
)
[docs] @classmethod
def from_rail_string(
cls,
rail_str: str,
num_reasks: int = 1,
api: Optional[Callable] = None,
*args: Any,
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html |
c2dd755b6d1c-2 | return self.guard.raw_prompt.format_instructions
[docs] def parse(self, text: str) -> Dict:
return self.guard.parse(text, llm_api=self.api, *self.args, **self.kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html |
8ff5045d66f4-0 | Source code for langchain.output_parsers.regex
from __future__ import annotations
import re
from typing import Dict, List, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexParser(BaseOutputParser):
"""Parse the output of an LLM call using a regex."""
@property
def lc_serializable(self... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/regex.html |
91e9b0f67c1d-0 | Source code for langchain.output_parsers.enum
from enum import Enum
from typing import Any, Dict, List, Type
from pydantic import root_validator
from langchain.schema import BaseOutputParser, OutputParserException
[docs]class EnumOutputParser(BaseOutputParser):
"""Parse an output that is one of a set of values."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/enum.html |
2afd113f9fba-0 | Source code for langchain.smith.evaluation.string_run_evaluator
"""Run evaluator wrapper for string evaluators."""
from __future__ import annotations
from abc import abstractmethod
from typing import Any, Dict, List, Optional
from langsmith import EvaluationResult, RunEvaluator
from langsmith.schemas import DataType, E... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
2afd113f9fba-1 | return self.map(run)
[docs]class LLMStringRunMapper(StringRunMapper):
"""Extract items to evaluate from the run object."""
[docs] def serialize_chat_messages(self, messages: List[Dict]) -> str:
"""Extract the input messages from the run."""
if isinstance(messages, list) and messages:
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
2afd113f9fba-2 | first_generation: Dict = generations[0]
if isinstance(first_generation, list):
# Runs from Tracer have generations as a list of lists of dicts
# Whereas Runs from the API have a list of dicts
first_generation = first_generation[0]
if "message" in first_generation:
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
2afd113f9fba-3 | """The key from the model Run's inputs to use as the eval input.
If not provided, will use the only input key or raise an
error if there are multiple."""
prediction_key: Optional[str] = None
"""The key from the model Run's outputs to use as the eval prediction.
If not provided, will use the only out... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
2afd113f9fba-4 | "input": input_,
"prediction": prediction,
}
[docs]class ToolStringRunMapper(StringRunMapper):
"""Map an input to the tool."""
[docs] def map(self, run: Run) -> Dict[str, str]:
if not run.outputs:
raise ValueError(f"Run {run.id} has no outputs to evaluate.")
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
2afd113f9fba-5 | raise ValueError(
f"Example {example.id} does not have reference key"
f" {self.reference_key}."
)
else:
output = example.outputs[self.reference_key]
return {
"reference": self.serialize_chat_messages([output])
if isinstance(... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
2afd113f9fba-6 | if not self.string_evaluator.requires_input:
# Hide warning about unused input
evaluate_strings_inputs.pop("input", None)
if example and self.example_mapper and self.string_evaluator.requires_reference:
evaluate_strings_inputs.update(self.example_mapper(example))
elif... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
2afd113f9fba-7 | ) -> Dict[str, Any]:
"""Call the evaluation chain."""
evaluate_strings_inputs = self._prepare_input(inputs)
_run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()
callbacks = _run_manager.get_child()
chain_output = await self.string_evaluator.aevaluate_s... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
2afd113f9fba-8 | reference_key: Optional[str] = None,
tags: Optional[List[str]] = None,
) -> StringRunEvaluatorChain:
"""
Create a StringRunEvaluatorChain from an evaluator and the run and dataset types.
This method provides an easy way to instantiate a StringRunEvaluatorChain, by
taking an e... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
2afd113f9fba-9 | )
# Configure how example rows are fed as a reference string to the evaluator
if reference_key is not None or data_type in (DataType.llm, DataType.chat):
example_mapper = StringExampleMapper(reference_key=reference_key)
elif evaluator.requires_reference:
raise ValueError(... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
8d277d257744-0 | Source code for langchain.smith.evaluation.config
"""Configuration for run evaluators."""
from typing import Any, Dict, List, Optional, Union
from langsmith import RunEvaluator
from pydantic import BaseModel, Field
from langchain.embeddings.base import Embeddings
from langchain.evaluation.criteria.eval_chain import CRI... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html |
8d277d257744-1 | Configurations for which evaluators to apply to the dataset run.
Each can be the string of an :class:`EvaluatorType <langchain.evaluation.schema.EvaluatorType>`, such
as EvaluatorType.QA, the evaluator type string ("qa"), or a configuration for a
given evaluator (e.g., :class:`RunEvalConfig.QA <... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html |
8d277d257744-2 | given evaluator
(e.g.,
:class:`RunEvalConfig.QA <langchain.smith.evaluation.config.RunEvalConfig.QA>`).""" # noqa: E501
custom_evaluators: Optional[List[Union[RunEvaluator, StringEvaluator]]] = None
"""Custom evaluators to apply to the dataset run."""
reference_key: Optional[str] = None
"""The... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html |
8d277d257744-3 | ) -> None:
super().__init__(criteria=criteria, **kwargs)
[docs] class LabeledCriteria(EvalConfig):
"""Configuration for a labeled (with references) criteria evaluator.
Parameters
----------
criteria : Optional[CRITERIA_TYPE]
The criteria to evaluate.
ll... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html |
8d277d257744-4 | distance: Optional[StringDistanceEnum] = None
"""The string distance metric to use.
damerau_levenshtein: The Damerau-Levenshtein distance.
levenshtein: The Levenshtein distance.
jaro: The Jaro distance.
jaro_winkler: The Jaro-Winkler distance.
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html |
8d277d257744-5 | Parameters
----------
prompt : Optional[BasePromptTemplate]
The prompt template to use for generating the question.
llm : Optional[BaseLanguageModel]
The language model to use for the evaluation chain.
"""
evaluator_type: EvaluatorType = EvaluatorType.CONT... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html |
baafdf8a2eb9-0 | Source code for langchain.smith.evaluation.runner_utils
"""Utilities for running language models or Chains over datasets."""
from __future__ import annotations
import asyncio
import functools
import inspect
import itertools
import logging
import uuid
from enum import Enum
from typing import (
Any,
Callable,
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-1 | MCF = Union[Callable[[], Union[Chain, Runnable]], BaseLanguageModel]
[docs]class InputFormatError(Exception):
"""Raised when the input format is invalid."""
## Shared Utilities
def _get_eval_project_url(api_url: str, project_id: str) -> str:
"""Get the project url from the api url."""
parsed = urlparse(api_... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-2 | "\nFor example:\n\n"
"def chain_constructor():\n"
f" new_memory = {memory_class}(...)\n"
f" return {chain_class}"
"(memory=new_memory, ...)\n\n"
f'run_on_dataset("{dataset_name}", chain_constructor, ...)'
)
logger.... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-3 | logger.info(f"Wrapping function {sig} as RunnableLambda.")
wrapped = RunnableLambda(user_func)
return lambda: wrapped
constructor = cast(Callable, llm_or_chain_factory)
if isinstance(_model, BaseLanguageModel):
# It's not uncommon to do an LLM constructor instead of r... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-4 | prompts = [inputs["prompt"]]
elif "prompts" in inputs:
if not isinstance(inputs["prompts"], list) or not all(
isinstance(i, str) for i in inputs["prompts"]
):
raise InputFormatError(
"Expected list of strings for 'prompts',"
f" got {type(inputs... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-5 | single_input = inputs["messages"]
elif len(inputs) == 1:
single_input = next(iter(inputs.values()))
else:
raise InputFormatError(
f"Chat Run expects 'messages' in inputs when example has multiple"
f" input keys. Got {inputs}"
)
if isinstance(single_input, list... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-6 | model_name = llm_or_chain_factory.__class__.__name__
else:
model_name = llm_or_chain_factory().__class__.__name__
hex = uuid.uuid4().hex
return f"{hex}-{model_name}"
## Shared Validation Utilities
def _validate_example_inputs_for_language_model(
first_example: Example,
input_mapper: Optional... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-7 | input_mapper: Optional[Callable[[Dict], Any]],
) -> None:
"""Validate that the example inputs match the chain input keys."""
if input_mapper:
first_inputs = input_mapper(first_example.inputs)
missing_keys = set(chain.input_keys).difference(first_inputs)
if not isinstance(first_inputs, di... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-8 | """Validate that the example inputs are valid for the model."""
first_example, examples = _first_example(examples)
if isinstance(llm_or_chain_factory, BaseLanguageModel):
_validate_example_inputs_for_language_model(first_example, input_mapper)
else:
chain = llm_or_chain_factory()
if ... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-9 | run_outputs = chain.output_keys if isinstance(chain, Chain) else None
run_evaluators = _load_run_evaluators(
evaluation,
run_type,
data_type,
list(first_example.outputs) if first_example.outputs else None,
run_inputs,
run_outputs,
)... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-10 | raise ValueError(
f"Must specify prediction key for model"
f" with multiple outputs: {run_outputs}"
)
return prediction_key
def _determine_reference_key(
config: RunEvalConfig,
example_outputs: Optional[List[str]],
) -> Optional[str]:
if config.reference_key:
refe... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-11 | f" evaluator of type {eval_type_tag} with"
f" dataset with multiple output keys: {example_outputs}."
)
run_evaluator = StringRunEvaluatorChain.from_run_and_data_type(
evaluator_,
run_type,
data_type,
input_key=input_key,
pre... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-12 | prediction_key,
)
run_evaluators.append(run_evaluator)
custom_evaluators = config.custom_evaluators or []
for custom_evaluator in custom_evaluators:
if isinstance(custom_evaluator, RunEvaluator):
run_evaluators.append(custom_evaluator)
elif isinstance(custom_evaluator... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-13 | """
if input_mapper is not None:
prompt_or_messages = input_mapper(inputs)
if isinstance(prompt_or_messages, str):
return await llm.apredict(
prompt_or_messages, callbacks=callbacks, tags=tags
)
elif isinstance(prompt_or_messages, list) and all(
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-14 | val = next(iter(inputs_.values()))
output = await chain.acall(val, callbacks=callbacks, tags=tags)
else:
output = await chain.acall(inputs_, callbacks=callbacks, tags=tags)
else:
runnable_config = RunnableConfig(tags=tags or [], callbacks=callbacks)
output = await cha... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-15 | previous_example_ids = None
outputs = []
chain_or_llm = (
"LLM" if isinstance(llm_or_chain_factory, BaseLanguageModel) else "Chain"
)
for _ in range(n_repetitions):
try:
if isinstance(llm_or_chain_factory, BaseLanguageModel):
output: Any = await _arun_llm(
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-16 | async_funcs: The async_funcs to be run concurrently.
Returns:
A list of results from the coroutines.
"""
semaphore = asyncio.Semaphore(n)
job_state = {"num_processed": 0}
callback_queue: asyncio.Queue[Sequence[BaseCallbackHandler]] = asyncio.Queue()
for _ in range(n):
callback_qu... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-17 | run_evaluators: The evaluators to run.
evaluation_handler_collector: A list to collect the evaluators.
Used to wait for the evaluators to finish.
Returns:
The callbacks for this thread.
"""
callbacks: List[BaseTracer] = []
if project_name:
callbacks.append(
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-18 | llm_or_chain_factory: Language model or Chain constructor to run
over the dataset. The Chain constructor is used to permit
independent calls on each example without carrying over state.
evaluation: Optional evaluation configuration to use when evaluating
concurrency_level: The nu... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-19 | ) -> None:
"""Process a single example."""
result = await _arun_llm_or_chain(
example,
wrapped_model,
num_repetitions,
tags=tags,
callbacks=callbacks,
input_mapper=input_mapper,
)
results[str(example.id)] = result
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-20 | input_mapper: function to map to the inputs dictionary from an Example
Returns:
The LLMResult or ChatResult.
Raises:
ValueError: If the LLM type is unsupported.
InputFormatError: If the input format is invalid.
"""
if input_mapper is not None:
prompt_or_messages = input_m... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-21 | ) -> Union[Dict, str]:
"""Run a chain on inputs."""
inputs_ = inputs if input_mapper is None else input_mapper(inputs)
if isinstance(chain, Chain):
if isinstance(inputs_, dict) and len(inputs_) == 1:
val = next(iter(inputs_.values()))
output = chain(val, callbacks=callbacks, ... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-22 | getattr(tracer, "example_id", None) for tracer in callbacks
]
for tracer in callbacks:
if hasattr(tracer, "example_id"):
tracer.example_id = example.id
else:
previous_example_ids = None
outputs = []
chain_or_llm = (
"LLM" if isinstance(llm_or_chain... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-23 | num_repetitions: int = 1,
project_name: Optional[str] = None,
verbose: bool = False,
tags: Optional[List[str]] = None,
input_mapper: Optional[Callable[[Dict], Any]] = None,
data_type: DataType = DataType.kv,
) -> Dict[str, Any]:
"""
Run the Chain or language model on examples and store
t... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-24 | """
results: Dict[str, Any] = {}
llm_or_chain_factory = _wrap_in_chain_factory(llm_or_chain_factory)
project_name = _get_project_name(project_name, llm_or_chain_factory)
tracer = LangChainTracer(
project_name=project_name, client=client, use_threading=False
)
run_evaluators, examples = _... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-25 | try:
project = client.create_project(project_name)
except ValueError as e:
if "already exists " not in str(e):
raise e
raise ValueError(
f"Project {project_name} already exists. Please use a different name."
)
project_url = _get_eval_project_url(client.api... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-26 | evaluation: Optional evaluation configuration to use when evaluating
concurrency_level: The number of async tasks to run concurrently.
num_repetitions: Number of times to run the model on each example.
This is useful when testing success rates or generating confidence
intervals.
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-27 | evaluation_config = RunEvalConfig(
evaluators=[
"qa", # "Correctness" against a reference answer
"embedding_distance",
RunEvalConfig.Criteria("helpfulness"),
RunEvalConfig.Criteria({
"fifth-grader-score": "Do you have to be... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-28 | client, dataset_name, llm_or_chain_factory, project_name
)
results = await _arun_on_examples(
client,
examples,
llm_or_chain_factory,
concurrency_level=concurrency_level,
num_repetitions=num_repetitions,
project_name=project_name,
verbose=verbose,
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-29 | ) -> Dict[str, Any]:
"""
Run the Chain or language model on a dataset and store traces
to the specified project name.
Args:
client: LangSmith client to use to access the dataset and to
log feedback and run traces.
dataset_name: Name of the dataset to run the chain on.
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-30 | from langchain.smith import RunEvalConfig, run_on_dataset
# Chains may have memory. Passing in a constructor function lets the
# evaluation framework avoid cross-contamination between runs.
def construct_chain():
llm = ChatOpenAI(temperature=0)
chain = LLMChain.from_strin... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
baafdf8a2eb9-31 | return {"score": prediction == reference}
evaluation_config = RunEvalConfig(
custom_evaluators = [MyStringEvaluator()],
)
run_on_dataset(
client,
"<my_dataset_name>",
construct_chain,
evaluation=evaluation_config,
)
""" # n... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
83425ba005ea-0 | Source code for langchain_experimental.llms.rellm_decoder
"""Experimental implementation of RELLM wrapped LLM."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Optional, cast
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.huggingface_pipeline impor... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/rellm_decoder.html |
83425ba005ea-1 | ) -> str:
rellm = import_rellm()
from transformers import Text2TextGenerationPipeline
pipeline = cast(Text2TextGenerationPipeline, self.pipeline)
text = rellm.complete_re(
prompt,
self.regex,
tokenizer=pipeline.tokenizer,
model=pipeline.mod... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/rellm_decoder.html |
e535e2ad4e9f-0 | Source code for langchain_experimental.llms.jsonformer_decoder
"""Experimental implementation of jsonformer wrapped LLM."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, List, Optional, cast
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.hugg... | https://api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/jsonformer_decoder.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.