id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
d0c3c407787e-0 | Source code for langchain.schema.retriever
from __future__ import annotations
import asyncio
import warnings
from abc import ABC, abstractmethod
from functools import partial
from inspect import signature
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from langchain.load.dump import dumpd
from langchain.sc... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
d0c3c407787e-1 | 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
These tags will be a... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
d0c3c407787e-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
d0c3c407787e-3 | input,
callbacks=config.get("callbacks"),
tags=config.get("tags"),
metadata=config.get("metadata"),
run_name=config.get("run_name"),
)
@abstractmethod
def _get_relevant_documents(
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
d0c3c407787e-4 | These tags will be associated with each call to this retriever,
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,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
d0c3c407787e-5 | run_name: Optional[str] = None,
**kwargs: Any,
) -> List[Document]:
"""Asynchronously get documents relevant to a query.
Args:
query: string to find relevant documents for
callbacks: Callback manager or list of callbacks
tags: Optional list of tags associa... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
d0c3c407787e-6 | await run_manager.on_retriever_end(
result,
**kwargs,
)
return result | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
2d5047ee1d6d-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 ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/prompt.html |
b618006e1d91-0 | Source code for langchain.schema.chat_history
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
from langchain.schema.messages import AIMessage, BaseMessage, HumanMessage
[docs]class BaseChatMessageHistory(ABC):
"""Abstract base class for storing chat message history.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/chat_history.html |
b618006e1d91-1 | Args:
message: The string contents of an AI message.
"""
self.add_message(AIMessage(content=message))
[docs] @abstractmethod
def add_message(self, message: BaseMessage) -> None:
"""Add a Message object to the store.
Args:
message: A BaseMessage object to st... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/chat_history.html |
9cc02dfe64d1-0 | Source code for langchain.schema.vectorstore
from __future__ import annotations
import asyncio
import logging
import math
import warnings
from abc import ABC, abstractmethod
from functools import partial
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Collection,
Dict,
Iterable,... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-1 | """Access the query embedding object if available."""
logger.debug(
f"{Embeddings.__name__} is not implemented for {self.__class__.__name__}"
)
return None
[docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:
"""Delete by vector ID or ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-2 | """Run more documents through the embeddings and add to the vectorstore.
Args:
documents (List[Document]: Documents to add to the vectorstore.
Returns:
List[str]: List of IDs of the added texts.
"""
# TODO: Handle the case where the user doesn't provide ids on the... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-3 | )
[docs] async def asearch(
self, query: str, search_type: str, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query using specified search type."""
if search_type == "similarity":
return await self.asimilarity_search(query, **kwargs)
elif search_typ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-4 | def _cosine_relevance_score_fn(distance: float) -> float:
"""Normalize the distance to a score on a scale [0, 1]."""
return 1.0 - distance
@staticmethod
def _max_inner_product_relevance_score_fn(distance: float) -> float:
"""Normalize the distance to a score on a scale [0, 1]."""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-5 | return await asyncio.get_event_loop().run_in_executor(None, func)
def _similarity_search_with_relevance_scores(
self,
query: str,
k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""
Default similarity search with relevance scores. Modify if necessary... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-6 | k: Number of Documents to return. Defaults to 4.
**kwargs: kwargs to be passed to similarity search. Should include:
score_threshold: Optional, a floating point value between 0 to 1 to
filter the resulting set of retrieved docs
Returns:
List of Tuples ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-7 | ):
warnings.warn(
"Relevance scores must be between"
f" 0 and 1, got {docs_and_similarities}"
)
if score_threshold is not None:
docs_and_similarities = [
(doc, similarity)
for doc, similarity in docs_and_similari... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-8 | for _, similarity in docs_and_similarities
):
warnings.warn(
"Relevance scores must be between"
f" 0 and 1, got {docs_and_similarities}"
)
if score_threshold is not None:
docs_and_similarities = [
(doc, similarity)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-9 | raise NotImplementedError
[docs] async def asimilarity_search_by_vector(
self, embedding: List[float], k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to embedding vector."""
# This is a temporary workaround to make the similarity search
# asynchronous. ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-10 | k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance."""
# This is a temporary workaround to make the similarity search
# asynchronous. The proper solution is to make ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-11 | List of Documents selected by maximal marginal relevance.
"""
raise NotImplementedError
[docs] async def amax_marginal_relevance_search_by_vector(
self,
embedding: List[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-12 | **kwargs: Any,
) -> VST:
"""Return VectorStore initialized from texts and embeddings."""
[docs] @classmethod
async def afrom_texts(
cls: Type[VST],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> VST:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-13 | filter: Filter by document metadata
Returns:
VectorStoreRetriever: Retriever class for VectorStore.
Examples:
.. code-block:: python
# Retrieve more documents with higher diversity
# Useful if your dataset has many similar documents
docsearch.as_re... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-14 | search_type: str = "similarity"
"""Type of search to perform. Defaults to "similarity"."""
search_kwargs: dict = Field(default_factory=dict)
"""Keyword arguments to pass to the search function."""
allowed_search_types: ClassVar[Collection[str]] = (
"similarity",
"similarity_score_thresho... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-15 | query, **self.search_kwargs
)
)
docs = [doc for doc, _ in docs_and_similarities]
elif self.search_type == "mmr":
docs = self.vectorstore.max_marginal_relevance_search(
query, **self.search_kwargs
)
else:
raise Va... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
9cc02dfe64d1-16 | ) -> List[str]:
"""Add documents to vectorstore."""
return await self.vectorstore.aadd_documents(documents, **kwargs) | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
52bb77ea5ac5-0 | Source code for langchain.schema.output_parser
from __future__ import annotations
import asyncio
import functools
from abc import ABC, abstractmethod
from typing import (
Any,
AsyncIterator,
Dict,
Generic,
Iterator,
List,
Optional,
Type,
TypeVar,
Union,
)
from typing_extensions i... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
52bb77ea5ac5-1 | """
return await asyncio.get_running_loop().run_in_executor(
None, self.parse_result, result
)
[docs]class BaseGenerationOutputParser(
BaseLLMOutputParser, RunnableSerializable[Union[str, BaseMessage], T]
):
"""Base class to parse the output of an LLM call."""
@property
def I... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
52bb77ea5ac5-2 | ),
input,
config,
run_type="parser",
)
else:
return await self._acall_with_config(
lambda inner_input: self.aparse_result([Generation(text=inner_input)]),
input,
config,
run_ty... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
52bb77ea5ac5-3 | return type_args[0]
raise TypeError(
f"Runnable {self.__class__.__name__} doesn't have an inferable OutputType. "
"Override the OutputType property to specify the output type."
)
[docs] def invoke(
self, input: Union[str, BaseMessage], config: Optional[RunnableConfig] ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
52bb77ea5ac5-4 | """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
is assumed to be the highest-likelihood Generation.
Args:
result: A list of Generations to be parsed. The Generations are assumed
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
52bb77ea5ac5-5 | 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 input prompt for context.
The prompt is largely provi... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
52bb77ea5ac5-6 | yield self.parse_result([ChatGeneration(message=chunk)])
else:
yield self.parse_result([Generation(text=chunk)])
async def _atransform(
self, input: AsyncIterator[Union[str, BaseMessage]]
) -> AsyncIterator[T]:
async for chunk in input:
if isinstance(chunk... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
52bb77ea5ac5-7 | up to the output parser."""
raise NotImplementedError()
def _transform(self, input: Iterator[Union[str, BaseMessage]]) -> Iterator[Any]:
prev_parsed = None
acc_gen = None
for chunk in input:
if isinstance(chunk, BaseMessageChunk):
chunk_gen: Generation = C... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
52bb77ea5ac5-8 | if parsed is not None and parsed != prev_parsed:
if self.diff:
yield self._diff(prev_parsed, parsed)
else:
yield parsed
prev_parsed = parsed
[docs]class StrOutputParser(BaseTransformOutputParser[str]):
"""OutputParser that parse... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
52bb77ea5ac5-9 | format.
"""
def __init__(
self,
error: Any,
observation: Optional[str] = None,
llm_output: Optional[str] = None,
send_to_llm: bool = False,
):
super(OutputParserException, self).__init__(error)
if send_to_llm:
if observation is None or llm_... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html |
cf75cb40b062-0 | Source code for langchain.schema.language_model
from __future__ import annotations
from abc import ABC, abstractmethod
from functools import lru_cache
from typing import (
TYPE_CHECKING,
Any,
List,
Optional,
Sequence,
Set,
TypeVar,
Union,
)
from typing_extensions import TypeAlias
from la... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
cf75cb40b062-1 | ):
"""Abstract base class for interfacing with language models.
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... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
cf75cb40b062-2 | 1. take advantage of batched calls,
2. need more output from the model than just the top generated value,
3. are building chains that are agnostic to the underlying language model
type (e.g., pure text completion models vs chat models).
Args:
prompts: List of ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
cf75cb40b062-3 | type (e.g., pure text completion models vs chat models).
Args:
prompts: List of PromptValues. A PromptValue is an object that can be
converted to match the format of any language model (string for pure
text generation models and BaseMessages for chat models).
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
cf75cb40b062-4 | stop: Optional[Sequence[str]] = None,
**kwargs: Any,
) -> BaseMessage:
"""Pass a message sequence to the model and return a message prediction.
Use this method when passing in chat messages. If you want to pass in raw text,
use predict.
Args:
messages: A seque... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
cf75cb40b062-5 | """Asynchronously pass messages to the model and return a message prediction.
Use this method when calling chat models and only the top
candidate generation is needed.
Args:
messages: A sequence of chat messages corresponding to a single model input.
stop: Stop words ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
cf75cb40b062-6 | Returns:
The sum of the number of tokens across the messages.
"""
return sum([self.get_num_tokens(get_buffer_string([m])) for m in messages])
@classmethod
def _all_required_field_names(cls) -> Set:
"""DEPRECATED: Kept for backwards compatibility.
Use get_pydantic_fiel... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
c0e052313c97-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
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/storage.html |
c0e052313c97-1 | This method is allowed to return an iterator over either K or str
depending on what makes more sense for the given store.
""" | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/storage.html |
cf826ffac3d0-0 | Source code for langchain.schema.embeddings
import asyncio
from abc import ABC, abstractmethod
from typing import List
[docs]class Embeddings(ABC):
"""Interface for embedding models."""
[docs] @abstractmethod
def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Embed search docs."""
[... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/embeddings.html |
c54a189d87e1-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
[docs]class BaseMemory(Serializable, ABC):
"""Abstract base class for memory in Chains.
Memory refers to state in... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/memory.html |
c54a189d87e1-1 | [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 contents.""" | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/memory.html |
abf03308bc75-0 | Source code for langchain.schema.messages
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Sequence, Union
from typing_extensions import Literal
from langchain.load.serializable import Serializable
from langchain.pydantic_v1 import Extra, Field
if TYPE_CHECKING:
from langchain.p... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
abf03308bc75-1 | else:
raise ValueError(f"Got unsupported message type: {m}")
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(... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
abf03308bc75-2 | else:
return_list: List[Union[str, Dict]] = [first_content]
return return_list + second_content
# If both are lists, merge them naively
elif isinstance(second_content, List):
return first_content + second_content
# If the first content is a list, and the second content is a s... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
abf03308bc75-3 | )
return merged
def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore
if isinstance(other, BaseMessageChunk):
# If both are (subclasses of) BaseMessageChunk,
# concat into a single BaseMessageChunk
if isinstance(self, ChatMessageChunk):
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
abf03308bc75-4 | [docs]class AIMessage(BaseMessage):
"""A Message from an AI."""
example: bool = False
"""Whether this Message is being passed in to the model as part of an example
conversation.
"""
type: Literal["ai"] = "ai"
AIMessage.update_forward_refs()
[docs]class AIMessageChunk(AIMessage, BaseMessageC... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
abf03308bc75-5 | # Ignoring mypy re-assignment here since we're overriding the value
# to make sure that the chunk variant can be discriminated from the
# non-chunk variant.
type: Literal["SystemMessageChunk"] = "SystemMessageChunk" # type: ignore[assignment] # noqa: E501
[docs]class FunctionMessage(BaseMessage):
"""A ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
abf03308bc75-6 | tool_call_id: str
"""Tool call that this message is responding to."""
type: Literal["tool"] = "tool"
ToolMessage.update_forward_refs()
[docs]class ToolMessageChunk(ToolMessage, BaseMessageChunk):
"""A Tool Message chunk."""
# Ignoring mypy re-assignment here since we're overriding the value
# to mak... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
abf03308bc75-7 | # non-chunk variant.
type: Literal["ChatMessageChunk"] = "ChatMessageChunk" # type: ignore
def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore
if isinstance(other, ChatMessageChunk):
if self.role != other.role:
raise ValueError(
"Cannot con... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
abf03308bc75-8 | return ChatMessage(**message["data"])
elif _type == "function":
return FunctionMessage(**message["data"])
elif _type == "tool":
return ToolMessage(**message["data"])
else:
raise ValueError(f"Got unexpected message type: {_type}")
[docs]def messages_from_dict(messages: List[dict]) -> ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html |
f7c3fcd00905-0 | Source code for langchain.schema.output
from __future__ import annotations
from copy import deepcopy
from typing import Any, Dict, List, Literal, Optional
from uuid import UUID
from langchain.load.serializable import Serializable
from langchain.pydantic_v1 import BaseModel, root_validator
from langchain.schema.messages... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output.html |
f7c3fcd00905-1 | [docs]class ChatGeneration(Generation):
"""A single chat generation output."""
text: str = ""
"""*SHOULD NOT BE SET DIRECTLY* The text contents of the output message."""
message: BaseMessage
"""The message output by the chat model."""
# Override type to be ChatGeneration, ignore mypy error as th... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output.html |
f7c3fcd00905-2 | else None
)
return ChatGenerationChunk(
message=self.message + other.message,
generation_info=generation_info,
)
else:
raise TypeError(
f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output.html |
f7c3fcd00905-3 | it is kept only for the LLMResult corresponding to the top-choice
Generation, to avoid over-counting of token usage downstream.
Returns:
List of LLMResults where each returned LLMResult contains a single
Generation.
"""
llm_results = []
for i, gen_... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/output.html |
8cf9574238da-0 | Source code for langchain.schema.callbacks.manager
from __future__ import annotations
import asyncio
import functools
import logging
import os
import uuid
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager, contextmanager
from contextvars import ContextVar
from typing import (
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-1 | from langsmith import Client as LangSmithClient
logger = logging.getLogger(__name__)
tracing_callback_var: ContextVar[Optional[LangChainTracerV1]] = ContextVar( # noqa: E501
"tracing_callback", default=None
)
tracing_v2_callback_var: ContextVar[Optional[LangChainTracer]] = ContextVar( # noqa: E501
"tracing_ca... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-2 | *,
example_id: Optional[Union[str, UUID]] = None,
tags: Optional[List[str]] = None,
client: Optional[LangSmithClient] = None,
) -> Generator[LangChainTracer, None, None]:
"""Instruct LangChain to log all runs in context to LangSmith.
Args:
project_name (str, optional): The name of the projec... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-3 | >>> with collect_runs() as runs_cb:
chain.invoke("foo")
run_id = runs_cb.traced_runs[0].id
"""
cb = run_collector.RunCollectorCallbackHandler()
run_collector_var.set(cb)
yield cb
run_collector_var.set(None)
def _get_trace_callbacks(
project_name: Optional[str] = N... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-4 | run_id: Optional[UUID] = None,
tags: Optional[List[str]] = None,
) -> Generator[CallbackManagerForChainGroup, None, None]:
"""Get a callback manager for a chain group in a context manager.
Useful for grouping different calls together as a single run even if
they aren't composed in a single chain.
Ar... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-5 | inheritable_callbacks=cb,
inheritable_tags=tags,
)
run_manager = cm.on_chain_start({"name": group_name}, inputs or {}, run_id=run_id)
child_cm = run_manager.get_child()
group_cm = CallbackManagerForChainGroup(
child_cm.handlers,
child_cm.inheritable_handlers,
child_cm.par... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-6 | callback_manager (AsyncCallbackManager, optional): The async callback manager to use,
which manages tracing and other callback behavior.
project_name (str, optional): The name of the project.
Defaults to None.
example_id (str or UUID, optional): The ID of the example.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-7 | inheritable_tags=child_cm.inheritable_tags,
metadata=child_cm.metadata,
inheritable_metadata=child_cm.inheritable_metadata,
)
try:
yield group_cm
except Exception as e:
if not group_cm.ended:
await run_manager.on_chain_error(e)
raise e
else:
if... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-8 | if event_name == "on_chat_model_start":
if message_strings is None:
message_strings = [get_buffer_string(m) for m in args[1]]
handle_event(
[handler],
"on_llm_start",
"ignore_llm",
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-9 | if hasattr(asyncio, "Runner"):
# Python 3.11+
# Run the coroutines in a new event loop, taking care to
# - install signal handlers
# - run pending tasks scheduled by `coros`
# - close asyncgens and executors
# - close the loop
with asyncio.Runner() as runner:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-10 | message_strings = [get_buffer_string(m) for m in args[1]]
await _ahandle_event_for_handler(
handler,
"on_llm_start",
"ignore_llm",
args[0],
message_strings,
*args[2:],
**kwargs,
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-11 | )
await asyncio.gather(
*(
_ahandle_event_for_handler(
handler, event_name, ignore_condition_name, *args, **kwargs
)
for handler in handlers
if not handler.run_inline
)
)
BRM = TypeVar("BRM", bound="BaseRunManager")
[docs]class Base... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-12 | self.handlers = handlers
self.inheritable_handlers = inheritable_handlers
self.parent_run_id = parent_run_id
self.tags = tags or []
self.inheritable_tags = inheritable_tags or []
self.metadata = metadata or {}
self.inheritable_metadata = inheritable_metadata or {}
[docs] ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-13 | run_id=self.run_id,
parent_run_id=self.parent_run_id,
tags=self.tags,
**kwargs,
)
[docs]class ParentRunManager(RunManager):
"""Sync Parent Run Manager."""
[docs] def get_child(self, tag: Optional[str] = None) -> CallbackManager:
"""Get a child callback manager.... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-14 | ) -> None:
await ahandle_event(
self.handlers,
"on_retry",
"ignore_retry",
retry_state,
run_id=self.run_id,
parent_run_id=self.parent_run_id,
tags=self.tags,
**kwargs,
)
[docs]class AsyncParentRunManager(Asyn... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-15 | run_id=self.run_id,
parent_run_id=self.parent_run_id,
tags=self.tags,
chunk=chunk,
**kwargs,
)
[docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
"""Run when LLM ends running.
Args:
response (LLMResult): The LLM... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-16 | Args:
token (str): The new token.
"""
await ahandle_event(
self.handlers,
"on_llm_new_token",
"ignore_llm",
token,
chunk=chunk,
run_id=self.run_id,
parent_run_id=self.parent_run_id,
tags=self.tags... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-17 | """Run when chain ends running.
Args:
outputs (Union[Dict[str, Any], Any]): The outputs of the chain.
"""
handle_event(
self.handlers,
"on_chain_end",
"ignore_chain",
outputs,
run_id=self.run_id,
parent_run_id=se... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-18 | Args:
finish (AgentFinish): The agent finish.
Returns:
Any: The result of the callback.
"""
handle_event(
self.handlers,
"on_agent_finish",
"ignore_agent",
finish,
run_id=self.run_id,
parent_run_id=se... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-19 | """Run when agent action is received.
Args:
action (AgentAction): The agent action.
Returns:
Any: The result of the callback.
"""
await ahandle_event(
self.handlers,
"on_agent_action",
"ignore_agent",
action,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-20 | self,
error: BaseException,
**kwargs: Any,
) -> None:
"""Run when tool errors.
Args:
error (Exception or KeyboardInterrupt): The error.
"""
handle_event(
self.handlers,
"on_tool_error",
"ignore_agent",
error,... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-21 | """Callback manager for retriever run."""
[docs] def on_retriever_end(
self,
documents: Sequence[Document],
**kwargs: Any,
) -> None:
"""Run when retriever ends running."""
handle_event(
self.handlers,
"on_retriever_end",
"ignore_retriev... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-22 | )
[docs] async def on_retriever_error(
self,
error: BaseException,
**kwargs: Any,
) -> None:
"""Run when retriever errors."""
await ahandle_event(
self.handlers,
"on_retriever_error",
"ignore_retriever",
error,
ru... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-23 | CallbackManagerForLLMRun(
run_id=run_id_,
handlers=self.handlers,
inheritable_handlers=self.inheritable_handlers,
parent_run_id=self.parent_run_id,
tags=self.tags,
inheritable_tags=self.inheritable_ta... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-24 | parent_run_id=self.parent_run_id,
tags=self.tags,
inheritable_tags=self.inheritable_tags,
metadata=self.metadata,
inheritable_metadata=self.inheritable_metadata,
)
)
return managers
[docs] def on_chain... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-25 | self,
serialized: Dict[str, Any],
input_str: str,
run_id: Optional[UUID] = None,
parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> CallbackManagerForToolRun:
"""Run when tool starts running.
Args:
serialized (Dict[str, Any]): The serialized... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-26 | parent_run_id: Optional[UUID] = None,
**kwargs: Any,
) -> CallbackManagerForRetrieverRun:
"""Run when retriever starts running."""
if run_id is None:
run_id = uuid.uuid4()
handle_event(
self.handlers,
"on_retriever_start",
"ignore_retri... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-27 | verbose (bool, optional): Whether to enable verbose mode. Defaults to False.
inheritable_tags (Optional[List[str]], optional): The inheritable tags.
Defaults to None.
local_tags (Optional[List[str]], optional): The local tags.
Defaults to None.
inherit... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-28 | tags=self.tags,
inheritable_tags=self.inheritable_tags,
metadata=self.metadata,
inheritable_metadata=self.inheritable_metadata,
parent_run_manager=self.parent_run_manager,
)
[docs] def on_chain_end(self, outputs: Union[Dict[str, Any], Any], **kwargs: Any) -> No... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-29 | Returns:
List[AsyncCallbackManagerForLLMRun]: The list of async
callback managers, one for each LLM Run corresponding
to each prompt.
"""
tasks = []
managers = []
for prompt in prompts:
run_id_ = uuid.uuid4()
tasks.appen... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-30 | Returns:
List[AsyncCallbackManagerForLLMRun]: The list of
async callback managers, one for each LLM Run
corresponding to each inner message list.
"""
tasks = []
managers = []
for message_list in messages:
run_id_ = uuid.uuid4()
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-31 | Returns:
AsyncCallbackManagerForChainRun: The async callback manager
for the chain run.
"""
if run_id is None:
run_id = uuid.uuid4()
await ahandle_event(
self.handlers,
"on_chain_start",
"ignore_chain",
seria... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-32 | run_id = uuid.uuid4()
await ahandle_event(
self.handlers,
"on_tool_start",
"ignore_agent",
serialized,
input_str,
run_id=run_id,
parent_run_id=self.parent_run_id,
tags=self.tags,
metadata=self.metadata,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-33 | parent_run_id=self.parent_run_id,
tags=self.tags,
inheritable_tags=self.inheritable_tags,
metadata=self.metadata,
inheritable_metadata=self.inheritable_metadata,
)
[docs] @classmethod
def configure(
cls,
inheritable_callbacks: Callbacks = No... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-34 | local_tags,
inheritable_metadata,
local_metadata,
)
[docs]class AsyncCallbackManagerForChainGroup(AsyncCallbackManager):
"""Async callback manager for the chain group."""
[docs] def __init__(
self,
handlers: List[BaseCallbackHandler],
inheritable_handlers: ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-35 | error: BaseException,
**kwargs: Any,
) -> None:
"""Run when chain errors.
Args:
error (Exception or KeyboardInterrupt): The error.
"""
self.ended = True
await self.parent_run_manager.on_chain_error(error, **kwargs)
T = TypeVar("T", CallbackManager, AsyncCa... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-36 | # Therefore, this just tricks the mypy type checker
str(ls_utils.get_tracer_project()),
),
)
_configure_hooks: List[
Tuple[
ContextVar[Optional[BaseCallbackHandler]],
bool,
Optional[Type[BaseCallbackHandler]],
Optional[str],
]
] = []
H = TypeVar("H", bound... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
8cf9574238da-37 | ) -> T:
"""Configure the callback manager.
Args:
callback_manager_cls (Type[T]): The callback manager class.
inheritable_callbacks (Optional[Callbacks], optional): The inheritable
callbacks. Defaults to None.
local_callbacks (Optional[Callbacks], optional): The local callback... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.