id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
8b66c083e60d-10 | "wrist",
"writer",
"yard",
"yoke",
"zebra",
"zinc",
"zipper",
"zone",
]
[docs]def random_name(prefix: str = "test") -> str:
"""Generate a random name."""
adjective = random.choice(adjectives)
noun = random.choice(nouns)
number = random.randint(1, 100)
return f"{prefix}-{a... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html |
252b0881c19e-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 langchain.evaluation.criteria.eval_chain import CRITERIA_TYPE
from langchain.evaluation.embedding_distance.base import (
EmbeddingDist... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html |
252b0881c19e-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 |
252b0881c19e-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 |
252b0881c19e-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 |
252b0881c19e-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 |
252b0881c19e-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 |
cea5f952d9e9-0 | Source code for langchain.smith.evaluation.progress
"""A simple progress bar for the console."""
import threading
from typing import Any, Dict, Optional, Sequence
from uuid import UUID
from langchain.callbacks import base as base_callbacks
from langchain.schema.document import Document
from langchain.schema.output impo... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/progress.html |
cea5f952d9e9-1 | ) -> Any:
if parent_run_id is None:
self.increment()
[docs] def on_retriever_end(
self,
documents: Sequence[Document],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> Any:
if parent_run_id is None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/progress.html |
c05f08480549-0 | Source code for langchain.smith.evaluation.runner_utils
"""Utilities for running language models or Chains over datasets."""
from __future__ import annotations
import functools
import inspect
import logging
import warnings
from enum import Enum
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-1 | Callable[[dict], Any],
Runnable,
Chain,
]
MCF = Union[Callable[[], Union[Chain, Runnable]], BaseLanguageModel]
[docs]class InputFormatError(Exception):
"""Raised when the input format is invalid."""
## Shared Utilities
[docs]class TestResult(dict):
"""A dictionary of the results of a single test run."""... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-2 | records = []
for example_id, result in self["results"].items():
feedback = result["feedback"]
r = {
**{f.key: f.score for f in feedback},
"input": result["input"],
"output": result["output"],
}
if "reference" in resu... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-3 | )
return lambda: chain
elif isinstance(llm_or_chain_factory, BaseLanguageModel):
return llm_or_chain_factory
elif isinstance(llm_or_chain_factory, Runnable):
# Memory may exist here, but it's not elegant to check all those cases.
lcf = llm_or_chain_factory
return lambda: ... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-4 | raise InputFormatError("Inputs should not be empty.")
prompts = []
if "prompt" in inputs:
if not isinstance(inputs["prompt"], str):
raise InputFormatError(
"Expected string for 'prompt', got"
f" {type(inputs['prompt']).__name__}"
)
prompts ... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-5 | inputs: The input dictionary.
Returns:
A list of chat messages.
Raises:
InputFormatError: If the input format is invalid.
"""
if not inputs:
raise InputFormatError("Inputs should not be empty.")
if "messages" in inputs:
single_input = inputs["messages"]
elif len(i... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-6 | if input_mapper:
prompt_input = input_mapper(first_example.inputs)
if not isinstance(prompt_input, str) and not (
isinstance(prompt_input, list)
and all(isinstance(msg, BaseMessage) for msg in prompt_input)
):
raise InputFormatError(
"When usin... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-7 | " inputs for a chain, the mapped value must be a dictionary."
f"\nGot: {first_inputs} of type {type(first_inputs)}."
)
if missing_keys:
raise InputFormatError(
"Missing keys after loading example using input_mapper."
f"\nExpected: {chain.in... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-8 | ## Shared Evaluator Setup Utilities
def _setup_evaluation(
llm_or_chain_factory: MCF,
examples: List[Example],
evaluation: Optional[smith_eval.RunEvalConfig],
data_type: DataType,
) -> Optional[List[RunEvaluator]]:
"""Configure the evaluators to run on the results of the chain."""
if evaluation:... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-9 | if config.input_key:
input_key = config.input_key
if run_inputs and input_key not in run_inputs:
raise ValueError(f"Input key {input_key} not in run inputs {run_inputs}")
elif run_inputs and len(run_inputs) == 1:
input_key = run_inputs[0]
elif run_inputs is not None and len(r... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-10 | )
elif example_outputs and len(example_outputs) == 1:
reference_key = list(example_outputs)[0]
else:
reference_key = None
return reference_key
def _construct_run_evaluator(
eval_config: Union[EvaluatorType, str, smith_eval_config.EvalConfig],
eval_llm: Optional[BaseLanguageModel],
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-11 | reference_key=reference_key,
tags=[eval_type_tag],
)
elif isinstance(evaluator_, PairwiseStringEvaluator):
raise NotImplementedError(
f"Run evaluator for {eval_type_tag} is not implemented."
" PairwiseStringEvaluators compare the outputs of two different models"
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-12 | A list of run evaluators.
"""
run_evaluators = []
input_key, prediction_key, reference_key = None, None, None
if (
config.evaluators
or any([isinstance(e, EvaluatorType) for e in config.evaluators])
or (
config.custom_evaluators
and any([isinstance(e, Stri... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-13 | return run_evaluators
### Async Helpers
async def _arun_llm(
llm: BaseLanguageModel,
inputs: Dict[str, Any],
*,
tags: Optional[List[str]] = None,
callbacks: Callbacks = None,
input_mapper: Optional[Callable[[Dict], Any]] = None,
) -> Union[str, BaseMessage]:
"""Asynchronously run the languag... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-14 | llm_output: Union[str, BaseMessage] = await llm.apredict(
prompt, callbacks=callbacks, tags=tags
)
except InputFormatError:
messages = _get_messages(inputs)
llm_output = await llm.apredict_messages(
messages, callbacks=callbacks, tags=tags
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-15 | llm_or_chain_factory: The Chain or language model constructor to run.
tags: Optional tags to add to the run.
callbacks: Optional callbacks to use during the run.
input_mapper: Optional function to map the input to the expected format.
Returns:
A list of outputs.
"""
chain_or_... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-16 | """
Run the language model on the example.
Args:
llm: The language model to run.
inputs: The input dictionary.
callbacks: The callbacks to use during the run.
tags: Optional tags to add to the run.
input_mapper: function to map to the inputs dictionary from an Example
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-17 | chain: Union[Chain, Runnable],
inputs: Dict[str, Any],
callbacks: Callbacks,
*,
tags: Optional[List[str]] = None,
input_mapper: Optional[Callable[[Dict], Any]] = None,
) -> Union[Dict, str]:
"""Run a chain on inputs."""
inputs_ = inputs if input_mapper is None else input_mapper(inputs)
i... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-18 | )
result = None
try:
if isinstance(llm_or_chain_factory, BaseLanguageModel):
output: Any = _run_llm(
llm_or_chain_factory,
example.inputs,
config["callbacks"],
tags=config["tags"],
input_mapper=input_mapper,
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-19 | raise e
raise ValueError(
f"Project {project_name} already exists. Please use a different name."
)
print(
f"View the evaluation results for project '{project_name}' at:\n{project.url}",
flush=True,
)
examples = list(client.list_examples(dataset_id=dataset.id))
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-20 | RunnableConfig(
callbacks=[
LangChainTracer(
project_name=project_name,
client=client,
use_threading=False,
example_id=example.id,
),
EvaluatorCallbackHandler(
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-21 | "will be removed in a future release. Please add a "
" RunnableLambda to your chain to map inputs to the expected format"
" instead. Example:\n"
"def construct_chain():\n"
" my_chain = ...\n"
" input_mapper = {'other_key': 'MyOtherInput', 'my_input_key': x}\n"
" return input_mapper | my... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-22 | client,
dataset_name,
llm_or_chain_factory,
project_name,
evaluation,
tags,
input_mapper,
concurrency_level,
project_metadata=project_metadata,
)
batch_results = await runnable_utils.gather_with_concurrency(
configs[0].get("max_concurrency"... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-23 | DeprecationWarning,
)
if kwargs:
warnings.warn(
"The following arguments are deprecated and "
"will be removed in a future release: "
f"{kwargs.keys()}.",
DeprecationWarning,
)
client = client or Client()
wrapped_model, project_name, ex... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-24 | Run the Chain or language model on a dataset and store traces
to the specified project name.
Args:
dataset_name: Name of the dataset to run the chain on.
llm_or_chain_factory: Language model or Chain constructor to run
over the dataset. The Chain constructor is used to permit
independent calls o... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-25 | "What's the answer to {your_input_key}"
)
return chain
# Load off-the-shelf evaluators via config or the EvaluatorType (string or enum)
evaluation_config = smith_eval.RunEvalConfig(
evaluators=[
"qa", # "Correctness" against a reference answer
"embedding_distance... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
c05f08480549-26 | evaluation=evaluation_config,
)
""" # noqa: E501
run_on_dataset.__doc__ = _RUN_ON_DATASET_DOCSTRING
arun_on_dataset.__doc__ = _RUN_ON_DATASET_DOCSTRING.replace(
"run_on_dataset(", "await arun_on_dataset("
) | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
32044eb4bb6d-0 | Source code for langchain.utils.pydantic
"""Utilities for tests."""
[docs]def get_pydantic_major_version() -> int:
"""Get the major version of Pydantic."""
try:
import pydantic
return int(pydantic.__version__.split(".")[0])
except ImportError:
return 0
PYDANTIC_MAJOR_VERSION = get_py... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/pydantic.html |
cf51028eb408-0 | Source code for langchain.utils.utils
"""Generic utility functions."""
import contextlib
import datetime
import functools
import importlib
import warnings
from importlib.metadata import version
from typing import Any, Callable, Dict, Optional, Set, Tuple
from packaging.version import parse
from requests import HTTPErro... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
cf51028eb408-1 | """Context manager for mocking out datetime.now() in unit tests.
Example:
with mock_now(datetime.datetime(2011, 2, 3, 10, 11)):
assert datetime.datetime.now() == datetime.datetime(2011, 2, 3, 10, 11)
"""
class MockDateTime(datetime.datetime):
"""Mock datetime.datetime.now() with a fixed ... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
cf51028eb408-2 | gte_version: Optional[str] = None,
) -> None:
"""Check the version of a package."""
imported_version = parse(version(package))
if lt_version is not None and imported_version >= parse(lt_version):
raise ValueError(
f"Expected {package} version to be < {lt_version}. Received "
... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
cf51028eb408-3 | values: Dict[str, Any],
all_required_field_names: Set[str],
) -> Dict[str, Any]:
"""Build extra kwargs from values and extra_kwargs.
Args:
extra_kwargs: Extra kwargs passed in by user.
values: Values passed in by user.
all_required_field_names: All required field names for the pydant... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
9865089be3e7-0 | Source code for langchain.utils.formatting
"""Utilities for formatting strings."""
from string import Formatter
from typing import Any, List, Mapping, Sequence, Union
[docs]class StrictFormatter(Formatter):
"""A subclass of formatter that checks for extra keys."""
[docs] def check_unused_args(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/formatting.html |
5cf4a0c0a906-0 | Source code for langchain.utils.math
"""Math utils."""
from typing import List, Optional, Tuple, Union
import numpy as np
Matrix = Union[List[List[float]], List[np.ndarray], np.ndarray]
[docs]def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray:
"""Row-wise cosine similarity between two equal-width matrices.""... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/math.html |
5cf4a0c0a906-1 | score_threshold: Minimum cosine similarity of results.
Returns:
Tuple of two lists. First contains two-tuples of indices (X_idx, Y_idx),
second contains corresponding cosine similarities.
"""
if len(X) == 0 or len(Y) == 0:
return [], []
score_array = cosine_similarity(X, Y)
... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/math.html |
0fbcd0b7853d-0 | Source code for langchain.utils.json_schema
from __future__ import annotations
from copy import deepcopy
from typing import Any, List, Optional, Sequence
def _retrieve_ref(path: str, schema: dict) -> dict:
components = path.split("/")
if components[0] != "#":
raise ValueError(
"ref paths are... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/json_schema.html |
0fbcd0b7853d-1 | keys += _infer_skip_keys(ref, full_schema)
elif isinstance(v, (list, dict)):
keys += _infer_skip_keys(v, full_schema)
elif isinstance(obj, list):
for el in obj:
keys += _infer_skip_keys(el, full_schema)
return keys
[docs]def dereference_refs(
schema_obj: dict,... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/json_schema.html |
28c60c7df2af-0 | Source code for langchain.utils.aiter
"""
Adapted from
https://github.com/maxfischer2781/asyncstdlib/blob/master/asyncstdlib/itertools.py
MIT License
"""
from collections import deque
from typing import (
Any,
AsyncContextManager,
AsyncGenerator,
AsyncIterator,
Awaitable,
Callable,
Deque,
... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html |
28c60c7df2af-1 | # The C code is way more low-level than this, as it implements
# all methods of the iterator protocol. In this implementation
# we're relying on higher-level coroutine concepts, but that's
# exactly what we want -- crosstest pure-Python high-level
# implementation and low... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html |
28c60c7df2af-2 | # This ensures the proper item ordering if any of our peers
# are fetching items concurrently. They may have buffered their
# item already.
for peer_buffer in peers:
peer_buffer.append(item)
yield buffer.popl... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html |
28c60c7df2af-3 | to get the child iterators. In addition, its :py:meth:`~.tee.aclose` method
immediately closes all children, and it can be used in an ``async with`` context
for the same effect.
If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*
provide these items. Also, ``tee`` must internally buffe... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html |
28c60c7df2af-4 | )
def __len__(self) -> int:
return len(self._children)
@overload
def __getitem__(self, item: int) -> AsyncIterator[T]:
...
@overload
def __getitem__(self, item: slice) -> Tuple[AsyncIterator[T], ...]:
...
def __getitem__(
self, item: Union[int, slice]
) -> Uni... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html |
5481f7fc02c1-0 | Source code for langchain.utils.html
import re
from typing import List, Optional, Sequence, Union
from urllib.parse import urljoin, urlparse
PREFIXES_TO_IGNORE = ("javascript:", "mailto:", "#")
SUFFIXES_TO_IGNORE = (
".css",
".js",
".ico",
".png",
".jpg",
".jpeg",
".gif",
".svg",
".c... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/html.html |
5481f7fc02c1-1 | Args:
raw_html: original html.
url: the url of the html.
base_url: the base url to check for outside links against.
pattern: Regex to use for extracting links from raw html.
prevent_outside: If True, ignore external links which are not children
of the base url.
... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/html.html |
67839babeb58-0 | Source code for langchain.utils.input
"""Handle chained inputs."""
from typing import Dict, List, Optional, TextIO
_TEXT_COLOR_MAPPING = {
"blue": "36;1",
"yellow": "33;1",
"pink": "38;5;200",
"green": "32;1",
"red": "31;1",
}
[docs]def get_color_mapping(
items: List[str], excluded_colors: Optio... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/input.html |
67839babeb58-1 | print(text_to_print, end=end, file=file)
if file:
file.flush() # ensure all printed content are written to file | https://api.python.langchain.com/en/latest/_modules/langchain/utils/input.html |
1b192cfeddd5-0 | Source code for langchain.utils.openai_functions
from typing import Optional, Type, TypedDict
from langchain.pydantic_v1 import BaseModel
from langchain.utils.json_schema import dereference_refs
[docs]class FunctionDescription(TypedDict):
"""Representation of a callable function to the OpenAI API."""
name: str
... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/openai_functions.html |
c593243e9e24-0 | Source code for langchain.utils.strings
from typing import Any, List
[docs]def stringify_value(val: Any) -> str:
"""Stringify a value.
Args:
val: The value to stringify.
Returns:
str: The stringified value.
"""
if isinstance(val, str):
return val
elif isinstance(val, dict... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/strings.html |
545d0a837e80-0 | Source code for langchain.utils.iter
from collections import deque
from itertools import islice
from typing import (
Any,
ContextManager,
Deque,
Generator,
Generic,
Iterable,
Iterator,
List,
Optional,
Tuple,
TypeVar,
Union,
overload,
)
from typing_extensions import Li... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html |
545d0a837e80-1 | # are fetching items concurrently. They may have buffered their
# item already.
for peer_buffer in peers:
peer_buffer.append(item)
yield buffer.popleft()
finally:
with lock:
# this peer is done – remove its b... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html |
545d0a837e80-2 | immediately closes all children, and it can be used in an ``async with`` context
for the same effect.
If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*
provide these items. Also, ``tee`` must internally buffer each item until the
last iterator has yielded it; if the most and least ad... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html |
545d0a837e80-3 | ...
@overload
def __getitem__(self, item: slice) -> Tuple[Iterator[T], ...]:
...
def __getitem__(
self, item: Union[int, slice]
) -> Union[Iterator[T], Tuple[Iterator[T], ...]]:
return self._children[item]
def __iter__(self) -> Iterator[Iterator[T]]:
yield from self._... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html |
793310d76477-0 | Source code for langchain.utils.loading
"""Utilities for loading configurations from langchain-hub."""
import os
import re
import tempfile
from pathlib import Path, PurePosixPath
from typing import Any, Callable, Optional, Set, TypeVar, Union
from urllib.parse import urljoin
import requests
DEFAULT_REF = os.environ.get... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/loading.html |
793310d76477-1 | # when working with URLs that use forward slashes as the path separator.
# Instead, use PurePosixPath to ensure that forward slashes are used as the
# path separator, regardless of the operating system.
full_url = urljoin(URL_BASE.format(ref=ref), PurePosixPath(remote_path).__str__())
r = requests.get(f... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/loading.html |
a5b0f4cb6055-0 | Source code for langchain.utils.env
import os
from typing import Any, Dict, Optional
[docs]def get_from_dict_or_env(
data: Dict[str, Any], key: str, env_key: str, default: Optional[str] = None
) -> str:
"""Get a value from a dictionary or an environment variable."""
if key in data and data[key]:
ret... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/env.html |
41ceef3947dd-0 | Source code for langchain.embeddings.cohere
from typing import Any, Dict, List, Optional
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.schema.embeddings import Embeddings
from langchain.utils import get_from_dict_or_env
[docs]class CohereEmbeddings(BaseModel, Embeddings):
"""Cohe... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html |
41ceef3947dd-1 | )
try:
import cohere
values["client"] = cohere.Client(cohere_api_key)
values["async_client"] = cohere.AsyncClient(cohere_api_key)
except ImportError:
raise ValueError(
"Could not import cohere python package. "
"Please insta... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html |
41ceef3947dd-2 | [docs] async def aembed_query(self, text: str) -> List[float]:
"""Async call out to Cohere's embedding endpoint.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
embeddings = await self.aembed_documents([text])
return embeddi... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html |
fcc5f7ed15d0-0 | Source code for langchain.embeddings.self_hosted_hugging_face
import importlib
import logging
from typing import Any, Callable, List, Optional
from langchain.embeddings.self_hosted import SelfHostedEmbeddings
DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
DEFAULT_INSTRUCT_MODEL = "hkunlp/instructor-larg... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
fcc5f7ed15d0-1 | logger.warning(
"Device has %d GPUs available. "
"Provide device={deviceId} to `from_model_id` to use available"
"GPUs for execution. deviceId is -1 for CPU and "
"can be a positive integer associated with CUDA device id.",
cuda_device_coun... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
fcc5f7ed15d0-2 | """Function to load the model remotely on the server."""
load_fn_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model load function."""
inference_fn: Callable = _embed_documents
"""Inference function to extract the embeddings."""
def __init__(self, **kwargs: Any):
"""Init... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
fcc5f7ed15d0-3 | """
model_id: str = DEFAULT_INSTRUCT_MODEL
"""Model name to use."""
embed_instruction: str = DEFAULT_EMBED_INSTRUCTION
"""Instruction to use for embedding documents."""
query_instruction: str = DEFAULT_QUERY_INSTRUCTION
"""Instruction to use for embedding query."""
model_reqs: List[str] = ["... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
fcc5f7ed15d0-4 | Returns:
Embeddings for the text.
"""
instruction_pair = [self.query_instruction, text]
embedding = self.client(self.pipeline_ref, [instruction_pair])[0]
return embedding.tolist() | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
2a31e6bd1710-0 | Source code for langchain.embeddings.gradient_ai
import asyncio
import logging
import os
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Callable, Dict, List, Optional, Tuple
import aiohttp
import numpy as np
import requests
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
fr... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html |
2a31e6bd1710-1 | class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator(allow_reuse=True)
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
values["gradient_access_token"] = get_from... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html |
2a31e6bd1710-2 | """Async call out to Gradient's embedding endpoint.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
embeddings = await self.client.aembed(
model=self.model,
texts=texts,
)
return ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html |
2a31e6bd1710-3 | )
# or
embeds = await mini_client.aembed(
model="bge-large",
text=["doc1", "doc2"]
)
"""
[docs] def __init__(
self,
access_token: Optional[str] = None,
workspace_id: Optional[str] = None,
host: str = "https://api.... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html |
2a31e6bd1710-4 | delivers a lambda expr, which can sort a same length list
https://github.com/UKPLab/sentence-transformers/blob/
c5f93f70eca933c78695c5bc686ceda59651ae3b/sentence_transformers/SentenceTransformer.py#L156
Args:
texts (List[str]): _description_
sorter (Callable, optional): _... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html |
2a31e6bd1710-5 | for start_index in range(0, len(texts), self._batch_size):
batches.append(texts[start_index : start_index + self._batch_size])
return batches
@staticmethod
def _unbatch(batch_of_texts: List[List[Any]]) -> List[Any]:
if len(batch_of_texts) == 1 and len(batch_of_texts[0]) == 1:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html |
2a31e6bd1710-6 | f"{response.status_code}: {response.text}"
)
return [e["embedding"] for e in response.json()["embeddings"]]
[docs] def embed(self, model: str, texts: List[str]) -> List[List[float]]:
"""call the embedding of model
Args:
model (str): to embedding model
texts... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html |
2a31e6bd1710-7 | return [e["embedding"] for e in embedding]
[docs] async def aembed(self, model: str, texts: List[str]) -> List[List[float]]:
"""call the embedding of model, async method
Args:
model (str): to embedding model
texts (List[str]): List of sentences to embed.
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html |
dbe580a65a5d-0 | Source code for langchain.embeddings.huggingface_hub
from typing import Any, Dict, List, Optional
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.schema.embeddings import Embeddings
from langchain.utils import get_from_dict_or_env
DEFAULT_REPO_ID = "sentence-transformers/all-mpnet-base... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
dbe580a65a5d-1 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
huggingfacehub_api_token = get_from_dict_or_env(
values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
)
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
dbe580a65a5d-2 | texts = [text.replace("\n", " ") for text in texts]
_model_kwargs = self.model_kwargs or {}
responses = self.client(inputs=texts, params=_model_kwargs)
return responses
[docs] def embed_query(self, text: str) -> List[float]:
"""Call out to HuggingFaceHub's embedding endpoint for embed... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
c5d7190acc45-0 | Source code for langchain.embeddings.huggingface
from typing import Any, Dict, List, Optional
import requests
from langchain.pydantic_v1 import BaseModel, Extra, Field
from langchain.schema.embeddings import Embeddings
DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
DEFAULT_INSTRUCT_MODEL = "hkunlp/instr... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
c5d7190acc45-1 | Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Key word arguments to pass to the model."""
encode_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Key word arguments to pass when calling the `encode` method of t... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
c5d7190acc45-2 | return embeddings.tolist()
[docs] def embed_query(self, text: str) -> List[float]:
"""Compute query embeddings using a HuggingFace transformer model.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
return self.embed_documents([text]... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
c5d7190acc45-3 | query_instruction: str = DEFAULT_QUERY_INSTRUCTION
"""Instruction to use for embedding query."""
def __init__(self, **kwargs: Any):
"""Initialize the sentence_transformer."""
super().__init__(**kwargs)
try:
from InstructorEmbedding import INSTRUCTOR
self.client = ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
c5d7190acc45-4 | Example:
.. code-block:: python
from langchain.embeddings import HuggingFaceBgeEmbeddings
model_name = "BAAI/bge-large-en"
model_kwargs = {'device': 'cpu'}
encode_kwargs = {'normalize_embeddings': True}
hf = HuggingFaceBgeEmbeddings(
mo... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
c5d7190acc45-5 | self.query_instruction = DEFAULT_QUERY_BGE_INSTRUCTION_ZH
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
[docs] def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Compute doc embeddings using a HuggingFace transformer model.
Args... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
c5d7190acc45-6 | "/pipeline"
"/feature-extraction"
f"/{self.model_name}"
)
@property
def _headers(self) -> dict:
return {"Authorization": f"Bearer {self.api_key}"}
[docs] def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Get the embeddings for a list of texts... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
1cfda358221a-0 | Source code for langchain.embeddings.cache
"""Module contains code for a cache backed embedder.
The cache backed embedder is a wrapper around an embedder that caches
embeddings in a key-value store. The cache is used to avoid recomputing
embeddings for the same text.
The text is hashed and the hash is used as the key i... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html |
1cfda358221a-1 | The interface allows works with any store that implements
the abstract store interface accepting keys of type str and values of list of
floats.
If need be, the interface can be extended to accept other implementations
of the value serializer and deserializer, as well as the key encoder.
Examples:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html |
1cfda358221a-2 | to embed the documents and stores the results in the cache.
Args:
texts: A list of texts to embed.
Returns:
A list of embeddings for the given texts.
"""
vectors: List[Union[List[float], None]] = self.document_embedding_store.mget(
texts
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html |
1cfda358221a-3 | def from_bytes_store(
cls,
underlying_embeddings: Embeddings,
document_embedding_cache: BaseStore[str, bytes],
*,
namespace: str = "",
) -> CacheBackedEmbeddings:
"""On-ramp that adds the necessary serialization and encoding to the store.
Args:
und... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html |
f6b1e247f6c7-0 | Source code for langchain.embeddings.deepinfra
from typing import Any, Dict, List, Mapping, Optional
import requests
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.schema.embeddings import Embeddings
from langchain.utils import get_from_dict_or_env
DEFAULT_MODEL_ID = "sentence-transfo... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html |
f6b1e247f6c7-1 | model_kwargs: Optional[dict] = None
"""Other model keyword args"""
deepinfra_api_token: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate tha... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html |
f6b1e247f6c7-2 | try:
t = res.json()
embeddings = t["embeddings"]
except requests.exceptions.JSONDecodeError as e:
raise ValueError(
f"Error raised by inference API: {e}.\nResponse: {res.text}"
)
return embeddings
[docs] def embed_documents(self, texts: ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html |
1f4ab89bac4e-0 | Source code for langchain.embeddings.spacy_embeddings
import importlib.util
from typing import Any, Dict, List
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.schema.embeddings import Embeddings
[docs]class SpacyEmbeddings(BaseModel, Embeddings):
"""Embeddings by SpaCy models.
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/spacy_embeddings.html |
1f4ab89bac4e-1 | import spacy
values["nlp"] = spacy.load("en_core_web_sm")
except OSError:
# If the model is not found, raise a ValueError
raise ValueError(
"Spacy model 'en_core_web_sm' not found. "
"Please install it with"
" `python -m spacy d... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/spacy_embeddings.html |
1f4ab89bac4e-2 | """
Asynchronously generates an embedding for a single piece of text.
This method is not implemented and raises a NotImplementedError.
Args:
text (str): The text to generate an embedding for.
Raises:
NotImplementedError: This method is not implemented.
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/spacy_embeddings.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.