id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
8230019c2354-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 |
8230019c2354-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 |
7d364523f7a8-0 | Source code for langchain.embeddings.spacy_embeddings
import importlib.util
from typing import Any, Dict, List
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
[docs]class SpacyEmbeddings(BaseModel, Embeddings):
"""Embeddings by SpaCy models.
It only support... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/spacy_embeddings.html |
7d364523f7a8-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 |
7d364523f7a8-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 |
571ce5748f35-0 | Source code for langchain.embeddings.sagemaker_endpoint
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.llms.sagemaker_endpoint import ContentHandlerBase
[docs]class EmbeddingsContentHandler(ContentHandler... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
571ce5748f35-1 | client: Any #: :meta private:
endpoint_name: str = ""
"""The name of the endpoint from the deployed Sagemaker model.
Must be unique within an AWS Region."""
region_name: str = ""
"""The aws region where the Sagemaker model is deployed, eg. `us-west-2`."""
credentials_profile_name: Optional[str]... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
571ce5748f35-2 | """Key word arguments to pass to the model."""
endpoint_kwargs: Optional[Dict] = None
"""Optional attributes passed to the invoke_endpoint
function. See `boto3`_. docs for more info.
.. _boto3: <https://boto3.amazonaws.com/v1/documentation/api/latest/index.html>
"""
class Config:
"""Conf... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
571ce5748f35-3 | texts = list(map(lambda x: x.replace("\n", " "), texts))
_model_kwargs = self.model_kwargs or {}
_endpoint_kwargs = self.endpoint_kwargs or {}
body = self.content_handler.transform_input(texts, _model_kwargs)
content_type = self.content_handler.content_type
accepts = self.content... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
571ce5748f35-4 | Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
return self._embedding_func([text])[0] | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
71bebf5c4e93-0 | Source code for langchain.embeddings.nlpcloud
from typing import Any, Dict, List
from pydantic import BaseModel, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
[docs]class NLPCloudEmbeddings(BaseModel, Embeddings):
"""NLP Cloud embedding models.
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/nlpcloud.html |
71bebf5c4e93-1 | )
return values
[docs] def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Embed a list of documents using NLP Cloud.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
return self.clien... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/nlpcloud.html |
8b86005e1bb1-0 | Source code for langchain.embeddings.aleph_alpha
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
[docs]class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embeddings):
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
8b86005e1bb1-1 | explicitly been set in the request."""
control_log_additive: bool = True
"""Apply controls on prompt items by adding the log(control_factor)
to attention scores."""
# Client params
aleph_alpha_api_key: Optional[str] = None
"""API key for Aleph Alpha API."""
host: str = "https://api.aleph-al... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
8b86005e1bb1-2 | retry made. So with the
default setting of 8 retries a total wait time of 63.5 s is added between
the retries."""
nice: bool = False
"""Setting this to True, will signal to the API that you intend to be
nice to other users
by de-prioritizing your request below concurrent ones."""
@root_val... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
8b86005e1bb1-3 | SemanticRepresentation,
)
except ImportError:
raise ValueError(
"Could not import aleph_alpha_client python package. "
"Please install it with `pip install aleph_alpha_client`."
)
document_embeddings = []
for text in texts:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
8b86005e1bb1-4 | "control_log_additive": self.control_log_additive,
}
symmetric_request = SemanticEmbeddingRequest(**symmetric_params)
symmetric_response = self.client.semantic_embed(
request=symmetric_request, model=self.model
)
return symmetric_response.embedding
[docs]class AlephAl... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
8b86005e1bb1-5 | query_response = self.client.semantic_embed(
request=query_request, model=self.model
)
return query_response.embedding
[docs] def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Call out to Aleph Alpha's Document endpoint.
Args:
texts: The list... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
a05657c30217-0 | Source code for langchain.embeddings.openai
from __future__ import annotations
import logging
import warnings
from typing import (
Any,
Callable,
Dict,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Union,
)
import numpy as np
from pydantic import BaseModel, Extra, Field, root_va... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-1 | )
def _async_retry_decorator(embeddings: OpenAIEmbeddings) -> Any:
import openai
min_seconds = 4
max_seconds = 10
# Wait 2^x * 1 second between each retry starting with
# 4 seconds, then up to 10 seconds, then 10 seconds afterwards
async_retrying = AsyncRetrying(
reraise=True,
st... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-2 | """Use tenacity to retry the embedding call."""
retry_decorator = _create_retry_decorator(embeddings)
@retry_decorator
def _embed_with_retry(**kwargs: Any) -> Any:
response = embeddings.client.create(**kwargs)
return _check_response(response)
return _embed_with_retry(**kwargs)
[docs]asyn... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-3 | import os
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_BASE"] = "https://<your-endpoint.openai.azure.com/"
os.environ["OPENAI_API_KEY"] = "your AzureOpenAI key"
os.environ["OPENAI_API_VERSION"] = "2023-05-15"
os.environ["OPENAI_PROXY"] = "htt... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-4 | allowed_special: Union[Literal["all"], Set[str]] = set()
disallowed_special: Union[Literal["all"], Set[str], Sequence[str]] = "all"
chunk_size: int = 1000
"""Maximum number of texts to embed in each batch"""
max_retries: int = 6
"""Maximum number of retries to make when generating."""
request_ti... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-5 | def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra kwargs from additional params that were passed in."""
all_required_field_names = get_pydantic_field_names(cls)
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name i... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-6 | "OPENAI_API_TYPE",
default="",
)
values["openai_proxy"] = get_from_dict_or_env(
values,
"openai_proxy",
"OPENAI_PROXY",
default="",
)
if values["openai_api_type"] in ("azure", "azure_ad", "azuread"):
default_api_vers... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-7 | if self.openai_api_type in ("azure", "azure_ad", "azuread"):
openai_args["engine"] = self.deployment
if self.openai_proxy:
try:
import openai
except ImportError:
raise ImportError(
"Could not import openai python package. "
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-8 | for i, text in enumerate(texts):
if self.model.endswith("001"):
# See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500
# replace newlines, which can negatively affect performance.
text = text.replace("\n", " ")
token = en... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-9 | for i in range(len(texts)):
_result = results[i]
if len(_result) == 0:
average = embed_with_retry(
self,
input="",
**self._invocation_params,
)[
"data"
][0]["embedding"... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-10 | # replace newlines, which can negatively affect performance.
text = text.replace("\n", " ")
token = encoding.encode(
text,
allowed_special=self.allowed_special,
disallowed_special=self.disallowed_special,
)
for j in rang... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-11 | return embeddings
[docs] def embed_documents(
self, texts: List[str], chunk_size: Optional[int] = 0
) -> List[List[float]]:
"""Call out to OpenAI's embedding endpoint for embedding search docs.
Args:
texts: The list of texts to embed.
chunk_size: The chunk size of ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
a05657c30217-12 | Returns:
Embedding for the text.
"""
return self.embed_documents([text])[0]
[docs] async def aembed_query(self, text: str) -> List[float]:
"""Call out to OpenAI's embedding endpoint async for embedding query text.
Args:
text: The text to embed.
Returns:... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
fad74986feb0-0 | Source code for langchain.schema.storage
from abc import ABC, abstractmethod
from typing import Generic, Iterator, List, Optional, Sequence, Tuple, TypeVar, Union
K = TypeVar("K")
V = TypeVar("V")
[docs]class BaseStore(Generic[K, V], ABC):
"""Abstract interface for a key-value store."""
[docs] @abstractmethod
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/storage.html |
fad74986feb0-1 | This method is allowed to return an iterator over either K or str
depending on what makes more sense for the given store.
""" | https://api.python.langchain.com/en/latest/_modules/langchain/schema/storage.html |
6cbcc5c8b741-0 | Source code for langchain.schema.messages
from __future__ import annotations
from abc import abstractmethod
from typing import TYPE_CHECKING, Any, Dict, List, Sequence
from pydantic import Field
from langchain.load.serializable import Serializable
if TYPE_CHECKING:
from langchain.prompts.chat import ChatPromptTempl... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
6cbcc5c8b741-1 | message = f"{role}: {m.content}"
if isinstance(m, AIMessage) and "function_call" in m.additional_kwargs:
message += f"{m.additional_kwargs['function_call']}"
string_messages.append(message)
return "\n".join(string_messages)
[docs]class BaseMessage(Serializable):
"""The base abstract ... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
6cbcc5c8b741-2 | )
elif isinstance(merged[k], str):
merged[k] += v
elif isinstance(merged[k], dict):
merged[k] = self._merge_kwargs_dict(merged[k], v)
else:
raise ValueError(
f"Additional kwargs key {k} already exists in this message... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
6cbcc5c8b741-3 | conversation.
"""
@property
def type(self) -> str:
"""Type of the message, used for serialization."""
return "ai"
[docs]class AIMessageChunk(AIMessage, BaseMessageChunk):
pass
[docs]class SystemMessage(BaseMessage):
"""A Message for priming AI behavior, usually passed in as the first... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
6cbcc5c8b741-4 | """Convert a sequence of Messages to a list of dictionaries.
Args:
messages: Sequence of messages (as BaseMessages) to convert.
Returns:
List of messages as dicts.
"""
return [_message_to_dict(m) for m in messages]
def _message_from_dict(message: dict) -> BaseMessage:
_type = message... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
9c674b37a3fa-0 | Source code for langchain.schema.agent
from __future__ import annotations
from dataclasses import dataclass
from typing import NamedTuple, Union
[docs]@dataclass
class AgentAction:
"""A full description of an action for an ActionAgent to execute."""
tool: str
"""The name of the Tool to execute."""
tool_... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/agent.html |
d5123ac3075e-0 | Source code for langchain.schema.retriever
from __future__ import annotations
import warnings
from abc import ABC, abstractmethod
from inspect import signature
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from langchain.load.dump import dumpd
from langchain.load.serializable import Serializable
from lang... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
d5123ac3075e-1 | """ # noqa: E501
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
_new_arg_supported: bool = False
_expects_other_args: bool = False
tags: Optional[List[str]] = None
"""Optional list of tags associated with the retriever. Defaults to None
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
d5123ac3075e-2 | if (
hasattr(cls, "aget_relevant_documents")
and cls.aget_relevant_documents != BaseRetriever.aget_relevant_documents
):
warnings.warn(
"Retrievers must implement abstract `_aget_relevant_documents` method"
" instead of `aget_relevant_documents... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
d5123ac3075e-3 | @abstractmethod
def _get_relevant_documents(
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
) -> List[Document]:
"""Get documents relevant to a query.
Args:
query: String to find relevant documents for
run_manager: The callbacks handler to use
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
d5123ac3075e-4 | List of relevant documents
"""
from langchain.callbacks.manager import CallbackManager
callback_manager = CallbackManager.configure(
callbacks,
None,
verbose=kwargs.get("verbose", False),
inheritable_tags=tags,
local_tags=self.tags,
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
d5123ac3075e-5 | and passed as arguments to the handlers defined in `callbacks`.
metadata: Optional metadata associated with the retriever. Defaults to None
This metadata will be associated with each call to this retriever,
and passed as arguments to the handlers defined in `callbacks`.
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
61ff44e1fb49-0 | Source code for langchain.schema.document
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Sequence
from pydantic import Field
from langchain.load.serializable import Serializable
[docs]class Document(Serializable):
"""Class for storing a piece of text and associated me... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/document.html |
61ff44e1fb49-1 | [docs] @abstractmethod
def transform_documents(
self, documents: Sequence[Document], **kwargs: Any
) -> Sequence[Document]:
"""Transform a list of documents.
Args:
documents: A sequence of Documents to be transformed.
Returns:
A list of transformed Docu... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/document.html |
e75dd585aa4a-0 | Source code for langchain.schema.exceptions
[docs]class LangChainException(Exception):
"""General LangChain exception.""" | https://api.python.langchain.com/en/latest/_modules/langchain/schema/exceptions.html |
ba21689d3f12-0 | Source code for langchain.schema.prompt
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
from langchain.load.serializable import Serializable
from langchain.schema.messages import BaseMessage
[docs]class PromptValue(Serializable, ABC):
"""Base abstract class for inputs ... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt.html |
7827df3132bf-0 | Source code for langchain.schema.output_parser
from __future__ import annotations
import asyncio
from abc import ABC, abstractmethod
from typing import Any, Dict, Generic, List, Optional, TypeVar, Union
from langchain.load.serializable import Serializable
from langchain.schema.messages import BaseMessage
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
7827df3132bf-1 | ) -> T:
if isinstance(input, BaseMessage):
return self._call_with_config(
lambda inner_input: self.parse_result(
[ChatGeneration(message=inner_input)]
),
input,
config,
run_type="parser",
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
7827df3132bf-2 | if cleaned_text not in (self.true_val.upper(), self.false_val.upper()):
raise OutputParserException(
f"BooleanOutputParser expected output value to either be "
f"{self.true_val} or {self.false_val} (case-insensitive). "
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
7827df3132bf-3 | input,
config,
run_type="parser",
)
[docs] def parse_result(self, result: List[Generation]) -> T:
"""Parse a list of candidate model Generations into a specific format.
The return value is parsed from only the first Generation in the result, which
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
7827df3132bf-4 | Returns:
Structured output.
"""
return await asyncio.get_running_loop().run_in_executor(None, self.parse, text)
# TODO: rename 'completion' -> 'text'.
[docs] def parse_with_prompt(self, completion: str, prompt: PromptValue) -> Any:
"""Parse the output of an LLM call with the i... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
7827df3132bf-5 | return True
@property
def _type(self) -> str:
"""Return the output parser type for serialization."""
return "default"
[docs] def parse(self, text: str) -> str:
"""Returns the input text with no changes."""
return text
# TODO: Deprecate
NoOpOutputParser = StrOutputParser
[docs]... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
7827df3132bf-6 | raise ValueError(
"Arguments 'observation' & 'llm_output'"
" are required if 'send_to_llm' is True"
)
self.observation = observation
self.llm_output = llm_output
self.send_to_llm = send_to_llm | https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
1f9237578396-0 | Source code for langchain.schema.runnable
from __future__ import annotations
import asyncio
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Coroutine,
Dict,
Generic,
Iterator,
List,
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-1 | """
callbacks: Callbacks
"""
Callbacks for this call and any sub-calls (eg. a Chain calling an LLM).
Tags are passed to all callbacks, metadata is passed to handle*Start callbacks.
"""
Input = TypeVar("Input")
# Output type should implement __concat__, as eg str, list, dict do
Output = TypeVar("Outp... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-2 | [docs] def batch(
self,
inputs: List[Input],
config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,
*,
max_concurrency: Optional[int] = None,
) -> List[Output]:
configs = self._get_config_list(config, len(inputs))
# If there's only one input,... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-3 | """
return RunnableBinding(bound=self, kwargs=kwargs)
def _get_config_list(
self, config: Optional[Union[RunnableConfig, List[RunnableConfig]]], length: int
) -> List[RunnableConfig]:
if isinstance(config, list) and len(config) != length:
raise ValueError(
f"c... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-4 | self,
func: Callable[[Input], Awaitable[Output]],
input: Input,
config: Optional[RunnableConfig],
run_type: Optional[str] = None,
) -> Output:
from langchain.callbacks.manager import AsyncCallbackManager
config = config or {}
callback_manager = AsyncCallbackMa... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-5 | class Config:
arbitrary_types_allowed = True
@property
def runnables(self) -> Iterator[Runnable[Input, Output]]:
yield self.runnable
yield from self.fallbacks
[docs] def invoke(self, input: Input, config: Optional[RunnableConfig] = None) -> Output:
from langchain.callbacks.man... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-6 | ) -> Output:
from langchain.callbacks.manager import AsyncCallbackManager
# setup callbacks
config = config or {}
callback_manager = AsyncCallbackManager.configure(
inheritable_callbacks=config.get("callbacks"),
local_callbacks=None,
verbose=False,
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-7 | # setup callbacks
configs = self._get_config_list(config, len(inputs))
callback_managers = [
CallbackManager.configure(
inheritable_callbacks=config.get("callbacks"),
local_callbacks=None,
verbose=False,
inheritable_tags=config.... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-8 | rm.on_chain_error(first_error)
raise first_error
[docs] async def abatch(
self,
inputs: List[Input],
config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,
*,
max_concurrency: Optional[int] = None,
) -> List[Output]:
from langchain.callbacks.... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-9 | if first_error is None:
first_error = e
except BaseException as e:
await asyncio.gather(*(rm.on_chain_error(e) for rm in run_managers))
else:
await asyncio.gather(
*(
rm.on_chain_end(
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-10 | last=other.last,
)
else:
return RunnableSequence(
first=self.first,
middle=self.middle + [self.last],
last=_coerce_to_runnable(other),
)
def __ror__(
self,
other: Union[
Runnable[Other, Any],
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-11 | for step in self.steps:
input = step.invoke(
input,
# mark each step as a child run
_patch_config(config, run_manager.get_child()),
)
# finish the root run
except (KeyboardInterrupt, Exception) as e:
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-12 | input if isinstance(input, dict) else {"output": input}
)
return cast(Output, input)
[docs] def batch(
self,
inputs: List[Input],
config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,
*,
max_concurrency: Optional[int] = None,
) -> Li... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-13 | else:
for rm, input in zip(run_managers, inputs):
rm.on_chain_end(input if isinstance(input, dict) else {"output": input})
return cast(List[Output], inputs)
[docs] async def abatch(
self,
inputs: List[Input],
config: Optional[Union[RunnableConfig, List[... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-14 | _patch_config(config, rm.get_child())
for rm, config in zip(run_managers, configs)
],
max_concurrency=max_concurrency,
)
# finish the root runs
except (KeyboardInterrupt, Exception) as e:
await asyncio.gather(*(r... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-15 | run_manager.on_chain_error(e)
raise
# stream the last step
final: Union[Output, None] = None
final_supported = True
try:
for output in self.last.stream(
input,
# mark the last step as a child run
_patch_config(config... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-16 | )
# invoke the first steps
try:
for step in [self.first] + self.middle:
input = await step.ainvoke(
input,
# mark each step as a child run
_patch_config(config, run_manager.get_child()),
)
exc... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-17 | ],
],
) -> None:
super().__init__(
steps={key: _coerce_to_runnable(r) for key, r in steps.items()}
)
@property
def lc_serializable(self) -> bool:
return True
class Config:
arbitrary_types_allowed = True
[docs] def invoke(
self, input: Input,... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-18 | return output
[docs] async def ainvoke(
self, input: Input, config: Optional[RunnableConfig] = None
) -> Dict[str, Any]:
from langchain.callbacks.manager import AsyncCallbackManager
# setup callbacks
config = config or {}
callback_manager = AsyncCallbackManager.configure(
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-19 | raise TypeError(
"Expected a callable type for `func`."
f"Instead got an unsupported type: {type(func)}"
)
def __eq__(self, other: Any) -> bool:
if isinstance(other, RunnableLambda):
return self.func == other.func
else:
return False... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-20 | return await self.bound.ainvoke(input, config, **self.kwargs)
[docs] def batch(
self,
inputs: List[Input],
config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,
*,
max_concurrency: Optional[int] = None,
) -> List[Output]:
return self.bound.batch(
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-21 | super().__init__(runnables=runnables)
class Config:
arbitrary_types_allowed = True
@property
def lc_serializable(self) -> bool:
return True
def __or__(
self,
other: Union[
Runnable[Any, Other],
Callable[[Any], Other],
Mapping[str, Union... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-22 | raise ValueError(f"No runnable associated with key '{key}'")
runnable = self.runnables[key]
return await runnable.ainvoke(actual_input, config)
[docs] def batch(
self,
inputs: List[RouterInput],
config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,
*,
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-23 | runnables = [self.runnables[key] for key in keys]
configs = self._get_config_list(config, len(inputs))
return await _gather_with_concurrency(
max_concurrency,
*(
runnable.ainvoke(input, config)
for runnable, input, config in zip(runnables, actual_i... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
1f9237578396-24 | ]
) -> Runnable[Input, Output]:
if isinstance(thing, Runnable):
return thing
elif callable(thing):
return RunnableLambda(thing)
elif isinstance(thing, dict):
runnables = {key: _coerce_to_runnable(r) for key, r in thing.items()}
return cast(Runnable[Input, Output], RunnableMap... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable.html |
5e557644de8a-0 | Source code for langchain.schema.prompt_template
from __future__ import annotations
import json
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Mapping, Optional, Union
import yaml
from pydantic import Field, root_validator
from langchain.load.serializable impo... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html |
5e557644de8a-1 | """Validate variable names do not include restricted names."""
if "stop" in values["input_variables"]:
raise ValueError(
"Cannot have an input variable named 'stop', as it is used internally,"
" please rename."
)
if "stop" in values["partial_variab... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html |
5e557644de8a-2 | A formatted string.
Example:
.. code-block:: python
prompt.format(variable1="foo")
"""
@property
def _prompt_type(self) -> str:
"""Return the prompt type key."""
raise NotImplementedError
[docs] def dict(self, **kwargs: Any) -> Dict:
"""Return dicti... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html |
5e557644de8a-3 | [docs]def format_document(doc: Document, prompt: BasePromptTemplate) -> str:
"""Format a document into a string based on a prompt template.
First, this pulls information from the document from two sources:
1. `page_content`:
This takes the information from the `document.page_content`
and ass... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html |
5e557644de8a-4 | f"{list(missing_metadata)}."
)
document_info = {k: base_info[k] for k in prompt.input_variables}
return prompt.format(**document_info) | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html |
1a62fd275027-0 | Source code for langchain.schema.output
from __future__ import annotations
from copy import deepcopy
from typing import Any, Dict, List, Optional
from uuid import UUID
from pydantic import BaseModel, root_validator
from langchain.load.serializable import Serializable
from langchain.schema.messages import BaseMessage, B... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/output.html |
1a62fd275027-1 | """The message output by the chat model."""
@root_validator
def set_text(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Set the text attribute to be the contents of the message."""
values["text"] = values["message"].content
return values
[docs]class ChatGenerationChunk(ChatGeneration... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/output.html |
1a62fd275027-2 | generations: List[List[Generation]]
"""List of generated outputs. This is a List[List[]] because
each input could have multiple candidate generations."""
llm_output: Optional[dict] = None
"""Arbitrary LLM provider-specific output."""
run: Optional[List[RunInfo]] = None
"""List of metadata info f... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/output.html |
1a62fd275027-3 | def __eq__(self, other: object) -> bool:
"""Check for LLMResult equality by ignoring any metadata related to runs."""
if not isinstance(other, LLMResult):
return NotImplemented
return (
self.generations == other.generations
and self.llm_output == other.llm_out... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/output.html |
2fa3a88f651b-0 | Source code for langchain.schema.language_model
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import (
TYPE_CHECKING,
Any,
List,
Optional,
Sequence,
Set,
TypeVar,
Union,
)
from langchain.load.serializable import Serializable
from langchain.schema.mess... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
2fa3a88f651b-1 | All language model wrappers inherit from BaseLanguageModel.
Exposes three main methods:
- generate_prompt: generate language model outputs for a sequence of prompt
values. A prompt value is a model input that can be converted to any language
model input format (string or messages).
- predict... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
2fa3a88f651b-2 | callbacks: Callbacks to pass through. Used for executing additional
functionality, such as logging or streaming, throughout generation.
**kwargs: Arbitrary additional keyword arguments. These are usually passed
to the model provider API call.
Returns:
An L... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
2fa3a88f651b-3 | to the model provider API call.
Returns:
An LLMResult, which contains a list of candidate Generations for each input
prompt and additional model provider-specific output.
"""
[docs] @abstractmethod
def predict(
self, text: str, *, stop: Optional[Sequence[str]] ... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
2fa3a88f651b-4 | Returns:
Top model prediction as a message.
"""
[docs] @abstractmethod
async def apredict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
) -> str:
"""Asynchronously pass a string to the model and return a string prediction.
Use this method... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
2fa3a88f651b-5 | """Return the ordered ids of the tokens in a text.
Args:
text: The string input to tokenize.
Returns:
A list of ids corresponding to the tokens in the text, in order they occur
in the text.
"""
return _get_token_ids_default_method(text)
[docs] d... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
5ea79ef84250-0 | Source code for langchain.schema.memory
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Dict, List
from langchain.load.serializable import Serializable
from langchain.schema.messages import AIMessage, BaseMessage, HumanMessage
[docs]class BaseMemory(Serializable, ABC):
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/memory.html |
5ea79ef84250-1 | """Return key-value pairs given the text input to the chain."""
[docs] @abstractmethod
def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:
"""Save the context of this chain run to memory."""
[docs] @abstractmethod
def clear(self) -> None:
"""Clear memory conten... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/memory.html |
5ea79ef84250-2 | [docs] def add_ai_message(self, message: str) -> None:
"""Convenience method for adding an AI message string to the store.
Args:
message: The string contents of an AI message.
"""
self.add_message(AIMessage(content=message))
[docs] @abstractmethod
def add_message(se... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/memory.html |
074b081ea0c0-0 | Source code for langchain.document_transformers.nuclia_text_transform
import asyncio
import json
import uuid
from typing import Any, Sequence
from langchain.schema.document import BaseDocumentTransformer, Document
from langchain.tools.nuclia.tool import NucliaUnderstandingAPI
[docs]class NucliaTextTransformer(BaseDocum... | https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/nuclia_text_transform.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.