id
stringlengths
14
15
text
stringlengths
44
2.47k
source
stringlengths
61
181
b53d744c322d-2
API. Use this method when you want to: 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 v...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html
b53d744c322d-3
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 PromptValues. A PromptValue is an object that can be converted to match the format of any language model (string f...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html
b53d744c322d-4
self, messages: List[BaseMessage], *, 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, ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html
b53d744c322d-5
**kwargs: Any, ) -> BaseMessage: """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 sing...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html
b53d744c322d-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...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html
8da700e74090-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...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/memory.html
8da700e74090-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."""
https://api.python.langchain.com/en/latest/_modules/langchain/schema/memory.html
aae63e68f0a5-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
5c1e9443c2ca-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...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html
5c1e9443c2ca-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(...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html
5c1e9443c2ca-2
" but with a different type." ) 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...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html
5c1e9443c2ca-3
"""A Human Message chunk.""" # 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. is_chunk: Literal[True] = True # type: ignore[assignment] [docs]class AIMessage(BaseMessage): """A Message from a...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html
5c1e9443c2ca-4
of input messages. """ type: Literal["system"] = "system" is_chunk: Literal[False] = False SystemMessage.update_forward_refs() [docs]class SystemMessageChunk(SystemMessage, BaseMessageChunk): """A System Message chunk.""" # Ignoring mypy re-assignment here since we're overriding the value # to m...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html
5c1e9443c2ca-5
), ) return super().__add__(other) [docs]class ChatMessage(BaseMessage): """A Message that can be assigned an arbitrary speaker (i.e. role).""" role: str """The speaker / role of the Message.""" type: Literal["chat"] = "chat" is_chunk: Literal[False] = False ChatMessage.update_fo...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html
5c1e9443c2ca-6
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["type"] if _type == "human": return HumanMessage(**message["data"]...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/messages.html
f6633f0700ad-0
Source code for langchain.schema.output_parser from __future__ import annotations import asyncio from abc import ABC, abstractmethod from typing import ( Any, AsyncIterator, Dict, Generic, Iterator, List, Optional, TypeVar, Union, ) from typing_extensions import get_args from langcha...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html
f6633f0700ad-1
""" return await asyncio.get_running_loop().run_in_executor( None, self.parse_result, result ) [docs]class BaseGenerationOutputParser( BaseLLMOutputParser, Runnable[Union[str, BaseMessage], T] ): """Base class to parse the output of an LLM call.""" @property def InputType(sel...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html
f6633f0700ad-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...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html
f6633f0700ad-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] ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html
f6633f0700ad-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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html
f6633f0700ad-5
# 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 provided in the event the OutputParser wants to retry or fix the output in some w...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html
f6633f0700ad-6
async def _atransform( self, input: AsyncIterator[Union[str, BaseMessage]] ) -> AsyncIterator[T]: async for chunk in input: if isinstance(chunk, BaseMessage): yield self.parse_result([ChatGeneration(message=chunk)]) else: yield self.parse_resul...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html
f6633f0700ad-7
prev_parsed = None acc_gen = None for chunk in input: if isinstance(chunk, BaseMessageChunk): chunk_gen: Generation = ChatGenerationChunk(message=chunk) elif isinstance(chunk, BaseMessage): chunk_gen = ChatGenerationChunk( messa...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html
f6633f0700ad-8
prev_parsed = parsed [docs]class StrOutputParser(BaseTransformOutputParser[str]): """OutputParser that parses LLMResult into the top likely string.""" [docs] @classmethod def is_lc_serializable(cls) -> bool: """Return whether this class is serializable.""" return True @property def _t...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html
f6633f0700ad-9
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_output is None: raise ValueError( "Arguments 'observation' & 'llm_output'" ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output_parser.html
f96abcb35f96-0
Source code for langchain.schema.agent from __future__ import annotations from typing import Any, Sequence, Union from langchain.load.serializable import Serializable from langchain.schema.messages import BaseMessage [docs]class AgentAction(Serializable): """A full description of an action for an ActionAgent to exe...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/agent.html
f96abcb35f96-1
if (tool, tool_input) cannot be used to fully recreate the LLM prediction, and you need that LLM prediction (for future agent iteration). Compared to `log`, this is useful when the underlying LLM is a ChatModel (and therefore returns messages rather than a string).""" [docs]class AgentFinish(Serializable): ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/agent.html
96f1f2c2cc5d-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 langchain.load.serializable import Serializable from langchain.pydantic_v1 import BaseModel, root_validator from langchain.schema.messages import B...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output.html
96f1f2c2cc5d-1
"""*SHOULD NOT BE SET DIRECTLY* The text contents of the output message.""" message: BaseMessage """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...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output.html
96f1f2c2cc5d-2
candidate generations. """ llm_output: Optional[dict] = None """For arbitrary LLM provider specific output.""" [docs]class LLMResult(BaseModel): """Class that contains all results for a batched LLM call.""" generations: List[List[Generation]] """List of generated outputs. This is a List[List[]] ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output.html
96f1f2c2cc5d-3
else: llm_output = None llm_results.append( LLMResult( generations=[gen_list], llm_output=llm_output, ) ) return llm_results def __eq__(self, other: object) -> bool: ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/output.html
bfdbb8d0d23e-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
bfdbb8d0d23e-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
987889cf40c7-0
Source code for langchain.schema.runnable.utils from __future__ import annotations import ast import asyncio import inspect import textwrap from inspect import signature from typing import ( Any, AsyncIterable, Callable, Coroutine, Dict, Iterable, List, Optional, Protocol, Set, ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html
987889cf40c7-1
[docs] def visit_Subscript(self, node: ast.Subscript) -> Any: if ( isinstance(node.ctx, ast.Load) and isinstance(node.value, ast.Name) and node.value.id == self.name and isinstance(node.slice, ast.Constant) and isinstance(node.slice.value, str) ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html
987889cf40c7-2
input_arg_name = node.args.args[0].arg IsLocalDict(input_arg_name, self.keys).visit(node) [docs]class GetLambdaSource(ast.NodeVisitor): [docs] def __init__(self) -> None: self.source: Optional[str] = None self.count = 0 [docs] def visit_Lambda(self, node: ast.Lambda) -> Any: self.c...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html
987889cf40c7-3
prefix: Used to determine the number of spaces to indent Returns: str: The indented text """ n_spaces = len(prefix) spaces = " " * n_spaces lines = text.splitlines() return "\n".join([lines[0]] + [spaces + line for line in lines[1:]]) [docs]class AddableDict(Dict[str, Any]): """ ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html
987889cf40c7-4
final = None for chunk in addables: if final is None: final = chunk else: final = final + chunk return final [docs]async def aadd(addables: AsyncIterable[Addable]) -> Optional[Addable]: final = None async for chunk in addables: if final is None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html
c7f123e88049-0
Source code for langchain.schema.runnable.router from __future__ import annotations from typing import ( Any, AsyncIterator, Callable, Iterator, List, Mapping, Optional, Union, cast, ) from typing_extensions import TypedDict from langchain.load.serializable import Serializable from l...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html
c7f123e88049-1
[docs] @classmethod def get_lc_namespace(cls) -> List[str]: return cls.__module__.split(".")[:-1] [docs] def invoke( self, input: RouterInput, config: Optional[RunnableConfig] = None ) -> Output: key = input["key"] actual_input = input["input"] if key not in self.ru...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html
c7f123e88049-2
def invoke( runnable: Runnable, input: Input, config: RunnableConfig ) -> Union[Output, Exception]: if return_exceptions: try: return runnable.invoke(input, config, **kwargs) except Exception as e: return e ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html
c7f123e88049-3
else: return await runnable.ainvoke(input, config, **kwargs) runnables = [self.runnables[key] for key in keys] configs = get_config_list(config, len(inputs)) return await gather_with_concurrency( configs[0].get("max_concurrency"), *( ainvok...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html
7d486a4a793f-0
Source code for langchain.schema.runnable.passthrough from __future__ import annotations import asyncio import threading from typing import ( Any, AsyncIterator, Callable, Dict, Iterator, List, Mapping, Optional, Type, Union, cast, ) from langchain.load.serializable import Se...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
7d486a4a793f-1
Callable[[Dict[str, Any]], Any], Mapping[ str, Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]], ], ], ) -> RunnableAssign: """ Merge the Dict input with the output produced by the mapping argument. Args: ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
7d486a4a793f-2
""" A runnable that assigns key-value pairs to Dict[str, Any] inputs. """ mapper: RunnableMap[Dict[str, Any]] def __init__(self, mapper: RunnableMap[Dict[str, Any]], **kwargs: Any) -> None: super().__init__(mapper=mapper, **kwargs) [docs] @classmethod def is_lc_serializable(cls) -> bool: ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
7d486a4a793f-3
) -> Dict[str, Any]: assert isinstance(input, dict) return { **input, **self.mapper.invoke(input, config, **kwargs), } [docs] async def ainvoke( self, input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any, ) -...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
7d486a4a793f-4
) if filtered: yield filtered # yield map output yield cast(Dict[str, Any], first_map_chunk_future.result()) for chunk in map_output: yield chunk [docs] async def atransform( self, input: AsyncIterator[Dict[str, A...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
7d486a4a793f-5
**kwargs: Any, ) -> Iterator[Dict[str, Any]]: return self.transform(iter([input]), config, **kwargs) [docs] async def astream( self, input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> AsyncIterator[Dict[str, Any]]: async def inp...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
1a9f57e4a012-0
Source code for langchain.schema.runnable.retry from typing import ( TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, TypeVar, Union, cast, ) from tenacity import ( AsyncRetrying, RetryCallState, RetryError, Retrying, retry_if_exception_type, stop_af...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
1a9f57e4a012-1
def _sync_retrying(self, **kwargs: Any) -> Retrying: return Retrying(**self._kwargs_retrying, **kwargs) def _async_retrying(self, **kwargs: Any) -> AsyncRetrying: return AsyncRetrying(**self._kwargs_retrying, **kwargs) def _patch_config( self, config: RunnableConfig, run_...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
1a9f57e4a012-2
) -> Output: return self._call_with_config(self._invoke, input, config, **kwargs) async def _ainvoke( self, input: Input, run_manager: "AsyncCallbackManagerForChainRun", config: RunnableConfig, ) -> Output: async for attempt in self._async_retrying(reraise=True): ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
1a9f57e4a012-3
), return_exceptions=True, ) # Register the results of the inputs that have succeeded. first_exception = None for i, r in enumerate(result): if isinstance(r, Exception): ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
1a9f57e4a012-4
results_map: Dict[int, Output] = {} def pending(iterable: List[U]) -> List[U]: return [item for idx, item in enumerate(iterable) if idx not in results_map] try: async for attempt in self._async_retrying(): with attempt: # Get the results of the...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
1a9f57e4a012-5
*, return_exceptions: bool = False, **kwargs: Any ) -> List[Output]: return await self._abatch_with_config( self._abatch, inputs, config, return_exceptions=return_exceptions, **kwargs ) # stream() and transform() are not retried because retrying a stream # is not ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
6b75ba941317-0
Source code for langchain.schema.runnable.base from __future__ import annotations import asyncio import inspect import threading from abc import ABC, abstractmethod from concurrent.futures import FIRST_COMPLETED, wait from functools import partial from itertools import tee from operator import itemgetter from typing im...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-1
from langchain.utils.iter import safetee Other = TypeVar("Other") [docs]class Runnable(Generic[Input, Output], ABC): """A Runnable is a unit of work that can be invoked, batched, streamed, or transformed.""" @property def InputType(self) -> Type[Input]: for cls in self.__class__.__orig_bases__: ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-2
root_type = self.OutputType if inspect.isclass(root_type) and issubclass(root_type, BaseModel): return root_type return create_model( self.__class__.__name__ + "Output", __root__=(root_type, None) ) def __or__( self, other: Union[ Runnable[...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-3
None, partial(self.invoke, **kwargs), input, config ) [docs] def batch( self, inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any], ) -> List[Output]: ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-4
Subclasses should override this method if they can batch more efficiently. """ if not inputs: return [] configs = get_config_list(config, len(inputs)) async def ainvoke( input: Input, config: RunnableConfig ) -> Union[Output, Exception]: if ret...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-5
*, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-6
elif isinstance(callbacks, BaseCallbackManager): callbacks = callbacks.copy() callbacks.inheritable_handlers.append(stream) config["callbacks"] = callbacks else: raise ValueError( f"Unexpected type for callbacks: {callbacks}." "Expe...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-7
final: Input got_first_val = False for chunk in input: if not got_first_val: final = chunk got_first_val = True else: # Make a best effort to gather, for any type that supports `+` # This method should throw an error...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-8
[docs] def with_config( self, config: Optional[RunnableConfig] = None, # Sadly Unpack is not well supported by mypy so this will have to be untyped **kwargs: Any, ) -> Runnable[Input, Output]: """ Bind config to a Runnable, returning a new Runnable. """ ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-9
runnable=self, fallbacks=fallbacks, exceptions_to_handle=exceptions_to_handle, ) """ --- Helper methods for Subclasses --- """ def _call_with_config( self, func: Union[ Callable[[Input], Output], Callable[[Input, CallbackManagerForChainRun]...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-10
], input: Input, config: Optional[RunnableConfig], run_type: Optional[str] = None, **kwargs: Optional[Any], ) -> Output: """Helper method to transform an Input value to an Output value, with callbacks. Use this method to implement ainvoke() in subclasses.""" c...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-11
"""Helper method to transform an Input value to an Output value, with callbacks. Use this method to implement invoke() in subclasses.""" if not input: return [] configs = get_config_list(config, len(input)) callback_managers = [get_callback_manager_for_config(c) for c in conf...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-12
else: raise first_exception async def _abatch_with_config( self, func: Union[ Callable[[List[Input]], Awaitable[List[Union[Exception, Output]]]], Callable[ [List[Input], List[AsyncCallbackManagerForChainRun]], Awaitable[List[Uni...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-13
kwargs["config"] = [ patch_config(c, callbacks=rm.get_child()) for c, rm in zip(configs, run_managers) ] if accepts_run_manager(func): kwargs["run_manager"] = run_managers output = await func(input, **kwargs) # type: ignore...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-14
run_type: Optional[str] = None, **kwargs: Optional[Any], ) -> Iterator[Output]: """Helper method to transform an Iterator of Input values into an Iterator of Output values, with callbacks. Use this to implement `stream()` or `transform()` in Runnable subclasses.""" # tee the ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-15
for ichunk in input_for_tracing: if final_input_supported: if final_input is None: final_input = ichunk else: try: final_input = final_input + ichunk # type: ignore ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-16
final_input_supported = True final_output: Optional[Output] = None final_output_supported = True config = ensure_config(config) callback_manager = get_async_callback_manager_for_config(config) run_manager = await callback_manager.on_chain_start( dumpd(self), ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-17
[docs]class RunnableBranch(Serializable, Runnable[Input, Output]): """A Runnable that selects which branch to run based on a condition. The runnable is initialized with a list of (condition, runnable) pairs and a default branch. When operating on an input, the first condition that evaluates to True is ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-18
default = branches[-1] if not isinstance( default, (Runnable, Callable, Mapping) # type: ignore[arg-type] ): raise TypeError( "RunnableBranch default must be runnable, callable or mapping." ) default_ = cast( Runnable[Input, Output...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-19
runnables = ( [self.default] + [r for _, r in self.branches] + [r for r, _ in self.branches] ) for runnable in runnables: if runnable.input_schema.schema().get("type") is not None: return runnable.input_schema return super().input_s...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-20
return output [docs] async def ainvoke( self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any ) -> Output: """Async version of invoke.""" config = ensure_config(config) callback_manager = get_callback_manager_for_config(config) run_manager = callback_m...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-21
fallbacks: Sequence[Runnable[Input, Output]] exceptions_to_handle: Tuple[Type[BaseException], ...] = (Exception,) class Config: arbitrary_types_allowed = True @property def InputType(self) -> Type[Input]: return self.runnable.InputType @property def OutputType(self) -> Type[Outpu...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-22
except self.exceptions_to_handle as e: if first_error is None: first_error = e except BaseException as e: run_manager.on_chain_error(e) raise e else: run_manager.on_chain_end(output) return output...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-23
[docs] def batch( self, inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any], ) -> List[Output]: from langchain.callbacks.manager import CallbackManager ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-24
first_error = e except BaseException as e: for rm in run_managers: rm.on_chain_error(e) raise e else: for rm, output in zip(run_managers, outputs): rm.on_chain_end(output) return outputs ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-25
) ) first_error = None for runnable in self.runnables: try: outputs = await runnable.abatch( inputs, [ # each step a child run of the corresponding root run patch_config(config, ca...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-26
return True [docs] @classmethod def get_lc_namespace(cls) -> List[str]: return cls.__module__.split(".")[:-1] class Config: arbitrary_types_allowed = True @property def InputType(self) -> Type[Input]: return self.first.InputType @property def OutputType(self) -> Type[O...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-27
Runnable[Other, Any], Callable[[Other], Any], Callable[[Iterator[Other]], Iterator[Any]], Mapping[str, Union[Runnable[Other, Any], Callable[[Other], Any], Any]], ], ) -> RunnableSequence[Other, Output]: if isinstance(other, RunnableSequence): return Ru...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-28
input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any], ) -> Output: # setup callbacks config = ensure_config(config) callback_manager = get_async_callback_manager_for_config(config) # start the root run run_manager = await callback_man...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-29
inheritable_metadata=config.get("metadata"), local_metadata=None, ) for config in configs ] # start the root runs, one per input run_managers = [ cm.on_chain_start( dumpd(self), input, name=config...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-30
for i, inp in zip(remaining_idxs, inputs): if isinstance(inp, Exception): failed_inputs_map[i] = inp inputs = [inp for inp in inputs if not isinstance(inp, Exception)] # If all inputs have failed, stop processing ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-31
return cast(List[Output], inputs) else: raise first_exception [docs] async def abatch( self, inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[An...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-32
failed_inputs_map: Dict[int, Exception] = {} for stepidx, step in enumerate(self.steps): # Assemble the original indexes of the remaining inputs # (i.e. the ones that haven't failed yet) remaining_idxs = [ i for i in ran...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-33
else: for i, step in enumerate(self.steps): inputs = await step.abatch( inputs, [ # each step a child run of the corresponding root run patch_config( ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-34
# buffer input in memory until all available, and then start emitting output final_pipeline = cast(Iterator[Output], input) for step in steps: final_pipeline = step.transform( final_pipeline, patch_config( config, callba...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-35
[docs] def stream( self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any], ) -> Iterator[Output]: yield from self.transform(iter([input]), config, **kwargs) [docs] async def atransform( self, input: AsyncIterator[Input], ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-36
], ], ) -> None: super().__init__(steps={key: coerce_to_runnable(r) for key, r in steps.items()}) [docs] @classmethod def is_lc_serializable(cls) -> bool: return True [docs] @classmethod def get_lc_namespace(cls) -> List[str]: return cls.__module__.split(".")[:-1] c...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-37
) def __repr__(self) -> str: map_for_repr = ",\n ".join( f"{k}: {indent_lines_after_first(repr(v), ' ' + k + ': ')}" for k, v in self.steps.items() ) return "{\n " + map_for_repr + "\n}" [docs] def invoke( self, input: Input, config: Optional[RunnableCon...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-38
# finish the root run except BaseException as e: run_manager.on_chain_error(e) raise else: run_manager.on_chain_end(output) return output [docs] async def ainvoke( self, input: Input, config: Optional[RunnableConfig] = None, ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-39
steps = dict(self.steps) # Each step gets a copy of the input iterator, # which is consumed in parallel in a separate thread. input_copies = list(safetee(input, len(steps), lock=threading.Lock())) with get_executor_for_config(config) as executor: # Create the transform() gene...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-40
yield from self._transform_stream_with_config( input, self._transform, config, **kwargs ) [docs] def stream( self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any], ) -> Iterator[Dict[str, Any]]: yield from self.transform(i...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-41
# and start the next iteration of the generator that yielded it. # When all generators are exhausted, stop. while tasks: completed_tasks, _ = await asyncio.wait( tasks, return_when=asyncio.FIRST_COMPLETED ) for task in completed_tasks: ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-42
Callable[[AsyncIterator[Input]], AsyncIterator[Output]], ], atransform: Optional[ Callable[[AsyncIterator[Input]], AsyncIterator[Output]] ] = None, ) -> None: if atransform is not None: self._atransform = atransform if inspect.isasyncgenfunction(transf...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-43
return self._transform == other._transform elif hasattr(self, "_atransform") and hasattr(other, "_atransform"): return self._atransform == other._atransform else: return False else: return False def __repr__(self) -> str: return "Ru...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-44
input, self._atransform, config, **kwargs ) [docs] def astream( self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> AsyncIterator[Output]: async def input_aiter() -> AsyncIterator[Input]: yield input return self.atra...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
6b75ba941317-45
) @property def InputType(self) -> Any: func = getattr(self, "func", None) or getattr(self, "afunc") try: params = inspect.signature(func).parameters first_param = next(iter(params.values()), None) if first_param and first_param.annotation != inspect.Parameter...
https://api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html