id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
94b373b81797-21 | configs = [
RunnableConfig(
callbacks=[
LangChainTracer(
project_name=project_name,
client=client,
use_threading=False,
example_id=example.id,
),
EvaluatorCallbackHandler(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
94b373b81797-22 | "input": example.inputs,
"feedback": feedback,
"execution_time": execution_time,
}
if example.outputs:
results[str(example.id)]["reference"] = example.outputs
return TestResult(
project_name=project_name,
results=results,
)
_INPUT_MAPPER_DEP_WA... | lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
94b373b81797-23 | input_mapper = kwargs.pop("input_mapper", None)
if input_mapper:
warn_deprecated("0.0.305", message=_INPUT_MAPPER_DEP_WARNING, pending=True)
if kwargs:
warn_deprecated(
"0.0.305",
message="The following arguments are deprecated and "
"will be removed in a futu... | lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
94b373b81797-24 | llm_or_chain_factory: MODEL_OR_CHAIN_FACTORY,
*,
evaluation: Optional[smith_eval.RunEvalConfig] = None,
concurrency_level: int = 5,
project_name: Optional[str] = None,
project_metadata: Optional[Dict[str, Any]] = None,
verbose: bool = False,
tags: Optional[List[str]] = None,
**kwargs: An... | lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
94b373b81797-25 | batch_results = list(
executor.map(
functools.partial(
_run_llm_or_chain,
llm_or_chain_factory=wrapped_model,
input_mapper=input_mapper,
),
examples,
co... | lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
94b373b81797-26 | Returns:
A dictionary containing the run's project name and the resulting model outputs.
For the (usually faster) async version of this function, see :func:`arun_on_dataset`.
Examples
--------
.. code-block:: python
from langsmith import Client
from langchain.chat_models import ChatOpenAI
from langchain... | lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
94b373b81797-27 | from langchain.evaluation import StringEvaluator
class MyStringEvaluator(StringEvaluator):
@property
def requires_input(self) -> bool:
return False
@property
def requires_reference(self) -> bool:
return True
@property
def evaluation_name(self) ... | lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html |
7f1882058aec-0 | Source code for langchain.prompts.chat
"""Chat prompt template."""
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
List,
Literal,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
overload... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-1 | """
def __add__(self, other: Any) -> ChatPromptTemplate:
"""Combine two prompt templates.
Args:
other: Another prompt template.
Returns:
Combined prompt template.
"""
prompt = ChatPromptTemplate(messages=[self])
return prompt + other
[docs]clas... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-2 | )
"""Type variable for message prompt templates."""
[docs]class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
"""Base class for message prompt templates that use a string prompt template."""
prompt: StringPromptTemplate
"""String prompt template."""
additional_kwargs: dict = Field(def... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-3 | return cls(prompt=prompt, **kwargs)
[docs] @abstractmethod
def format(self, **kwargs: Any) -> BaseMessage:
"""Format the prompt template.
Args:
**kwargs: Keyword arguments to use for formatting.
Returns:
Formatted message.
"""
[docs] def format_messages(... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-4 | Returns:
Formatted message.
"""
text = self.prompt.format(**kwargs)
return HumanMessage(content=text, additional_kwargs=self.additional_kwargs)
[docs]class AIMessagePromptTemplate(BaseStringMessagePromptTemplate):
"""AI message prompt template. This is a message sent from the AI.... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-5 | return list(self.messages)
[docs]class ChatPromptValueConcrete(ChatPromptValue):
"""Chat prompt value which explicitly lists out the message types it accepts.
For use in external schemas."""
messages: Sequence[AnyMessage]
type: Literal["ChatPromptValueConcrete"] = "ChatPromptValueConcrete"
[docs]class B... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-6 | MessageLike,
Tuple[str, str],
Tuple[Type, str],
str,
]
[docs]class ChatPromptTemplate(BaseChatPromptTemplate):
"""A prompt template for chat models.
Use to create flexible templated prompts for chat models.
Examples:
.. code-block:: python
from langchain.prompts import ChatPr... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-7 | _other = ChatPromptTemplate.from_messages(other)
return ChatPromptTemplate(messages=self.messages + _other.messages)
elif isinstance(other, str):
prompt = HumanMessagePromptTemplate.from_template(other)
return ChatPromptTemplate(messages=self.messages + [prompt])
else... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-8 | return values
[docs] @classmethod
def from_template(cls, template: str, **kwargs: Any) -> ChatPromptTemplate:
"""Create a chat prompt template from a template string.
Creates a chat template consisting of a single message assumed to be from
the human.
Args:
template: t... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-9 | Returns:
a chat prompt template
"""
return cls.from_messages(string_messages)
[docs] @classmethod
def from_messages(
cls,
messages: Sequence[MessageLikeRepresentation],
) -> ChatPromptTemplate:
"""Create a chat prompt template from a variety of message form... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-10 | ):
input_vars.update(_message.input_variables)
return cls(input_variables=sorted(input_vars), messages=_messages)
[docs] def format(self, **kwargs: Any) -> str:
"""Format the chat template into a string.
Args:
**kwargs: keyword arguments to use for filling in templ... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-11 | **kwargs: keyword arguments to use for filling in template variables. Ought
to be a subset of the input variables.
Returns:
A new ChatPromptTemplate.
Example:
.. code-block:: python
from langchain.prompts import ChatPromptTemplate
... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-12 | ...
def __getitem__(
self, index: Union[int, slice]
) -> Union[MessageLike, ChatPromptTemplate]:
"""Use to index into the chat template."""
if isinstance(index, slice):
start, stop, step = index.indices(len(self.messages))
messages = self.messages[start:stop:step]... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-13 | else:
raise ValueError(
f"Unexpected message type: {message_type}. Use one of 'human',"
f" 'user', 'ai', 'assistant', or 'system'."
)
return message
def _convert_to_message(
message: MessageLikeRepresentation,
) -> Union[BaseMessage, BaseMessagePromptTemplate, BaseChatPro... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
7f1882058aec-14 | _message = message_type_str(prompt=PromptTemplate.from_template(template))
else:
raise NotImplementedError(f"Unsupported message type: {type(message)}")
return _message | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
9b82c62c98d7-0 | Source code for langchain.prompts.few_shot
"""Prompt template that contains few shot examples."""
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional, Union
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
StringPromptTemplate,
che... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
9b82c62c98d7-1 | )
if examples is None and example_selector is None:
raise ValueError(
"One of 'examples' and 'example_selector' should be provided"
)
return values
def _get_examples(self, **kwargs: Any) -> List[dict]:
"""Get the examples to use for formatting the prom... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
9b82c62c98d7-2 | """The format of the prompt template. Options are: 'f-string', 'jinja2'."""
@root_validator()
def template_is_valid(cls, values: Dict) -> Dict:
"""Check that prefix, suffix, and input variables are consistent."""
if values["validate_template"]:
check_valid_template(
v... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
9b82c62c98d7-3 | pieces = [self.prefix, *example_strings, self.suffix]
template = self.example_separator.join([piece for piece in pieces if piece])
# Format the template with the input variables.
return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)
@property
def _prompt_type(self) -... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
9b82c62c98d7-4 | {"input": "2+2", "output": "4"},
{"input": "2+3", "output": "5"},
]
example_prompt = ChatPromptTemplate.from_messages(
[('human', '{input}'), ('ai', '{output}')]
)
few_shot_prompt = FewShotChatMessagePromptTemplate(
examples... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
9b82c62c98d7-5 | from langchain.prompts import HumanMessagePromptTemplate
from langchain.prompts.few_shot import FewShotChatMessagePromptTemplate
few_shot_prompt = FewShotChatMessagePromptTemplate(
# Which variable(s) will be passed to the example selector.
input_variables=["input... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
9b82c62c98d7-6 | """Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
[docs] def format_messages(self, **kwargs: Any) -> List[BaseMessage]:
"""Format kwargs into a list of messages.
Args:
**kwargs: keyword arguments to use for filling in templat... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
40de01057950-0 | Source code for langchain.prompts.pipeline
from typing import Any, Dict, List, Tuple
from langchain.prompts.chat import BaseChatPromptTemplate
from langchain.pydantic_v1 import root_validator
from langchain.schema import BasePromptTemplate, PromptValue
def _get_inputs(inputs: dict, input_variables: List[str]) -> dict:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/pipeline.html |
40de01057950-1 | for k, prompt in self.pipeline_prompts:
_inputs = _get_inputs(kwargs, prompt.input_variables)
if isinstance(prompt, BaseChatPromptTemplate):
kwargs[k] = prompt.format_messages(**_inputs)
else:
kwargs[k] = prompt.format(**_inputs)
_inputs = _get... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/pipeline.html |
1355eba9ddc3-0 | Source code for langchain.prompts.prompt
"""Prompt schema definition."""
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional, Union
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
StringPromptTemplate,
check_valid_template,
ge... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
1355eba9ddc3-1 | """
@property
def lc_attributes(self) -> Dict[str, Any]:
return {
"template_format": self.template_format,
}
input_variables: List[str]
"""A list of the names of the variables the prompt template expects."""
template: str
"""The prompt template."""
template_format... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
1355eba9ddc3-2 | input_variables=input_variables,
partial_variables=partial_variables,
template_format="f-string",
validate_template=validate_template,
)
elif isinstance(other, str):
prompt = PromptTemplate.from_template(other)
return self + pro... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
1355eba9ddc3-3 | suffix: str,
input_variables: List[str],
example_separator: str = "\n\n",
prefix: str = "",
**kwargs: Any,
) -> PromptTemplate:
"""Take examples in list format with prefix and suffix to create a prompt.
Intended to be used as a way to dynamically create a prompt from ... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
1355eba9ddc3-4 | def from_template(
cls,
template: str,
*,
template_format: str = "f-string",
partial_variables: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> PromptTemplate:
"""Load a prompt template from a template.
*Security warning*: Prefer using `template_f... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
1355eba9ddc3-5 | if _partial_variables:
input_variables = [
var for var in input_variables if var not in _partial_variables
]
return cls(
input_variables=input_variables,
template=template,
template_format=template_format,
partial_variables=... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
e5e29154b0fe-0 | Source code for langchain.prompts.base
"""BasePrompt schema definition."""
from __future__ import annotations
import warnings
from abc import ABC
from string import Formatter
from typing import Any, Callable, Dict, List, Literal, Set
from langchain.schema.messages import BaseMessage, HumanMessage
from langchain.schema.... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
e5e29154b0fe-1 | # a guarantee of security.
# We recommend to never use jinja2 templates with untrusted inputs.
# https://jinja.palletsprojects.com/en/3.1.x/sandbox/
# approach not a guarantee of security.
return SandboxedEnvironment().from_string(template).render(**kwargs)
[docs]def validate_jinja2(template: str, input... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
e5e29154b0fe-2 | "jinja2": jinja2_formatter,
}
DEFAULT_VALIDATOR_MAPPING: Dict[str, Callable] = {
"f-string": formatter.validate_input_variables,
"jinja2": validate_jinja2,
}
[docs]def check_valid_template(
template: str, template_format: str, input_variables: List[str]
) -> None:
"""Check that template string is valid.... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
e5e29154b0fe-3 | if template_format == "jinja2":
# Get the variables for the template
input_variables = _get_jinja2_variables_from_template(template)
elif template_format == "f-string":
input_variables = {
v for _, v, _, _ in Formatter().parse(template) if v is not None
}
else:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
408171d04ffe-0 | Source code for langchain.prompts.loading
"""Load prompts."""
import json
import logging
from pathlib import Path
from typing import Callable, Dict, Union
import yaml
from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplate
from langchain.schema import BaseLLMOutp... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
408171d04ffe-1 | with open(template_path) as f:
template = f.read()
else:
raise ValueError
# Set the template variable to the extracted variable.
config[var_name] = template
return config
def _load_examples(config: dict) -> dict:
"""Load examples if necessary."""
if isinst... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
408171d04ffe-2 | """Load the "few shot" prompt from the config."""
# Load the suffix and prefix templates.
config = _load_template("suffix", config)
config = _load_template("prefix", config)
# Load the example prompt.
if "example_prompt_path" in config:
if "example_prompt" in config:
raise ValueE... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
408171d04ffe-3 | """Unified method for loading a prompt from LangChainHub or local fs."""
if hub_result := try_load_from_hub(
path, _load_prompt_from_file, "prompts", {"py", "json", "yaml"}
):
return hub_result
else:
return _load_prompt_from_file(path)
def _load_prompt_from_file(file: Union[str, Path... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
8f60699980cf-0 | Source code for langchain.prompts.few_shot_with_templates
"""Prompt template that contains few shot examples."""
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from langchain.prompts.base import DEFAULT_FORMATTER_MAPPING, StringPromptTemplate
from langchain.prompts.example_selector.base im... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
8f60699980cf-1 | """Check that one and only one of examples/example_selector are provided."""
examples = values.get("examples", None)
example_selector = values.get("example_selector", None)
if examples and example_selector:
raise ValueError(
"Only one of 'examples' and 'example_select... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
8f60699980cf-2 | if self.examples is not None:
return self.examples
elif self.example_selector is not None:
return self.example_selector.select_examples(kwargs)
else:
raise ValueError
[docs] def format(self, **kwargs: Any) -> str:
"""Format the prompt with the inputs.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
8f60699980cf-3 | return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)
@property
def _prompt_type(self) -> str:
"""Return the prompt type key."""
return "few_shot_with_templates"
[docs] def save(self, file_path: Union[Path, str]) -> None:
if self.example_selector:
rais... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
41cb1c5d7063-0 | Source code for langchain.prompts.example_selector.ngram_overlap
"""Select and order examples based on ngram overlap score (sentence_bleu score).
https://www.nltk.org/_modules/nltk/translate/bleu_score.html
https://aclanthology.org/P02-1040.pdf
"""
from typing import Dict, List
import numpy as np
from langchain.prompts... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html |
41cb1c5d7063-1 | """
examples: List[dict]
"""A list of the examples that the prompt template expects."""
example_prompt: PromptTemplate
"""Prompt template used to format the examples."""
threshold: float = -1.0
"""Threshold at which algorithm stops. Set to -1.0 by default.
For negative threshold:
select_... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html |
41cb1c5d7063-2 | examples = []
k = len(self.examples)
score = [0.0] * k
first_prompt_template_key = self.example_prompt.input_variables[0]
for i in range(k):
score[i] = ngram_overlap_score(
inputs, [self.examples[i][first_prompt_template_key]]
)
while True:... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html |
665440fd29b0-0 | Source code for langchain.prompts.example_selector.semantic_similarity
"""Example selector that selects examples based on SemanticSimilarity."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Type
from langchain.prompts.example_selector.base import BaseExampleSelector
from langchain.py... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
665440fd29b0-1 | return ids[0]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use based on semantic similarity."""
# Get the docs with the highest similarity.
if self.input_keys:
input_variables = {key: input_variables[key] for key in s... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
665440fd29b0-2 | instead of all variables.
vectorstore_cls_kwargs: optional kwargs containing url for vector store
Returns:
The ExampleSelector instantiated, backed by a vector store.
"""
if input_keys:
string_examples = [
" ".join(sorted_values({k: eg[k] for k... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
665440fd29b0-3 | examples = [dict(e.metadata) for e in example_docs]
# If example keys are provided, filter examples to those keys.
if self.example_keys:
examples = [{k: eg[k] for k in self.example_keys} for eg in examples]
return examples
[docs] @classmethod
def from_examples(
cls,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
665440fd29b0-4 | )
return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys) | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
de2e7739d670-0 | Source code for langchain.prompts.example_selector.base
"""Interface for selecting examples to include in prompts."""
from abc import ABC, abstractmethod
from typing import Any, Dict, List
[docs]class BaseExampleSelector(ABC):
"""Interface for selecting examples to include in prompts."""
[docs] @abstractmethod
... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/base.html |
d6ac79cc46b4-0 | Source code for langchain.prompts.example_selector.length_based
"""Select examples based on length."""
import re
from typing import Callable, Dict, List
from langchain.prompts.example_selector.base import BaseExampleSelector
from langchain.prompts.prompt import PromptTemplate
from langchain.pydantic_v1 import BaseModel... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
d6ac79cc46b4-1 | get_text_length = values["get_text_length"]
string_examples = [example_prompt.format(**eg) for eg in values["examples"]]
return [get_text_length(eg) for eg in string_examples]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use base... | lang/api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
57e8a26c3616-0 | Source code for langchain.storage.exceptions
from langchain.schema import LangChainException
[docs]class InvalidKeyException(LangChainException):
"""Raised when a key is invalid; e.g., uses incorrect characters.""" | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/exceptions.html |
4bd286c73082-0 | Source code for langchain.storage.upstash_redis
from typing import Any, Iterator, List, Optional, Sequence, Tuple, cast
from langchain.schema import BaseStore
[docs]class UpstashRedisStore(BaseStore[str, str]):
"""BaseStore implementation using Upstash Redis as the underlying store."""
[docs] def __init__(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/upstash_redis.html |
4bd286c73082-1 | else:
if not url or not token:
raise ValueError(
"Either an Upstash Redis client or url and token must be provided."
)
_client = Redis(url=url, token=token)
self.client = _client
if not isinstance(ttl, int) and ttl is not None:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/upstash_redis.html |
4bd286c73082-2 | self.client.delete(*_keys)
[docs] def yield_keys(self, *, prefix: Optional[str] = None) -> Iterator[str]:
"""Yield keys in the store."""
if prefix:
pattern = self._get_prefixed_key(prefix)
else:
pattern = self._get_prefixed_key("*")
cursor, keys = self.client.s... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/upstash_redis.html |
af43cc304d33-0 | Source code for langchain.storage.redis
from typing import Any, Iterator, List, Optional, Sequence, Tuple, cast
from langchain.schema import BaseStore
from langchain.utilities.redis import get_client
[docs]class RedisStore(BaseStore[str, bytes]):
"""BaseStore implementation using Redis as the underlying store.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/redis.html |
af43cc304d33-1 | ttl: time to expire keys in seconds if provided,
if None keys will never expire
namespace: if provided, all keys will be prefixed with this namespace
"""
try:
from redis import Redis
except ImportError as e:
raise ImportError(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/redis.html |
af43cc304d33-2 | """Get the values associated with the given keys."""
return cast(
List[Optional[bytes]],
self.client.mget([self._get_prefixed_key(key) for key in keys]),
)
[docs] def mset(self, key_value_pairs: Sequence[Tuple[str, bytes]]) -> None:
"""Set the given key-value pairs."""... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/redis.html |
fddb35974b92-0 | Source code for langchain.storage.encoder_backed
from typing import (
Any,
Callable,
Iterator,
List,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
from langchain.schema import BaseStore
K = TypeVar("K")
V = TypeVar("V")
[docs]class EncoderBackedStore(BaseStore[K, V]):
"""Wraps a s... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/encoder_backed.html |
fddb35974b92-1 | value_serializer: Callable[[V], bytes],
value_deserializer: Callable[[Any], V],
) -> None:
"""Initialize an EncodedStore."""
self.store = store
self.key_encoder = key_encoder
self.value_serializer = value_serializer
self.value_deserializer = value_deserializer
[docs] ... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/encoder_backed.html |
a1985bb1201d-0 | Source code for langchain.storage.file_system
import re
from pathlib import Path
from typing import Iterator, List, Optional, Sequence, Tuple, Union
from langchain.schema import BaseStore
from langchain.storage.exceptions import InvalidKeyException
[docs]class LocalFileStore(BaseStore[str, bytes]):
"""BaseStore int... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html |
a1985bb1201d-1 | Returns:
Path: The full path for the given key.
"""
if not re.match(r"^[a-zA-Z0-9_.\-/]+$", key):
raise InvalidKeyException(f"Invalid characters in key: {key}")
return self.root_path / key
[docs] def mget(self, keys: Sequence[str]) -> List[Optional[bytes]]:
"""... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html |
a1985bb1201d-2 | for key in keys:
full_path = self._get_full_path(key)
if full_path.exists():
full_path.unlink()
[docs] def yield_keys(self, prefix: Optional[str] = None) -> Iterator[str]:
"""Get an iterator over keys that match the given prefix.
Args:
prefix (Optio... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/file_system.html |
40fb6623156b-0 | Source code for langchain.storage.in_memory
"""In memory store that is not thread safe and has no eviction policy.
This is a simple implementation of the BaseStore using a dictionary that is useful
primarily for unit testing purposes.
"""
from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple
from lang... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/in_memory.html |
40fb6623156b-1 | """
return [self.store.get(key) for key in keys]
[docs] def mset(self, key_value_pairs: Sequence[Tuple[str, Any]]) -> None:
"""Set the values for the given keys.
Args:
key_value_pairs (Sequence[Tuple[str, V]]): A sequence of key-value pairs.
Returns:
None
... | lang/api.python.langchain.com/en/latest/_modules/langchain/storage/in_memory.html |
5b1160badd35-0 | Source code for langchain.chat_models.everlyai
"""EverlyAI Endpoints chat wrapper. Relies heavily on ChatOpenAI."""
from __future__ import annotations
import logging
import sys
from typing import TYPE_CHECKING, Dict, Optional, Set
from langchain.adapters.openai import convert_message_to_dict
from langchain.chat_models.... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/everlyai.html |
5b1160badd35-1 | @property
def lc_secrets(self) -> Dict[str, str]:
return {"everlyai_api_key": "EVERLYAI_API_KEY"}
everlyai_api_key: Optional[str] = None
"""EverlyAI Endpoints API keys."""
model_name: str = Field(default=DEFAULT_MODEL, alias="model")
"""Model name to use."""
everlyai_api_base: str = DEFA... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/everlyai.html |
5b1160badd35-2 | except AttributeError as exc:
raise ValueError(
"`openai` has no `ChatCompletion` attribute, this is likely "
"due to an old version of the openai package. Try upgrading it "
"with `pip install --upgrade openai`.",
) from exc
if "model_name... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/everlyai.html |
5b1160badd35-3 | main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb"""
if sys.version_info[1] <= 7:
return super().get_num_tokens_from_messages(messages)
model, encoding = self._get_encoding_model()
tokens_per_message = 3
tokens_per_name = 1
num_tokens = 0
messages_dic... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/everlyai.html |
76106380b621-0 | Source code for langchain.chat_models.azureml_endpoint
import json
from typing import Any, Dict, List, Optional, cast
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.chat_models.base import SimpleChatModel
from langchain.llms.azureml_endpoint import AzureMLEndpointClient, ContentFormatte... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html |
76106380b621-1 | "content": ContentFormatterBase.escape_special_characters(content),
}
else:
supported = ",".join(
[role for role in LlamaContentFormatter.SUPPORTED_ROLES]
)
raise ValueError(
f"""Received unsupported role.
Supported... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html |
76106380b621-2 | env var `AZUREML_ENDPOINT_URL`."""
endpoint_api_key: SecretStr = convert_to_secret_str("")
"""Authentication Key for Endpoint. Should be passed to constructor or specified as
env var `AZUREML_ENDPOINT_API_KEY`."""
http_client: Any = None #: :meta private:
content_formatter: Any = None
"""Th... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html |
76106380b621-3 | def _call(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call out to an AzureML Managed Online endpoint.
Args:
messages: The messages in the ... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/azureml_endpoint.html |
19e0b60114ec-0 | Source code for langchain.chat_models.minimax
"""Wrapper around Minimax chat models."""
import logging
from typing import Any, Dict, List, Optional, cast
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import BaseChatModel
from... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/minimax.html |
19e0b60114ec-1 | def _generate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
"""Generate next turn in the conversation.
Args:
messages: The history of th... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/minimax.html |
55736f3a296b-0 | Source code for langchain.chat_models.baichuan
import hashlib
import json
import logging
import time
from typing import Any, Dict, Iterator, List, Mapping, Optional, Type
import requests
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.chat_models.base import BaseChatModel, _generate_from... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html |
55736f3a296b-1 | role = _dict["role"]
if role == "user":
return HumanMessage(content=_dict["content"])
elif role == "assistant":
return AIMessage(content=_dict.get("content", "") or "")
else:
return ChatMessage(content=_dict["content"], role=role)
def _convert_delta_to_message_chunk(
_dict: Mappi... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html |
55736f3a296b-2 | "baichuan_api_key": "BAICHUAN_API_KEY",
"baichuan_secret_key": "BAICHUAN_SECRET_KEY",
}
@property
def lc_serializable(self) -> bool:
return True
baichuan_api_base: str = Field(default=DEFAULT_API_BASE)
"""Baichuan custom endpoints"""
baichuan_api_key: Optional[str] = None... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html |
55736f3a296b-3 | all_required_field_names = get_pydantic_field_names(cls)
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name in extra:
raise ValueError(f"Found {field_name} supplied twice.")
if field_name not in all_required_field_names:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html |
55736f3a296b-4 | @property
def _default_params(self) -> Dict[str, Any]:
"""Get the default parameters for calling Baichuan API."""
normal_params = {
"model": self.model,
"temperature": self.temperature,
"top_p": self.top_p,
"top_k": self.top_k,
"with_search... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html |
55736f3a296b-5 | response = json.loads(chunk)
if response.get("code") != 0:
raise ValueError(f"Error from Baichuan api response: {response}")
data = response.get("data")
for m in data.get("messages"):
chunk = _convert_delta_to_message_chunk(m, default_chunk_class)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html |
55736f3a296b-6 | **headers,
},
json=payload,
stream=self.streaming,
)
return res
def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
generations = []
for m in response["data"]["messages"]:
message = _convert_dict_to_message(m)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/baichuan.html |
194e5c6709ca-0 | Source code for langchain.chat_models.yandex
"""Wrapper around YandexGPT chat models."""
import logging
from typing import Any, Dict, List, Optional, Tuple, cast
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.chat_models.base import BaseChatMo... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/yandex.html |
194e5c6709ca-1 | with the ``ai.languageModels.user`` role:
- You can specify the token in a constructor parameter `iam_token`
or in an environment variable `YC_IAM_TOKEN`.
- You can specify the key in a constructor parameter `api_key`
or in an environment variable `YC_API_KEY`.
Example:
.. co... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/yandex.html |
194e5c6709ca-2 | )
except ImportError as e:
raise ImportError(
"Please install YandexCloud SDK" " with `pip install yandexcloud`."
) from e
if not messages:
raise ValueError(
"You should provide at least one message to start the chat!"
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/yandex.html |
c0c3b21491f4-0 | Source code for langchain.chat_models.jinachat
"""JinaChat wrapper."""
from __future__ import annotations
import logging
from typing import (
Any,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Mapping,
Optional,
Tuple,
Type,
Union,
)
from tenacity import (
before_sleep_l... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
c0c3b21491f4-1 | return retry(
reraise=True,
stop=stop_after_attempt(llm.max_retries),
wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
retry=(
retry_if_exception_type(openai.error.Timeout)
| retry_if_exception_type(openai.error.APIError)
| retry_... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
c0c3b21491f4-2 | elif role or default_class == ChatMessageChunk:
return ChatMessageChunk(content=content, role=role)
else:
return default_class(content=content)
def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
role = _dict["role"]
if role == "user":
return HumanMessage(content=_... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
c0c3b21491f4-3 | """`Jina AI` Chat models API.
To use, you should have the ``openai`` python package installed, and the
environment variable ``JINACHAT_API_KEY`` set to your API key, which you
can generate at https://chat.jina.ai/api.
Any parameters that are valid to be passed to the openai.create call can be passed
... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
c0c3b21491f4-4 | max_tokens: Optional[int] = None
"""Maximum number of tokens to generate."""
class Config:
"""Configuration for this pydantic object."""
allow_population_by_field_name = True
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra ... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
c0c3b21491f4-5 | raise ValueError(
"Could not import openai python package. "
"Please install it with `pip install openai`."
)
try:
values["client"] = openai.ChatCompletion
except AttributeError:
raise ValueError(
"`openai` has no `ChatC... | lang/api.python.langchain.com/en/latest/_modules/langchain/chat_models/jinachat.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.