id
stringlengths
14
16
text
stringlengths
13
2.7k
source
stringlengths
57
178
8cf9574238da-38
tags=inheritable_callbacks.tags.copy(), inheritable_tags=inheritable_callbacks.inheritable_tags.copy(), metadata=inheritable_callbacks.metadata.copy(), inheritable_metadata=inheritable_callbacks.inheritable_metadata.copy(), ) local_handlers_ = ( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html
8cf9574238da-39
if tracing_enabled_ and not any( isinstance(handler, LangChainTracerV1) for handler in callback_manager.handlers ): if tracer: callback_manager.add_handler(tracer, True) else: handler = LangChainTracerV1() handler.lo...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/manager.html
f40b4e1ca980-0
Source code for langchain.schema.callbacks.stdout """Callback Handler that prints to std out.""" from typing import Any, Dict, List, Optional from langchain.schema import AgentAction, AgentFinish, LLMResult from langchain.schema.callbacks.base import BaseCallbackHandler from langchain.utils.input import print_text [doc...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/stdout.html
f40b4e1ca980-1
"""Print out that we finished a chain.""" print("\n\033[1m> Finished chain.\033[0m") [docs] def on_chain_error(self, error: BaseException, **kwargs: Any) -> None: """Do nothing.""" pass [docs] def on_tool_start( self, serialized: Dict[str, Any], input_str: str, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/stdout.html
f40b4e1ca980-2
) -> None: """Run when agent ends.""" print_text(text, color=color or self.color, end=end) [docs] def on_agent_finish( self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any ) -> None: """Run on agent end.""" print_text(finish.log, color=color or self.color,...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/stdout.html
36fe02779302-0
Source code for langchain.schema.callbacks.base """Base callback handler that can be used to handle callbacks in langchain.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Sequence, TypeVar, Union from uuid import UUID from tenacity import RetryCallState from langchain.schema.agent i...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
36fe02779302-1
Args: token (str): The new token. chunk (GenerationChunk | ChatGenerationChunk): The new generated chunk, containing content and other information. """ [docs] def on_llm_end( self, response: LLMResult, *, run_id: UUID, parent_run_id:...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
36fe02779302-2
) -> Any: """Run on agent action.""" [docs] def on_agent_finish( self, finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any, ) -> Any: """Run on agent end.""" [docs]class ToolManagerMixin: """Mixin for tool c...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
36fe02779302-3
messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> Any: """Run when a chat model starts running.""" raise NotImpleme...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
36fe02779302-4
metadata: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> Any: """Run when tool starts running.""" [docs]class RunManagerMixin: """Mixin for run manager.""" [docs] def on_text( self, text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None,...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
36fe02779302-5
"""Whether to ignore retriever callbacks.""" return False @property def ignore_chat_model(self) -> bool: """Whether to ignore chat model callbacks.""" return False [docs]class AsyncCallbackHandler(BaseCallbackHandler): """Async callback handler that handles callbacks from LangChain."...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
36fe02779302-6
**kwargs: Any, ) -> None: """Run on new LLM token. Only available when streaming is enabled.""" [docs] async def on_llm_end( self, response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
36fe02779302-7
self, error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any, ) -> None: """Run when chain errors.""" [docs] async def on_tool_start( self, serialized: Dict[str, Any], ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
36fe02779302-8
) -> None: """Run on arbitrary text.""" [docs] async def on_retry( self, retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any, ) -> Any: """Run on a retry event.""" [docs] async def on_agent_action( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
36fe02779302-9
tags: Optional[List[str]] = None, **kwargs: Any, ) -> None: """Run on retriever end.""" [docs] async def on_retriever_error( self, error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
36fe02779302-10
"""Copy the callback manager.""" return self.__class__( handlers=self.handlers, inheritable_handlers=self.inheritable_handlers, parent_run_id=self.parent_run_id, tags=self.tags, inheritable_tags=self.inheritable_tags, metadata=self.metadata...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
36fe02779302-11
for tag in tags: if tag in self.tags: self.remove_tags([tag]) self.tags.extend(tags) if inherit: self.inheritable_tags.extend(tags) [docs] def remove_tags(self, tags: List[str]) -> None: for tag in tags: self.tags.remove(tag) sel...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/base.html
8f80e23d99e8-0
Source code for langchain.schema.callbacks.tracers.stdout import json from typing import Any, Callable, List from langchain.schema.callbacks.tracers.base import BaseTracer from langchain.schema.callbacks.tracers.schemas import Run from langchain.utils.input import get_bolded_text, get_colored_text [docs]def try_json_st...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/stdout.html
8f80e23d99e8-1
super().__init__(**kwargs) self.function_callback = function def _persist_run(self, run: Run) -> None: pass [docs] def get_parents(self, run: Run) -> List[Run]: parents = [] current_run = run while current_run.parent_run_id: parent = self.run_map.get(str(curren...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/stdout.html
8f80e23d99e8-2
+ get_bolded_text( f"[{crumbs}] [{elapsed(run)}] Exiting {run_type} run with output:\n" ) + f"{try_json_stringify(run.outputs, '[outputs]')}" ) def _on_chain_error(self, run: Run) -> None: crumbs = self.get_breadcrumbs(run) run_type = run.run_type.capi...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/stdout.html
8f80e23d99e8-3
) + f"{try_json_stringify(run.outputs, '[response]')}" ) def _on_llm_error(self, run: Run) -> None: crumbs = self.get_breadcrumbs(run) self.function_callback( f"{get_colored_text('[llm/error]', color='red')} " + get_bolded_text( f"[{crumbs}...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/stdout.html
8f80e23d99e8-4
+ get_bolded_text(f"[{crumbs}] [{elapsed(run)}] ") + f"Tool run errored with error:\n" f"{run.error}" ) [docs]class ConsoleCallbackHandler(FunctionCallbackHandler): """Tracer that prints to the console.""" name: str = "console_callback_handler" [docs] def __init__(self, **kwar...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/stdout.html
1ff71c24663c-0
Source code for langchain.schema.callbacks.tracers.root_listeners from typing import Callable, Optional, Union from uuid import UUID from langchain.schema.callbacks.tracers.base import BaseTracer from langchain.schema.callbacks.tracers.schemas import Run from langchain.schema.runnable.config import ( RunnableConfig...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/root_listeners.html
1ff71c24663c-1
else: if self._arg_on_error is not None: call_func_with_variable_args(self._arg_on_error, run, self.config)
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/root_listeners.html
2e9c3311c106-0
Source code for langchain.schema.callbacks.tracers.log_stream from __future__ import annotations import math import threading from collections import defaultdict from typing import ( Any, AsyncIterator, Dict, List, Optional, Sequence, TypedDict, Union, ) from uuid import UUID import json...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html
2e9c3311c106-1
"""ID of the run.""" streamed_output: List[Any] """List of output chunks streamed by Runnable.stream()""" final_output: Optional[Any] """Final output of the run, usually the result of aggregating (`+`) streamed_output. Only available after the run has finished successfully.""" logs: Dict[str, Lo...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html
2e9c3311c106-2
# 1:-1 to get rid of the [] around the list return f"RunLogPatch({pformat(self.ops)[1:-1]})" def __eq__(self, other: object) -> bool: return isinstance(other, RunLogPatch) and self.ops == other.ops [docs]class RunLog(RunLogPatch): """A run log.""" state: RunState """Current state of the ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html
2e9c3311c106-3
exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, ) -> None: super().__init__() self.auto_close = auto_close self.include_names = include_names self.include_types = include_types self.include_tags = include_tags self....
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html
2e9c3311c106-4
include = include and run.name not in self.exclude_names if self.exclude_types is not None: include = include and run.run_type not in self.exclude_types if self.exclude_tags is not None: include = include and all(tag not in self.exclude_tags for tag in run_tags) return in...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html
2e9c3311c106-5
id=str(run.id), name=run.name, type=run.run_type, tags=run.tags or [], metadata=(run.extra or {}).get("metadata", {}), start_time=run.start_time.isoformat(timespec="milliseconds"), ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html
2e9c3311c106-6
chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]], ) -> None: """Process new LLM token.""" index = self._key_map_by_run_id.get(run.id) if index is None: return self.send_stream.send_nowait( RunLogPatch( { "op": "a...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/log_stream.html
112b8d993f7b-0
Source code for langchain.schema.callbacks.tracers.langchain """A Tracer implementation that records to LangChain endpoint.""" from __future__ import annotations import logging import weakref from concurrent.futures import Future, ThreadPoolExecutor, wait from datetime import datetime from typing import Any, Callable, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html
112b8d993f7b-1
global _CLIENT if _CLIENT is None: _CLIENT = Client() return _CLIENT def _get_executor() -> ThreadPoolExecutor: """Get the executor.""" global _EXECUTOR if _EXECUTOR is None: _EXECUTOR = ThreadPoolExecutor() return _EXECUTOR def _copy(run: Run) -> Run: """Copy a run.""" t...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html
112b8d993f7b-2
global _TRACERS _TRACERS.add(self) [docs] def on_chat_model_start( self, serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[D...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html
112b8d993f7b-3
"""Get the LangSmith root run URL""" if not self.latest_run: raise ValueError("No traced run found.") # If this is the first run in a project, the project may not yet be created. # This method is only really useful for debugging flows, so we will assume # there is some tolera...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html
112b8d993f7b-4
run_dict["tags"] = self._get_tags(run) self.client.update_run(run.id, **run_dict) except Exception as e: # Errors are swallowed by the thread executor so we need to log them here log_error_once("patch", e) raise def _submit(self, function: Callable[[Run], None...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html
112b8d993f7b-5
self._submit(self._persist_run_single, _copy(run)) def _on_chain_end(self, run: Run) -> None: """Process the Chain Run.""" self._submit(self._update_run_single, _copy(run)) def _on_chain_error(self, run: Run) -> None: """Process the Chain Run upon error.""" self._submit(self._upd...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html
112b8d993f7b-6
self._submit(self._update_run_single, _copy(run)) [docs] def wait_for_futures(self) -> None: """Wait for the given futures to complete.""" wait(self._futures)
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain.html
287a21143fb9-0
Source code for langchain.schema.callbacks.tracers.base """Base interfaces for tracing runs.""" from __future__ import annotations import logging from abc import ABC, abstractmethod from datetime import datetime from typing import Any, Dict, List, Optional, Sequence, Union, cast from uuid import UUID from tenacity impo...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-1
parent_run.child_execution_order = max( parent_run.child_execution_order, run.child_execution_order ) else: logger.debug(f"Parent run with UUID {run.parent_run_id} not found.") self.run_map[str(run.id)] = run self._on_run_create(run) de...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-2
self, serialized: Dict[str, Any], prompts: List[str], *, run_id: UUID, tags: Optional[List[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, **kwargs: Any, ) -> Run: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-3
if not run_id: raise TracerException("No run_id provided for on_llm_new_token callback.") run_id_ = str(run_id) llm_run = self.run_map.get(run_id_) if llm_run is None or llm_run.run_type != "llm": raise TracerException(f"No LLM Run found to be traced for {run_id}") ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-4
exception = retry_state.outcome.exception() retry_d["exception"] = str(exception) retry_d["exception_type"] = exception.__class__.__name__ else: retry_d["outcome"] = "success" retry_d["result"] = str(retry_state.outcome.result()) llm_run.events.append( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-5
self._on_llm_end(llm_run) return llm_run [docs] def on_llm_error( self, error: BaseException, *, run_id: UUID, **kwargs: Any, ) -> Run: """Handle an error for an LLM run.""" if not run_id: raise TracerException("No run_id provided for on...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-6
start_time = datetime.utcnow() if metadata: kwargs.update({"metadata": metadata}) chain_run = Run( id=run_id, parent_run_id=parent_run_id, serialized=serialized, inputs=inputs if isinstance(inputs, dict) else {"input": inputs}, extr...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-7
self._end_trace(chain_run) self._on_chain_end(chain_run) return chain_run [docs] def on_chain_error( self, error: BaseException, *, inputs: Optional[Dict[str, Any]] = None, run_id: UUID, **kwargs: Any, ) -> Run: """Handle an error for a chai...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-8
start_time = datetime.utcnow() if metadata: kwargs.update({"metadata": metadata}) tool_run = Run( id=run_id, parent_run_id=parent_run_id, serialized=serialized, inputs={"input": input_str}, extra=kwargs, events=[{"name":...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-9
"""Handle an error for a tool run.""" if not run_id: raise TracerException("No run_id provided for on_tool_error callback.") tool_run = self.run_map.get(str(run_id)) if tool_run is None or tool_run.run_type != "tool": raise TracerException(f"No tool Run found to be traced...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-10
start_time=start_time, execution_order=execution_order, child_execution_order=execution_order, tags=tags, child_runs=[], run_type="retriever", ) self._start_trace(retrieval_run) self._on_retriever_start(retrieval_run) return ret...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-11
if retrieval_run is None or retrieval_run.run_type != "retriever": raise TracerException(f"No retriever Run found to be traced for {run_id}") retrieval_run.outputs = {"documents": documents} retrieval_run.end_time = datetime.utcnow() retrieval_run.events.append({"name": "end", "time"...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
287a21143fb9-12
def _on_chain_end(self, run: Run) -> None: """Process the Chain Run.""" def _on_chain_error(self, run: Run) -> None: """Process the Chain Run upon error.""" def _on_tool_start(self, run: Run) -> None: """Process the Tool Run upon start.""" def _on_tool_end(self, run: Run) -> None: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/base.html
947f1b04301c-0
Source code for langchain.schema.callbacks.tracers.schemas """Schemas for tracers.""" from __future__ import annotations import datetime import warnings from typing import Any, Dict, List, Optional, Type from uuid import UUID from langsmith.schemas import RunBase as BaseRunV2 from langsmith.schemas import RunTypeEnum a...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/schemas.html
947f1b04301c-1
"""Base class for Run.""" uuid: str parent_uuid: Optional[str] = None start_time: datetime.datetime = Field(default_factory=datetime.datetime.utcnow) end_time: datetime.datetime = Field(default_factory=datetime.datetime.utcnow) extra: Optional[Dict[str, Any]] = None execution_order: int chil...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/schemas.html
947f1b04301c-2
child_runs: List[Run] = Field(default_factory=list) tags: Optional[List[str]] = Field(default_factory=list) events: List[Dict[str, Any]] = Field(default_factory=list) @root_validator(pre=True) def assign_name(cls, values: dict) -> dict: """Assign name to the run.""" if values.get("name")...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/schemas.html
f6a8d154d519-0
Source code for langchain.schema.callbacks.tracers.evaluation """A tracer that runs evaluators over completed runs.""" from __future__ import annotations import logging import threading import weakref from concurrent.futures import Future, ThreadPoolExecutor, wait from typing import Any, Dict, List, Optional, Sequence,...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/evaluation.html
f6a8d154d519-1
Attributes ---------- example_id : Union[UUID, None] The example ID associated with the runs. client : Client The LangSmith client instance used for evaluating the runs. evaluators : Sequence[RunEvaluator] The sequence of run evaluators to be executed. executor : ThreadPoolEx...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/evaluation.html
f6a8d154d519-2
weakref.finalize( self, lambda: cast(ThreadPoolExecutor, self.executor).shutdown(wait=True), ) else: self.executor = None self.futures: weakref.WeakSet[Future] = weakref.WeakSet() self.skip_unfinished = skip_unfinished self.project_...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/evaluation.html
f6a8d154d519-3
f"{evaluator.__class__.__name__}: {repr(e)}", exc_info=True, ) raise e example_id = str(run.reference_example_id) with self.lock: for res in eval_results: run_id = ( str(getattr(res, "target_run_id")) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/evaluation.html
f6a8d154d519-4
else run.id ) self.client.create_feedback( run_id_, res.key, score=res.score, value=res.value, comment=res.comment, correction=res.correction, source_info=source_info_, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/evaluation.html
1c9bcca8f7de-0
Source code for langchain.schema.callbacks.tracers.run_collector """A tracer that collects all nested runs in a list.""" from typing import Any, List, Optional, Union from uuid import UUID from langchain.schema.callbacks.tracers.base import BaseTracer from langchain.schema.callbacks.tracers.schemas import Run [docs]cla...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/run_collector.html
270fb32cca4e-0
Source code for langchain.schema.callbacks.tracers.langchain_v1 from __future__ import annotations import logging import os from typing import Any, Dict, Optional, Union import requests from langchain.schema.callbacks.tracers.base import BaseTracer from langchain.schema.callbacks.tracers.schemas import ( ChainRun, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain_v1.html
270fb32cca4e-1
if not isinstance(session, TracerSessionV1): raise ValueError( "LangChainTracerV1 is not compatible with" f" session of type {type(session)}" ) if run.run_type == "llm": if "prompts" in run.inputs: prompts = run.inputs["prompts"...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain_v1.html
270fb32cca4e-2
outputs=run.outputs, error=run.error, extra=run.extra, child_llm_runs=[run for run in child_runs if isinstance(run, LLMRun)], child_chain_runs=[ run for run in child_runs if isinstance(run, ChainRun) ], c...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain_v1.html
270fb32cca4e-3
v1_run = self._convert_to_v1_run(run) else: v1_run = run if isinstance(v1_run, LLMRun): endpoint = f"{self._endpoint}/llm-runs" elif isinstance(v1_run, ChainRun): endpoint = f"{self._endpoint}/chain-runs" else: endpoint = f"{self._endpoint}...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain_v1.html
270fb32cca4e-4
r = requests.get(url, headers=self._headers) tracer_session = TracerSessionV1(**r.json()[0]) except Exception as e: session_type = "default" if not session_name else session_name logger.warning( f"Failed to load {session_type} session, using empty session: {e}...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/callbacks/tracers/langchain_v1.html
6ca47b79a450-0
Source code for langchain.schema.runnable.passthrough """Implementation of the RunnablePassthrough.""" from __future__ import annotations import asyncio import inspect import threading from typing import ( Any, AsyncIterator, Awaitable, Callable, Dict, Iterator, List, Mapping, Option...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
6ca47b79a450-1
and experiment with. Examples: .. code-block:: python from langchain.schema.runnable import RunnablePassthrough, RunnableParallel runnable = RunnableParallel( origin=RunnablePassthrough(), modified=lambda x: x+1 ) runnable.invok...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
6ca47b79a450-2
Union[Callable[[Other], None], Callable[[Other, RunnableConfig], None]] ] = None afunc: Optional[ Union[ Callable[[Other], Awaitable[None]], Callable[[Other, RunnableConfig], Awaitable[None]], ] ] = None def __init__( self, func: Optional[ ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
6ca47b79a450-3
**kwargs: Union[ Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any], Mapping[ str, Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]], ], ], ) -> RunnableAssign: """Merge the Dict input wit...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
6ca47b79a450-4
**kwargs: Any, ) -> Iterator[Other]: if self.func is None: for chunk in self._transform_stream_with_config(input, identity, config): yield chunk else: final = None for chunk in self._transform_stream_with_config(input, identity, config): ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
6ca47b79a450-5
**kwargs: Any, ) -> Iterator[Other]: return self.transform(iter([input]), config, **kwargs) [docs] async def astream( self, input: Other, config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> AsyncIterator[Other]: async def input_aiter() -> AsyncIterator...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
6ca47b79a450-6
map_input_schema = self.mapper.get_input_schema(config) map_output_schema = self.mapper.get_output_schema(config) if ( not map_input_schema.__custom_root_type__ and not map_output_schema.__custom_root_type__ ): # ie. both are dicts return create_mo...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
6ca47b79a450-7
return { **input, **await self.mapper.ainvoke(input, config, **kwargs), } [docs] def transform( self, input: Iterator[Dict[str, Any]], config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> Iterator[Dict[str, Any]]: # collect mapper ke...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
6ca47b79a450-8
config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> AsyncIterator[Dict[str, Any]]: # collect mapper keys mapper_keys = set(self.mapper.steps.keys()) # create two streams, one for the map and one for the passthrough for_passthrough, for_map = atee(input, 2, lock=async...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
6ca47b79a450-9
config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> AsyncIterator[Dict[str, Any]]: async def input_aiter() -> AsyncIterator[Dict[str, Any]]: yield input async for chunk in self.atransform(input_aiter(), config, **kwargs): yield chunk
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/passthrough.html
c902d3a2c232-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
c902d3a2c232-1
runnable = RunnableLambda(foo) runnable_with_retries = runnable.with_retry( retry_exception_types=(ValueError,), # Retry only on ValueError wait_exponential_jitter=True, # Add jitter to the exponential backoff max_attempt_number=2, # Try twice ) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
c902d3a2c232-2
errors (4xx) such as 429 Too Many Requests. """ wait_exponential_jitter: bool = True """Whether to add jitter to the exponential backoff.""" max_attempt_number: int = 3 """The maximum number of attempts to retry the runnable.""" @property def _kwargs_retrying(self) -> Dict[str, Any]: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
c902d3a2c232-3
) -> List[RunnableConfig]: return [ self._patch_config(c, rm, retry_state) for c, rm in zip(config, run_manager) ] def _invoke( self, input: Input, run_manager: "CallbackManagerForChainRun", config: RunnableConfig, **kwargs: Any, ) -> Output: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
c902d3a2c232-4
) -> Output: return await self._acall_with_config(self._ainvoke, input, config, **kwargs) def _batch( self, inputs: List[Input], run_manager: List["CallbackManagerForChainRun"], config: List[RunnableConfig], **kwargs: Any, ) -> List[Union[Output, Exception]]: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
c902d3a2c232-5
outputs: List[Union[Output, Exception]] = [] for idx, _ in enumerate(inputs): if idx in results_map: outputs.append(results_map[idx]) else: outputs.append(result.pop(0)) return outputs [docs] def batch( self, inputs: List[Input],...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
c902d3a2c232-6
if isinstance(r, Exception): if not first_exception: first_exception = r continue results_map[i] = r # If any exception occurred, raise it, to retry the failed ones if ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/retry.html
053cd908fd61-0
Source code for langchain.schema.runnable.configurable from __future__ import annotations import enum import threading from abc import abstractmethod from typing import ( Any, AsyncIterator, Callable, Dict, Iterator, List, Optional, Sequence, Type, Union, cast, ) from weakref...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html
053cd908fd61-1
) -> Type[BaseModel]: return self._prepare(config).get_input_schema(config) [docs] def get_output_schema( self, config: Optional[RunnableConfig] = None ) -> Type[BaseModel]: return self._prepare(config).get_output_schema(config) @abstractmethod def _prepare( self, config: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html
053cd908fd61-2
input: Input, config: RunnableConfig, ) -> Union[Output, Exception]: if return_exceptions: try: return bound.invoke(input, config, **kwargs) except Exception as e: return e else: return bo...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html
053cd908fd61-3
except Exception as e: return e else: return await bound.ainvoke(input, config, **kwargs) coros = map(ainvoke, prepared, inputs, configs) return await gather_with_concurrency(configs[0].get("max_concurrency"), *coros) [docs] def stream( self, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html
053cd908fd61-4
fields: Dict[str, AnyConfigurableField] @property def config_specs(self) -> List[ConfigurableFieldSpec]: return get_unique_config_specs( [ ConfigurableFieldSpec( id=spec.id, name=spec.name, description=spec.descripti...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html
053cd908fd61-5
if isinstance(v, ConfigurableFieldSingleOption) } configurable_multi_options = { k: [ v.options[o] for o in config.get("configurable", {}).get(v.id, v.default) ] for k, v in self.fields.items() if isinstance(v, ConfigurableF...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html
053cd908fd61-6
self.which.name or self.which.id, ( (v, v) for v in list(self.alternatives.keys()) + [self.default_key] ), ) _enums_for_spec[self.which] = cast(Type[StrEnum], which_enum) return [ ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html
053cd908fd61-7
description: Optional[str], ) -> ConfigurableFieldSpec: """Make a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or ConfigurableFieldMultiOption.""" with _enums_for_spec_lock: if enum := _enums_for_spec.get(spec): pass else: enum = StrEnum( # type: ignore[...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/configurable.html
7cd2723fa80e-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
7cd2723fa80e-1
AnyConfigurableField, ConfigurableField, ConfigurableFieldSpec, Input, Output, accepts_config, accepts_run_manager, gather_with_concurrency, get_function_first_arg_dict_keys, get_lambda_source, get_unique_config_specs, indent_lines_after_first, ) from langchain.utils.aiter im...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
7cd2723fa80e-2
into chains. Any chain constructed this way will automatically have sync, async, batch, and streaming support. The main composition primitives are RunnableSequence and RunnableParallel. RunnableSequence invokes a series of runnables sequentially, with one runnable's output serving as the next's input. C...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
7cd2723fa80e-3
For example, .. code-block:: python from langchain.schema.runnable import RunnableLambda import random def add_one(x: int) -> int: return x + 1 def buggy_double(y: int) -> int: '''Buggy code that will fail 70% of the time''' if random.random() > 0....
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
7cd2723fa80e-4
""" @property def InputType(self) -> Type[Input]: """The type of input this runnable accepts specified as a type annotation.""" for cls in self.__class__.__orig_bases__: # type: ignore[attr-defined] type_args = get_args(cls) if type_args and len(type_args) == 2: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
7cd2723fa80e-5
configuration the runnable is invoked with. This method allows to get an input schema for a specific configuration. Args: config: A config to use when generating the schema. Returns: A pydantic model that can be used to validate input. """ root_type = self...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
7cd2723fa80e-6
"""List configurable fields for this runnable.""" return [] [docs] def config_schema( self, *, include: Optional[Sequence[str]] = None ) -> Type[BaseModel]: """The type of config this runnable accepts specified as a pydantic model. To mark a field as configurable, see the `configu...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
7cd2723fa80e-7
Runnable[Any, Other], Callable[[Any], Other], Callable[[Iterator[Any]], Iterator[Other]], Mapping[str, Union[Runnable[Any, Other], Callable[[Any], Other], Any]], ], ) -> RunnableSerializable[Input, Other]: """Compose this runnable with another object to create a R...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
7cd2723fa80e-8
) -> Output: """Default implementation of ainvoke, calls invoke from a thread. The default implementation allows usage of async code even if the runnable did not implement a native async version of invoke. Subclasses should override this method if they can run asynchronously. """...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html
7cd2723fa80e-9
return cast(List[Output], list(executor.map(invoke, inputs, configs))) [docs] async def abatch( self, inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any], ) -> List[O...
lang/api.python.langchain.com/en/latest/_modules/langchain/schema/runnable/base.html