id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
7cd2723fa80e-10 | [docs] async def astream(
self,
input: Input,
config: Optional[RunnableConfig] = None,
**kwargs: Optional[Any],
) -> AsyncIterator[Output]:
"""
Default implementation of astream, which calls ainvoke.
Subclasses should override this method if they support st... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-11 | ...
[docs] async def astream_log(
self,
input: Any,
config: Optional[RunnableConfig] = None,
*,
diff: bool = True,
include_names: Optional[Sequence[str]] = None,
include_types: Optional[Sequence[str]] = None,
include_tags: Optional[Sequence[str]] = None... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-12 | config = config or {}
callbacks = config.get("callbacks")
if callbacks is None:
config["callbacks"] = [stream]
elif isinstance(callbacks, list):
config["callbacks"] = callbacks + [stream]
elif isinstance(callbacks, BaseCallbackManager):
callbacks = cal... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-13 | pass
[docs] def transform(
self,
input: Iterator[Input],
config: Optional[RunnableConfig] = None,
**kwargs: Optional[Any],
) -> Iterator[Output]:
"""
Default implementation of transform, which buffers input and then calls stream.
Subclasses should override ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-14 | if got_first_val:
async for output in self.astream(final, config, **kwargs):
yield output
[docs] def bind(self, **kwargs: Any) -> Runnable[Input, Output]:
"""
Bind arguments to a Runnable, returning a new Runnable.
"""
return RunnableBinding(bound=self, kwa... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-15 | added to the run.
"""
from langchain.callbacks.tracers.root_listeners import RootListenersTracer
return RunnableBinding(
bound=self,
config_factories=[
lambda config: {
"callbacks": [
RootListenersTracer(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-16 | return RunnableRetry(
bound=self,
kwargs={},
config={},
retry_exception_types=retry_if_exception_type,
wait_exponential_jitter=wait_exponential_jitter,
max_attempt_number=stop_after_attempt,
)
[docs] def map(self) -> Runnable[List[Input]... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-17 | ],
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 invoke() in subclasses."""
co... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-18 | dumpd(self),
input,
run_type=run_type,
name=config.get("run_name"),
)
try:
output = await acall_func_with_variable_args(
func, input, config, run_manager, **kwargs
)
except BaseException as e:
await run_manag... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-19 | run_type=run_type,
name=config.get("run_name"),
)
for callback_manager, input, config in zip(
callback_managers, input, configs
)
]
try:
if accepts_config(func):
kwargs["config"] = [
patch... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-20 | List[AsyncCallbackManagerForChainRun],
List[RunnableConfig],
],
Awaitable[List[Union[Exception, Output]]],
],
],
input: List[Input],
config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,
*,
return_exc... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-21 | )
if return_exceptions:
return cast(List[Output], [e for _ in input])
else:
raise
else:
first_exception: Optional[Exception] = None
coros: List[Awaitable[None]] = []
for run_manager, out in zip(run_managers, output):
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-22 | # Start the input iterator to ensure the input runnable starts before this one
final_input: Optional[Input] = next(input_for_tracing, None)
final_input_supported = True
final_output: Optional[Output] = None
final_output_supported = True
config = ensure_config(config)
call... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-23 | else:
run_manager.on_chain_end(final_output, inputs=final_input)
async def _atransform_stream_with_config(
self,
input: AsyncIterator[Input],
transformer: Union[
Callable[[AsyncIterator[Input]], AsyncIterator[Output]],
Callable[
[AsyncItera... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-24 | if accepts_config(transformer):
kwargs["config"] = patch_config(
config, callbacks=run_manager.get_child()
)
if accepts_run_manager(transformer):
kwargs["run_manager"] = run_manager
iterator = transformer(input_for_transform, **... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-25 | "available keys are {self.__fields__.keys()}"
)
return RunnableConfigurableFields(default=self, fields=kwargs)
[docs] def configurable_alternatives(
self,
which: ConfigurableField,
default_key: str = "default",
**kwargs: Union[Runnable[Input, Output], Callable[... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-26 | output -- then the sequence will be able to stream input to output!
If any component of the sequence does not implement transform then the
streaming will only begin after this component is run. If there are
multiple blocking components, streaming begins after the last one.
Please note: RunnableLambdas d... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-27 | prompt = PromptTemplate.from_template(
'In JSON format, give me a list of {topic} and their '
'corresponding names in French, Spanish and in a '
'Cat Language.'
)
model = ChatOpenAI()
chain = prompt | model | SimpleJsonOutputParser()
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-28 | return self.last.OutputType
[docs] def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> Type[BaseModel]:
from langchain.schema.runnable.passthrough import RunnableAssign
if isinstance(self.first, RunnableAssign):
first = cast(RunnableAssign, self.first)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-29 | Callable[[Any], Other],
Callable[[Iterator[Any]], Iterator[Other]],
Mapping[str, Union[Runnable[Any, Other], Callable[[Any], Other], Any]],
],
) -> RunnableSerializable[Input, Other]:
if isinstance(other, RunnableSequence):
return RunnableSequence(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-30 | dumpd(self), input, name=config.get("run_name")
)
# invoke all steps in sequence
try:
for i, step in enumerate(self.steps):
input = step.invoke(
input,
# mark each step as a child run
patch_config(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-31 | [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
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-32 | ]
# Invoke the step on the remaining inputs
inputs = step.batch(
[
inp
for i, inp in zip(remaining_idxs, inputs)
if i not in failed_inputs_map
],
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-33 | ],
)
# finish the root runs
except BaseException as e:
for rm in run_managers:
rm.on_chain_error(e)
if return_exceptions:
return cast(List[Output], [e for _ in inputs])
else:
raise
else:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-34 | *(
cm.on_chain_start(
dumpd(self),
input,
name=config.get("run_name"),
)
for cm, input, config in zip(callback_managers, inputs, configs)
)
)
# invoke .batch() on each step
# t... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-35 | 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
if len(failed_inputs_map) == len(configs):
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-36 | await asyncio.gather(*coros)
if return_exceptions or first_exception is None:
return cast(List[Output], inputs)
else:
raise first_exception
def _transform(
self,
input: Iterator[Input],
run_manager: CallbackManagerForChainRun,
c... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-37 | final_pipeline,
patch_config(
config,
callbacks=run_manager.get_child(f"seq:step:{steps.index(step)+1}"),
),
)
async for output in final_pipeline:
yield output
[docs] def transform(
self,
input: It... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-38 | """
A runnable that runs a mapping of runnables in parallel,
and returns a mapping of their outputs.
"""
steps: Mapping[str, Runnable[Input, Any]]
def __init__(
self,
__steps: Optional[
Mapping[
str,
Union[
Runnable[Inpu... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-39 | for s in self.steps.values()
):
# This is correct, but pydantic typings/mypy don't think so.
return create_model( # type: ignore[call-overload]
"RunnableParallelInput",
**{
k: (v.annotation, v.default)
for step in s... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-40 | from langchain.callbacks.manager import CallbackManager
# setup callbacks
config = ensure_config(config)
callback_manager = CallbackManager.configure(
inheritable_callbacks=config.get("callbacks"),
local_callbacks=None,
verbose=False,
inheritable_t... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-41 | callback_manager = get_async_callback_manager_for_config(config)
# start the root run
run_manager = await callback_manager.on_chain_start(
dumpd(self), input, name=config.get("run_name")
)
# gather results from all steps
try:
# copy to avoid issues from th... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-42 | step.transform(
input_copies.pop(),
patch_config(
config, callbacks=run_manager.get_child(f"map:key:{name}")
),
),
)
for name, step in steps.items()
]
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-43 | self,
input: AsyncIterator[Input],
run_manager: AsyncCallbackManagerForChainRun,
config: RunnableConfig,
) -> AsyncIterator[AddableDict]:
# Shallow copy steps to ignore mutations while in progress
steps = dict(self.steps)
# Each step gets a copy of the input iterator,... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-44 | yield chunk
new_task = asyncio.create_task(get_next_chunk(generator))
tasks[new_task] = (step_name, generator)
except StopAsyncIteration:
pass
[docs] async def atransform(
self,
input: AsyncIterator[Input],
config: Op... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-45 | self._atransform = transform
elif inspect.isgeneratorfunction(transform):
self._transform = transform
else:
raise TypeError(
"Expected a generator function type for `transform`."
f"Instead got an unsupported type: {type(transform)}"
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-46 | return "RunnableGenerator(...)"
[docs] def transform(
self,
input: Iterator[Input],
config: Optional[RunnableConfig] = None,
**kwargs: Any,
) -> Iterator[Output]:
return self._transform_stream_with_config(
input, self._transform, config, **kwargs
)
[doc... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-47 | async def input_aiter() -> AsyncIterator[Input]:
yield input
return self.atransform(input_aiter(), config, **kwargs)
[docs] async def ainvoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
final = None
async for output in self.... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-48 | runnable = RunnableLambda(add_one, afunc=add_one_async)
runnable.invoke(1) # Uses add_one
await runnable.ainvoke(1) # Uses add_one_async
"""
[docs] def __init__(
self,
func: Union[
Union[
Callable[[Input], Output],
Callable[[Inpu... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-49 | self.afunc = afunc
if inspect.iscoroutinefunction(func):
if afunc is not None:
raise TypeError(
"Func was provided as a coroutine function, but afunc was "
"also provided. If providing both, func should be a regular "
"funct... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-50 | if all(
item[0] == "'" and item[-1] == "'" and len(item) > 2 for item in items
):
# It's a dict, lol
return create_model(
"RunnableLambdaInput",
**{item[1:-1]: (Any, None) for item in items}, # type: ignore
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-51 | """A string representation of this runnable."""
if hasattr(self, "func"):
return f"RunnableLambda({get_lambda_source(self.func) or '...'})"
elif hasattr(self, "afunc"):
return f"RunnableLambda(afunc={get_lambda_source(self.afunc) or '...'})"
else:
return "Runn... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-52 | recursion_limit = config["recursion_limit"]
if recursion_limit <= 0:
raise RecursionError(
f"Recursion limit reached when invoking {self} with input {input}."
)
output = await output.ainvoke(
input,
patch_config(... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-53 | """Invoke this runnable asynchronously."""
if hasattr(self, "afunc"):
return await self._acall_with_config(
self._ainvoke,
input,
self._config(config, self.afunc),
**kwargs,
)
else:
# Delegating to super ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-54 | return create_model(
"RunnableEachOutput",
__root__=(
List[schema], # type: ignore
None,
),
)
@property
def config_specs(self) -> List[ConfigurableFieldSpec]:
return self.bound.config_specs
[docs] @classmethod
def is_lc_... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-55 | ) -> List[Output]:
return await self._acall_with_config(self._ainvoke, input, config, **kwargs)
[docs]class RunnableEach(RunnableEachBase[Input, Output]):
"""
A runnable that delegates calls to another runnable
with each element of the input sequence.
"""
[docs] def bind(self, **kwargs: Any) ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-56 | )
[docs]class RunnableBindingBase(RunnableSerializable[Input, Output]):
"""
A runnable that delegates calls to another runnable with a set of kwargs.
Use only if creating a new RunnableBinding subclass with different __init__ args.
"""
bound: Runnable[Input, Output]
kwargs: Mapping[str, Any] = F... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-57 | if key not in allowed_keys:
raise ValueError(
f"Configurable key '{key}' not found in runnable with"
f" config keys: {allowed_keys}"
)
super().__init__(
bound=bound,
kwargs=kwargs or {},
c... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-58 | [docs] @classmethod
def is_lc_serializable(cls) -> bool:
return True
[docs] @classmethod
def get_lc_namespace(cls) -> List[str]:
return cls.__module__.split(".")[:-1]
def _merge_configs(self, *configs: Optional[RunnableConfig]) -> RunnableConfig:
config = merge_configs(self.con... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-59 | configs = [self._merge_configs(config) for _ in range(len(inputs))]
return self.bound.batch(
inputs,
configs,
return_exceptions=return_exceptions,
**{**self.kwargs, **kwargs},
)
[docs] async def abatch(
self,
inputs: List[Input],
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-60 | **{**self.kwargs, **kwargs},
):
yield item
[docs] def transform(
self,
input: Iterator[Input],
config: Optional[RunnableConfig] = None,
**kwargs: Any,
) -> Iterator[Output]:
yield from self.bound.transform(
input,
self._merge_con... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-61 | return self.__class__(
bound=self.bound,
kwargs=self.kwargs,
config=cast(RunnableConfig, {**self.config, **(config or {}), **kwargs}),
custom_input_type=self.custom_input_type,
custom_output_type=self.custom_output_type,
)
[docs] def with_listeners(... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-62 | )
[docs] def with_types(
self,
input_type: Optional[Union[Type[Input], BaseModel]] = None,
output_type: Optional[Union[Type[Output], BaseModel]] = None,
) -> Runnable[Input, Output]:
return self.__class__(
bound=self.bound,
kwargs=self.kwargs,
c... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
7cd2723fa80e-63 | return cast(Runnable[Input, Output], RunnableParallel(thing))
else:
raise TypeError(
f"Expected a Runnable, callable or dict."
f"Instead got an unsupported type: {type(thing)}"
) | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html |
f94b50230f5b-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.schema.runnable.base import (
Input,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html |
f94b50230f5b-1 | ) -> None:
super().__init__(
runnables={key: coerce_to_runnable(r) for key, r in runnables.items()}
)
class Config:
arbitrary_types_allowed = True
[docs] @classmethod
def is_lc_serializable(cls) -> bool:
"""Return whether this class is serializable."""
retu... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html |
f94b50230f5b-2 | ) -> List[Output]:
if not inputs:
return []
keys = [input["key"] for input in inputs]
actual_inputs = [input["input"] for input in inputs]
if any(key not in self.runnables for key in keys):
raise ValueError("One or more keys do not have a corresponding runnable")
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html |
f94b50230f5b-3 | runnable: Runnable, input: Input, config: RunnableConfig
) -> Union[Output, Exception]:
if return_exceptions:
try:
return await runnable.ainvoke(input, config, **kwargs)
except Exception as e:
return e
else:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/router.html |
d653e3fa9b4b-0 | Source code for langchain.schema.runnable.fallbacks
import asyncio
from typing import (
TYPE_CHECKING,
Any,
Iterator,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
)
from langchain.load.dump import dumpd
from langchain.pydantic_v1 import BaseModel
from langchain.schema.runnable.base ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html |
d653e3fa9b4b-1 | .. code-block:: python
from langchain.chat_models.openai import ChatOpenAI
from langchain.chat_models.anthropic import ChatAnthropic
model = ChatAnthropic().with_fallbacks([ChatOpenAI()])
# Will usually use ChatAnthropic, but fallback to ChatOpenAI
# if ChatAn... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html |
d653e3fa9b4b-2 | @property
def OutputType(self) -> Type[Output]:
return self.runnable.OutputType
[docs] def get_input_schema(
self, config: Optional[RunnableConfig] = None
) -> Type[BaseModel]:
return self.runnable.get_input_schema(config)
[docs] def get_output_schema(
self, config: Optiona... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html |
d653e3fa9b4b-3 | input,
patch_config(config, callbacks=run_manager.get_child()),
**kwargs,
)
except self.exceptions_to_handle as e:
if first_error is None:
first_error = e
except BaseException as e:
run_ma... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html |
d653e3fa9b4b-4 | raise first_error
[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 Call... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html |
d653e3fa9b4b-5 | if first_error is None:
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(... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html |
d653e3fa9b4b-6 | )
)
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... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/fallbacks.html |
b766d60527a8-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 itertools import groupby
from typing import (
Any,
AsyncIterable,
Callable,
Coroutine,
Dict,
Iterable,
List,
Mapp... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html |
b766d60527a8-1 | except ValueError:
return False
[docs]def accepts_config(callable: Callable[..., Any]) -> bool:
"""Check if a callable accepts a config argument."""
try:
return signature(callable).parameters.get("config") is not None
except ValueError:
return False
[docs]class IsLocalDict(ast.NodeVi... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html |
b766d60527a8-2 | """Check if the first argument of a function is a dict."""
[docs] def __init__(self) -> None:
self.keys: Set[str] = set()
[docs] def visit_Lambda(self, node: ast.Lambda) -> Any:
input_arg_name = node.args.args[0].arg
IsLocalDict(input_arg_name, self.keys).visit(node.body)
[docs] def vis... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html |
b766d60527a8-3 | visitor.visit(tree)
return list(visitor.keys) if visitor.keys else None
except (SyntaxError, TypeError, OSError):
return None
[docs]def get_lambda_source(func: Callable) -> Optional[str]:
"""Get the source code of a lambda function.
Args:
func: a callable that can be a lambda functio... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html |
b766d60527a8-4 | elif other[key] is not None:
try:
added = chunk[key] + other[key]
except TypeError:
added = other[key]
chunk[key] = added
return chunk
def __radd__(self, other: AddableDict) -> AddableDict:
chunk = AddableDict(ot... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html |
b766d60527a8-5 | if final is None:
final = chunk
else:
final = final + chunk
return final
[docs]class ConfigurableField(NamedTuple):
"""A field that can be configured by the user."""
id: str
name: Optional[str] = None
description: Optional[str] = None
annotation: Optional[Any] = N... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html |
b766d60527a8-6 | default: Any
annotation: Any
[docs]def get_unique_config_specs(
specs: Iterable[ConfigurableFieldSpec],
) -> List[ConfigurableFieldSpec]:
"""Get the unique config specs from a sequence of config specs."""
grouped = groupby(sorted(specs, key=lambda s: s.id), lambda s: s.id)
unique: List[ConfigurableF... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/utils.html |
63a357835cb9-0 | Source code for langchain.schema.runnable.config
from __future__ import annotations
from concurrent.futures import Executor, ThreadPoolExecutor
from contextlib import contextmanager
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
Generator,
List,
Optional,
Union,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html |
63a357835cb9-1 | Tags are passed to all callbacks, metadata is passed to handle*Start callbacks.
"""
run_name: str
"""
Name for the tracer run for this call. Defaults to the name of the class.
"""
max_concurrency: Optional[int]
"""
Maximum number of parallel calls to make. If not provided, defaults to
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html |
63a357835cb9-2 | ) -> List[RunnableConfig]:
"""Get a list of configs from a single config or a list of configs.
It is useful for subclasses overriding batch() or abatch().
Args:
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]):
The config or list of configs.
length (int): The length ... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html |
63a357835cb9-3 | callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.
Defaults to None.
recursion_limit (Optional[int], optional): The recursion limit to set.
Defaults to None.
max_concurrency (Optional[int], optional): The max concurrency to set.
Defaults to None.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html |
63a357835cb9-4 | # because both dicts are the same type
for config in (c for c in configs if c is not None):
for key in config:
if key == "metadata":
base[key] = { # type: ignore
**base.get(key, {}), # type: ignore
**(config.get(key) or {}), # type: igno... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html |
63a357835cb9-5 | mngr = these_callbacks.copy()
for callback in base_callbacks:
mngr.add_handler(callback, inherit=True)
base["callbacks"] = mngr
else:
# base_callbacks is also a manager
base["c... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html |
63a357835cb9-6 | The function to call.
input (Input): The input to the function.
run_manager (CallbackManagerForChainRun): The run manager to
pass to the function.
config (RunnableConfig): The config to pass to the function.
**kwargs (Any): The keyword arguments to pass to the function.
Ret... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html |
63a357835cb9-7 | The function to call.
input (Input): The input to the function.
run_manager (AsyncCallbackManagerForChainRun): The run manager
to pass to the function.
config (RunnableConfig): The config to pass to the function.
**kwargs (Any): The keyword arguments to pass to the function.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html |
63a357835cb9-8 | inheritable_callbacks=config.get("callbacks"),
inheritable_tags=config.get("tags"),
inheritable_metadata=config.get("metadata"),
)
[docs]@contextmanager
def get_executor_for_config(config: RunnableConfig) -> Generator[Executor, None, None]:
"""Get an executor for a config.
Args:
conf... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/config.html |
c31c0a27d954-0 | Source code for langchain.schema.runnable.history
from __future__ import annotations
import asyncio
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Sequence,
Type,
Union,
)
from langchain.load import load
from langchain.pydantic_v1 import BaseModel, create_mo... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html |
c31c0a27d954-1 | prompt = ChatPromptTemplate.from_messages([
("system", "You're an assistant who's good at {ability}"),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
])
chain = prompt | ChatAnthropic(model="claude-2")
chain_with... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html |
c31c0a27d954-2 | Args:
runnable: The base Runnable to be wrapped.
Must take as input one of:
- A sequence of BaseMessages
- A dict with one key for all messages
- A dict with one key for the current input string/message(s) and
a separate key... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html |
c31c0a27d954-3 | messages_key = history_messages_key or input_messages_key
if messages_key:
history_chain = RunnablePassthrough.assign(
**{messages_key: history_chain}
).with_config(run_name="insert_history")
bound = (
history_chain | runnable.with_listeners(on_end=sel... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html |
c31c0a27d954-4 | if self.history_messages_key:
fields[self.history_messages_key] = (Sequence[BaseMessage], ...)
return create_model( # type: ignore[call-overload]
"RunnableWithChatHistoryInput",
**fields,
)
else:
return super_schema
def _ge... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html |
c31c0a27d954-5 | hist = config["configurable"]["message_history"]
# return only historic messages
if self.history_messages_key:
return hist.messages.copy()
# return all messages
else:
input_val = (
input if not self.input_messages_key else input[self.input_messages... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html |
c31c0a27d954-6 | " Pass it in as part of the config argument to .invoke() or .stream()"
f"\neg. chain.invoke({example_input}, {example_config})"
)
# attach message_history
session_id = config["configurable"]["session_id"]
config["configurable"]["message_history"] = self.get_session_hi... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/history.html |
879e07ce5e54-0 | Source code for langchain.schema.runnable.branch
from typing import (
Any,
Awaitable,
Callable,
List,
Mapping,
Optional,
Sequence,
Tuple,
Type,
Union,
cast,
)
from langchain.load.dump import dumpd
from langchain.pydantic_v1 import BaseModel
from langchain.schema.runnable.base... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/branch.html |
879e07ce5e54-1 | )
branch.invoke("hello") # "HELLO"
branch.invoke(None) # "goodbye"
"""
branches: Sequence[Tuple[Runnable[Input, bool], Runnable[Input, Output]]]
default: Runnable[Input, Output]
def __init__(
self,
*branches: Union[
Tuple[
Union[
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/branch.html |
879e07ce5e54-2 | )
condition, runnable = branch
condition = cast(Runnable[Input, bool], coerce_to_runnable(condition))
runnable = coerce_to_runnable(runnable)
_branches.append((condition, runnable))
super().__init__(branches=_branches, default=default_)
class Config:
a... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/branch.html |
879e07ce5e54-3 | ) -> Output:
"""First evaluates the condition, then delegate to true or false branch."""
config = ensure_config(config)
callback_manager = get_callback_manager_for_config(config)
run_manager = callback_manager.on_chain_start(
dumpd(self),
input,
name=c... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/branch.html |
879e07ce5e54-4 | input,
name=config.get("run_name"),
)
try:
for idx, branch in enumerate(self.branches):
condition, runnable = branch
expression_value = await condition.ainvoke(
input,
config=patch_config(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/branch.html |
df1ad08b95f6-0 | Source code for langchain.graphs.rdf_graph
from __future__ import annotations
from typing import (
TYPE_CHECKING,
List,
Optional,
)
if TYPE_CHECKING:
import rdflib
prefixes = {
"owl": """PREFIX owl: <http://www.w3.org/2002/07/owl#>\n""",
"rdf": """PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-sy... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
df1ad08b95f6-1 | """ FILTER (isIRI(?cls)) . \n"""
""" OPTIONAL { ?cls rdfs:comment ?com } \n"""
"""}"""
)
rel_query_rdf = prefixes["rdfs"] + (
"""SELECT DISTINCT ?rel ?com\n"""
"""WHERE { \n"""
""" ?subj ?rel ?obj . \n"""
""" OPTIONAL { ?rel rdfs:comment ?com } \n"""
"""}"""
)
rel_query_rdfs = (
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
df1ad08b95f6-2 | """}"""
)
)
[docs]class RdfGraph:
"""RDFlib wrapper for graph operations.
Modes:
* local: Local file - can be queried and changed
* online: Online file - can only be queried, changes can be stored locally
* store: Triple store - can be queried and changed if update_endpoint available
Togethe... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
df1ad08b95f6-3 | :param standard: RDF, RDFS, or OWL
:param local_copy: new local copy for storing changes
"""
self.source_file = source_file
self.serialization = serialization
self.query_endpoint = query_endpoint
self.update_endpoint = update_endpoint
self.standard = standard
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
df1ad08b95f6-4 | self._store = sparqlstore.SPARQLStore()
self._store.open(query_endpoint)
else:
self._store = sparqlstore.SPARQLUpdateStore()
self._store.open((query_endpoint, update_endpoint))
self.graph = rdflib.Graph(self._store, identifier=default)
# Ve... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
df1ad08b95f6-5 | )
else:
raise ValueError("No target file specified for saving the updated file.")
@staticmethod
def _get_local_name(iri: str) -> str:
if "#" in iri:
local_name = iri.split("#")[-1]
elif "/" in iri:
local_name = iri.split("/")[-1]
else:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
df1ad08b95f6-6 | clss = self.query(cls_query_rdf)
rels = self.query(rel_query_rdf)
self.schema = _rdf_s_schema(clss, rels)
elif self.standard == "rdfs":
clss = self.query(cls_query_rdfs)
rels = self.query(rel_query_rdfs)
self.schema = _rdf_s_schema(clss, rels)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.