id
stringlengths
14
15
text
stringlengths
35
2.51k
source
stringlengths
61
154
516ae6354a29-3
[docs] def close(self) -> None: self.logger.close() diagnostic_logger.info("Closing WhyLabs logger, see you next time!") def __enter__(self) -> WhyLabsCallbackHandler: return self def __exit__( self, exception_type: Any, exception_value: Any, traceback: Any ) -> None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
516ae6354a29-4
metric. """ # langkit library will import necessary whylogs libraries import_langkit(sentiment=sentiment, toxicity=toxicity, themes=themes) import whylogs as why from whylogs.api.writer.whylabs import WhyLabsWriter from whylogs.core.schema import DeclarativeSchema ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
f60492ebc90d-0
Source code for langchain.callbacks.argilla_callback import os import warnings from typing import Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult [docs]class ArgillaCallbackHandler(BaseCallbackHandler): """Cal...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
f60492ebc90d-1
>>> argilla_callback = ArgillaCallbackHandler( ... dataset_name="my-dataset", ... workspace_name="my-workspace", ... api_url="http://localhost:6900", ... api_key="argilla.apikey", ... ) >>> llm = OpenAI( ... temperature=0, ... callb...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
f60492ebc90d-2
`FeedbackDataset` lives in. Defaults to `None`, which means that either `ARGILLA_API_URL` environment variable or the default http://localhost:6900 will be used. api_key: API Key to connect to the Argilla Server. Defaults to `None`, which means that either `AR...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
f60492ebc90d-3
" set, it will default to `argilla.apikey`." ), ) # Connect to Argilla with the provided credentials, if applicable try: rg.init( api_key=api_key, api_url=api_url, ) except Exception as e: raise Conne...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
f60492ebc90d-4
" If the problem persists please report it to" " https://github.com/argilla-io/argilla/issues with the label" " `langchain`." ) from e supported_fields = ["prompt", "response"] if supported_fields != [field.name for field in self.dataset.fields]: r...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
f60492ebc90d-5
[docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None: """Do nothing when a new token is generated.""" pass [docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Log records to Argilla when an LLM ends.""" # Do nothing if there's a parent_run_id...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
f60492ebc90d-6
we don't log the same input prompt twice, once when the LLM starts and once when the chain starts. """ if "input" in inputs: self.prompts.update( { str(kwargs["parent_run_id"] or kwargs["run_id"]): ( inputs["input"] ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
f60492ebc90d-7
self.dataset.add_records( records=[ { "fields": { "prompt": " ".join(prompts), # type: ignore "response": chain_output_val.strip(), }, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
f60492ebc90d-8
) -> None: """Do nothing when tool outputs an error.""" pass [docs] def on_text(self, text: str, **kwargs: Any) -> None: """Do nothing""" pass [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Do nothing""" pass
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
3e71cfcbed2d-0
Source code for langchain.callbacks.wandb_callback import json import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.utils import ( BaseMetadataCallbackHandler...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-1
Parameters: text (str): The text to analyze. complexity_metrics (bool): Whether to compute complexity metrics. visualize (bool): Whether to visualize the text. nlp (spacy.lang): The spacy language model to use for visualization. output_dir (str): The directory to save the visuali...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-2
"gutierrez_polini": textstat.gutierrez_polini(text), "crawford": textstat.crawford(text), "gulpease_index": textstat.gulpease_index(text), "osman": textstat.osman(text), } resp.update(text_complexity_metrics) if visualize and nlp and output_dir is not None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-3
formatted_prompt = prompt.replace("\n", "<br>") formatted_generation = generation.replace("\n", "<br>") return wandb.Html( f""" <p style="color:black;">{formatted_prompt}:</p> <blockquote> <p style="color:green;"> {formatted_generation} </p> </blockquote> """, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-4
group: Optional[str] = None, name: Optional[str] = None, notes: Optional[str] = None, visualize: bool = False, complexity_metrics: bool = False, stream_logs: bool = False, ) -> None: """Initialize callback handler.""" wandb = import_wandb() import_pand...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-5
def _init_resp(self) -> Dict: return {k: None for k in self.callback_columns} [docs] def on_llm_start( self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any ) -> None: """Run when LLM starts.""" self.step += 1 self.llm_starts += 1 self.starts += 1 ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-6
self.ends += 1 resp = self._init_resp() resp.update({"action": "on_llm_end"}) resp.update(flatten_dict(response.llm_output or {})) resp.update(self.get_custom_callback_meta()) for generations in response.generations: for generation in generations: gene...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-7
self.on_chain_start_records.append(input_resp) self.action_records.append(input_resp) if self.stream_logs: self.run.log(input_resp) elif isinstance(chain_input, list): for inp in chain_input: input_resp = deepcopy(resp) input_re...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-8
resp.update({"action": "on_tool_start", "input_str": input_str}) resp.update(flatten_dict(serialized)) resp.update(self.get_custom_callback_meta()) self.on_tool_start_records.append(resp) self.action_records.append(resp) if self.stream_logs: self.run.log(resp) [docs] ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-9
"""Run when agent ends running.""" self.step += 1 self.agent_ends += 1 self.ends += 1 resp = self._init_resp() resp.update( { "action": "on_agent_finish", "output": finish.return_values["output"], "log": finish.log, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-10
.dropna(axis=1) .rename({"step": "prompt_step"}, axis=1) ) complexity_metrics_columns = [] visualizations_columns = [] if self.complexity_metrics: complexity_metrics_columns = [ "flesch_reading_ease", "flesch_kincaid_grade", ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-11
row["prompts"], row["output"] ), axis=1, ) return session_analysis_df [docs] def flush_tracker( self, langchain_asset: Any = None, reset: bool = True, finish: bool = False, job_type: Optional[str] = None, project: Optional[str] =...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
3e71cfcbed2d-12
} ) if langchain_asset: langchain_asset_path = Path(self.temp_dir.name, "model.json") model_artifact = wandb.Artifact(name="model", type="model") model_artifact.add(action_records_table, name="action_records") model_artifact.add(session_analysis_table, nam...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
7905a485ac3e-0
Source code for langchain.callbacks.manager from __future__ import annotations import asyncio import functools import logging import os import warnings from contextlib import asynccontextmanager, contextmanager from contextvars import ContextVar from typing import ( Any, AsyncGenerator, Dict, Generator,...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-1
"tracing_callback", default=None ) wandb_tracing_callback_var: ContextVar[ Optional[WandbTracer] ] = ContextVar( # noqa: E501 "tracing_wandb_callback", default=None ) tracing_v2_callback_var: ContextVar[ Optional[LangChainTracer] ] = ContextVar( # noqa: E501 "tracing_callback_v2", default=None ) def _...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-2
""" cb = LangChainTracerV1() session = cast(TracerSessionV1, cb.load_session(session_name)) tracing_callback_var.set(cb) yield session tracing_callback_var.set(None) [docs]@contextmanager def wandb_tracing_enabled( session_name: str = "default", ) -> Generator[None, None, None]: """Get the W...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-3
"This is not yet stable and may change in the future." ) if isinstance(example_id, str): example_id = UUID(example_id) cb = LangChainTracer( example_id=example_id, project_name=project_name, ) tracing_v2_callback_var.set(cb) yield tracing_v2_callback_var.set(None) [do...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-4
) cm = CallbackManager.configure( inheritable_callbacks=[cb], inheritable_tags=tags, ) run_manager = cm.on_chain_start({"name": group_name}, {}) yield run_manager.get_child() run_manager.on_chain_end({}) @asynccontextmanager async def atrace_as_chain_group( group_name: str, *...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-5
inheritable_callbacks=[cb], inheritable_tags=tags ) run_manager = await cm.on_chain_start({"name": group_name}, {}) try: yield run_manager.get_child() finally: await run_manager.on_chain_end({}) def _handle_event( handlers: List[BaseCallbackHandler], event_name: str, ignore_c...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-6
ignore_condition_name: Optional[str], *args: Any, **kwargs: Any, ) -> None: try: if ignore_condition_name is None or not getattr(handler, ignore_condition_name): event = getattr(handler, event_name) if asyncio.iscoroutinefunction(event): await event(*args, **k...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-7
await _ahandle_event_for_handler( handler, event_name, ignore_condition_name, *args, **kwargs ) await asyncio.gather( *( _ahandle_event_for_handler( handler, event_name, ignore_condition_name, *args, **kwargs ) for handler in handlers ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-8
self.inheritable_tags = inheritable_tags or [] [docs] @classmethod def get_noop_manager(cls: Type[BRM]) -> BRM: """Return a manager that doesn't perform any operations. Returns: BaseRunManager: The noop manager. """ return cls( run_id=uuid4(), h...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-9
parent_run_id=self.parent_run_id, **kwargs, ) [docs]class CallbackManagerForLLMRun(RunManager, LLMManagerMixin): """Callback manager for LLM run.""" [docs] def on_llm_new_token( self, token: str, **kwargs: Any, ) -> None: """Run when LLM generates a new tok...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-10
run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) [docs]class AsyncCallbackManagerForLLMRun(AsyncRunManager, LLMManagerMixin): """Async callback manager for LLM run.""" [docs] async def on_llm_new_token( self, token: str, **kwargs: Any, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-11
"on_llm_error", "ignore_llm", error, run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) [docs]class CallbackManagerForChainRun(RunManager, ChainManagerMixin): """Callback manager for chain run.""" [docs] def get_child(self, tag: O...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-12
_handle_event( self.handlers, "on_chain_error", "ignore_chain", error, run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) [docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any: """...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-13
Returns: AsyncCallbackManager: The child callback manager. """ manager = AsyncCallbackManager(handlers=[], parent_run_id=self.run_id) manager.set_handlers(self.inheritable_handlers) manager.add_tags(self.inheritable_tags) if tag is not None: manager.add_ta...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-14
await _ahandle_event( self.handlers, "on_agent_action", "ignore_agent", action, run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) [docs] async def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> A...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-15
Args: output (str): The output of the tool. """ _handle_event( self.handlers, "on_tool_end", "ignore_agent", output, run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) [docs] def on_...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-16
"""Run when tool ends running. Args: output (str): The output of the tool. """ await _ahandle_event( self.handlers, "on_tool_end", "ignore_agent", output, run_id=self.run_id, parent_run_id=self.parent_run_id, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-17
"on_retriever_end", "ignore_retriever", documents, run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) [docs] def on_retriever_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any, ) -> Non...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-18
) [docs] async def on_retriever_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any, ) -> None: """Run when retriever errors.""" await _ahandle_event( self.handlers, "on_retriever_error", "ignore_retriever", ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-19
run_id=run_id_, handlers=self.handlers, inheritable_handlers=self.inheritable_handlers, parent_run_id=self.parent_run_id, tags=self.tags, inheritable_tags=self.inheritable_tags, ) ) re...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-20
return managers [docs] def on_chain_start( self, serialized: Dict[str, Any], inputs: Dict[str, Any], run_id: Optional[UUID] = None, **kwargs: Any, ) -> CallbackManagerForChainRun: """Run when chain starts running. Args: serialized (Dict[str, Any...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-21
Args: serialized (Dict[str, Any]): The serialized tool. input_str (str): The input to the tool. run_id (UUID, optional): The ID of the run. Defaults to None. parent_run_id (UUID, optional): The ID of the parent run. Defaults to None. Returns: CallbackM...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-22
**kwargs, ) return CallbackManagerForRetrieverRun( run_id=run_id, handlers=self.handlers, inheritable_handlers=self.inheritable_handlers, parent_run_id=self.parent_run_id, tags=self.tags, inheritable_tags=self.inheritable_tags, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-23
return True [docs] async def on_llm_start( self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any, ) -> List[AsyncCallbackManagerForLLMRun]: """Run when LLM starts running. Args: serialized (Dict[str, Any]): The serialized LLM. ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-24
**kwargs: Any, ) -> Any: """Run when LLM starts running. Args: serialized (Dict[str, Any]): The serialized LLM. messages (List[List[BaseMessage]]): The list of messages. run_id (UUID, optional): The ID of the run. Defaults to None. Returns: Lis...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-25
Args: serialized (Dict[str, Any]): The serialized chain. inputs (Dict[str, Any]): The inputs to the chain. run_id (UUID, optional): The ID of the run. Defaults to None. Returns: AsyncCallbackManagerForChainRun: The async callback manager for the ch...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-26
AsyncCallbackManagerForToolRun: The async callback manager for the tool run. """ if run_id is None: run_id = uuid4() await _ahandle_event( self.handlers, "on_tool_start", "ignore_agent", serialized, input_str...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-27
) [docs] @classmethod def configure( cls, inheritable_callbacks: Callbacks = None, local_callbacks: Callbacks = None, verbose: bool = False, inheritable_tags: Optional[List[str]] = None, local_tags: Optional[List[str]] = None, ) -> AsyncCallbackManager: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-28
) def _configure( callback_manager_cls: Type[T], inheritable_callbacks: Callbacks = None, local_callbacks: Callbacks = None, verbose: bool = False, inheritable_tags: Optional[List[str]] = None, local_tags: Optional[List[str]] = None, ) -> T: """Configure the callback manager. Args: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-29
) local_handlers_ = ( local_callbacks if isinstance(local_callbacks, list) else (local_callbacks.handlers if local_callbacks else []) ) for handler in local_handlers_: callback_manager.add_handler(handler, False) if inheritable_tags or local_ta...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
7905a485ac3e-30
if debug and not any( isinstance(handler, ConsoleCallbackHandler) for handler in callback_manager.handlers ): callback_manager.add_handler(ConsoleCallbackHandler(), True) if tracing_enabled_ and not any( isinstance(handler, LangChainTracerV1) f...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
2ec9424c0c25-0
Source code for langchain.callbacks.streamlit.__init__ from __future__ import annotations from typing import TYPE_CHECKING, Optional from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.streamlit.streamlit_callback_handler import ( LLMThoughtLabeler as LLMThoughtLabeler, ) from langchai...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/__init__.html
2ec9424c0c25-1
If True, LLM thought expanders will be collapsed when completed. Defaults to True. thought_labeler An optional custom LLMThoughtLabeler instance. If unspecified, the handler will use the default thought labeling logic. Defaults to None. Returns ------- A new StreamlitCallbackHand...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/__init__.html
294311aef711-0
Source code for langchain.callbacks.streamlit.streamlit_callback_handler """Callback Handler that prints to streamlit.""" from __future__ import annotations from enum import Enum from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
294311aef711-1
"""Return the markdown label for a new LLMThought that doesn't have an associated tool yet. """ return f"{THINKING_EMOJI} **Thinking...**" def get_tool_label(self, tool: ToolRecord, is_complete: bool) -> str: """Return the label for an LLMThought that has an associated tool. ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
294311aef711-2
class LLMThought: def __init__( self, parent_container: DeltaGenerator, labeler: LLMThoughtLabeler, expanded: bool, collapse_on_complete: bool, ): self._container = MutableExpander( parent_container=parent_container, label=labeler.get_initi...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
294311aef711-3
self._llm_token_stream, index=self._llm_token_writer_idx ) def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: # `response` is the concatenation of all the tokens received by the LLM. # If we're receiving streaming tokens from `on_llm_new_token`, this response # data is...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
294311aef711-4
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: self._container.markdown("**Tool encountered an error...**") self._container.exception(error) def on_agent_action( self, action: AgentAction, color: Optional[str] = None, **kwargs: Any ) -> Any: # Call...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
294311aef711-5
*, max_thought_containers: int = 4, expand_new_thoughts: bool = True, collapse_completed_thoughts: bool = True, thought_labeler: Optional[LLMThoughtLabeler] = None, ): """Create a StreamlitCallbackHandler instance. Parameters ---------- parent_containe...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
294311aef711-6
self._collapse_completed_thoughts = collapse_completed_thoughts self._thought_labeler = thought_labeler or LLMThoughtLabeler() def _require_current_thought(self) -> LLMThought: """Return our current LLMThought. Raise an error if we have no current thought. """ if self._curren...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
294311aef711-7
self._current_thought = None def _prune_old_thought_containers(self) -> None: """If we have too many thoughts onscreen, move older thoughts to the 'history container.' """ while ( self._num_thought_containers > self._max_thought_containers and len(self._comple...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
294311aef711-8
) self._current_thought.on_llm_start(serialized, prompts) # We don't prune_old_thought_containers here, because our container won't # be visible until it has a child. [docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None: self._require_current_thought().on_llm_new_token...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
294311aef711-9
) self._complete_current_thought() [docs] def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: self._require_current_thought().on_tool_error(error, **kwargs) self._prune_old_thought_containers() [docs] def on_text( self, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
76a12c5b3342-0
Source code for langchain.callbacks.streamlit.mutable_expander from __future__ import annotations from enum import Enum from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional if TYPE_CHECKING: from streamlit.delta_generator import DeltaGenerator from streamlit.type_util import SupportsStr [docs...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html
76a12c5b3342-1
return self._label @property def expanded(self) -> bool: """True if the expander was created with `expanded=True`.""" return self._expanded def clear(self) -> None: """Remove the container and its contents entirely. A cleared container can't be reused. """ sel...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html
76a12c5b3342-2
*, help: Optional[str] = None, index: Optional[int] = None, ) -> int: """Add a Markdown element to the container and return its index.""" kwargs = {"body": body, "unsafe_allow_html": unsafe_allow_html, "help": help} new_dg = self._get_dg(index).markdown(**kwargs) # type: ign...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html
76a12c5b3342-3
""" if index is not None: # Replace existing child self._child_records[index] = record return index # Append new child self._child_records.append(record) return len(self._child_records) - 1 def _get_dg(self, index: Optional[int]) -> DeltaGenerator:...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html
59a8dbc5a368-0
Source code for langchain.callbacks.tracers.wandb """A Tracer Implementation that records activity to Weights & Biases.""" from __future__ import annotations from typing import ( TYPE_CHECKING, Any, Dict, List, Optional, Sequence, TypedDict, Union, ) from langchain.callbacks.tracers.base...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
59a8dbc5a368-1
} if ( run.outputs is not None and len(run.outputs["generations"]) > ndx and len(run.outputs["generations"][ndx]) > 0 ) else None, ) for ndx, prompt in enumerate(run.inputs["prompts"] or []) ] base_span.span_kind...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
59a8dbc5a368-2
_convert_lc_run_to_wb_span(trace_tree, child_run) for child_run in run.child_runs ] base_span.span_kind = trace_tree.SpanKind.TOOL return base_span def _convert_run_to_wb_span(trace_tree: Any, run: Run) -> trace_tree.Span: attributes = {**run.extra} if run.extra else {} attributes["execution...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
59a8dbc5a368-3
return data [docs]class WandbRunArgs(TypedDict): """Arguments for the WandbTracer.""" job_type: Optional[str] dir: Optional[StrPath] config: Union[Dict, str, None] project: Optional[str] entity: Optional[str] reinit: Optional[bool] tags: Optional[Sequence] group: Optional[str] na...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
59a8dbc5a368-4
"""Initializes the WandbTracer. Parameters: run_args: (dict, optional) Arguments to pass to `wandb.init()`. If not provided, `wandb.init()` will be called with no arguments. Please refer to the `wandb.init` for more details. To use W&B to monitor all LangChain...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
59a8dbc5a368-5
except Exception as e: if PRINT_WARNINGS: self._wandb.termwarn( f"Skipping trace saving - unable to safely convert LangChain Run " f"into W&B Trace due to: {e}" ) return model_dict = None # TODO: Add somethin...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
59a8dbc5a368-6
self._wandb.init(**run_args) if self._wandb.run is not None: if should_print_url: run_url = self._wandb.run.settings.run_url self._wandb.termlog( f"Streaming LangChain activity to W&B at {run_url}\n" "`Wa...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
025c502df5cd-0
Source code for langchain.callbacks.tracers.langchain_v1 from __future__ import annotations import logging import os from typing import Any, Dict, Optional, Union import requests from langchain.callbacks.tracers.base import BaseTracer from langchain.callbacks.tracers.schemas import ( ChainRun, LLMRun, Run, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain_v1.html
025c502df5cd-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"...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain_v1.html
025c502df5cd-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain_v1.html
025c502df5cd-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}...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain_v1.html
025c502df5cd-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 logging.warning( f"Failed to load {session_type} session, using empty session: {e...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain_v1.html
f2ec6415f7a8-0
Source code for langchain.callbacks.tracers.langchain """A Tracer implementation that records to LangChain endpoint.""" from __future__ import annotations import logging import os from concurrent.futures import Future, ThreadPoolExecutor, wait from datetime import datetime from typing import Any, Dict, List, Optional, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html
f2ec6415f7a8-1
"""Initialize the LangChain tracer.""" super().__init__(**kwargs) self.session: Optional[TracerSession] = None self.example_id = ( UUID(example_id) if isinstance(example_id, str) else example_id ) self.project_name = project_name or os.getenv( "LANGCHAIN_P...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html
f2ec6415f7a8-2
tags=tags, ) self._start_trace(chat_model_run) self._on_chat_model_start(chat_model_run) def _persist_run(self, run: Run) -> None: """The Langchain Tracer uses Post/Patch rather than persist.""" def _persist_run_single(self, run: Run) -> None: """Persist a run.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html
f2ec6415f7a8-3
self.executor.submit(self._persist_run_single, run.copy(deep=True)) ) def _on_llm_end(self, run: Run) -> None: """Process the LLM Run.""" self._futures.add( self.executor.submit(self._update_run_single, run.copy(deep=True)) ) def _on_llm_error(self, run: Run) -> None:...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html
f2ec6415f7a8-4
self.executor.submit(self._update_run_single, run.copy(deep=True)) ) def _on_tool_error(self, run: Run) -> None: """Process the Tool Run upon error.""" self._futures.add( self.executor.submit(self._update_run_single, run.copy(deep=True)) ) def _on_retriever_start(self...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html
f1ad553c8766-0
Source code for langchain.callbacks.tracers.stdout import json from typing import Any, List from langchain.callbacks.tracers.base import BaseTracer from langchain.callbacks.tracers.schemas import Run from langchain.input import get_bolded_text, get_colored_text [docs]def try_json_stringify(obj: Any, fallback: str) -> s...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html
f1ad553c8766-1
parents = [] current_run = run while current_run.parent_run_id: parent = self.run_map.get(str(current_run.parent_run_id)) if parent: parents.append(parent) current_run = parent else: break return parents [docs] ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html
f1ad553c8766-2
crumbs = self.get_breadcrumbs(run) print( f"{get_colored_text('[chain/error]', color='red')} " + get_bolded_text( f"[{crumbs}] [{elapsed(run)}] Chain run errored with error:\n" ) + f"{try_json_stringify(run.error, '[error]')}" ) def _on...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html
f1ad553c8766-3
) + f"{try_json_stringify(run.error, '[error]')}" ) def _on_tool_start(self, run: Run) -> None: crumbs = self.get_breadcrumbs(run) print( f'{get_colored_text("[tool/start]", color="green")} ' + get_bolded_text(f"[{crumbs}] Entering Tool run with input:\n")...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html
17ae60e04238-0
Source code for langchain.callbacks.tracers.schemas """Schemas for tracers.""" from __future__ import annotations import datetime from typing import Any, Dict, List, Optional from uuid import UUID from langchainplus_sdk.schemas import RunBase as BaseRunV2 from langchainplus_sdk.schemas import RunTypeEnum from pydantic ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/schemas.html
17ae60e04238-1
session_id: int error: Optional[str] = None [docs]class LLMRun(BaseRun): """Class for LLMRun.""" prompts: List[str] response: Optional[LLMResult] = None [docs]class ChainRun(BaseRun): """Class for ChainRun.""" inputs: Dict[str, Any] outputs: Optional[Dict[str, Any]] = None child_llm_runs...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/schemas.html
17ae60e04238-2
elif "id" in values["serialized"]: values["name"] = values["serialized"]["id"][-1] return values ChainRun.update_forward_refs() ToolRun.update_forward_refs() __all__ = [ "BaseRun", "ChainRun", "LLMRun", "Run", "RunTypeEnum", "ToolRun", "TracerSession", "TracerSess...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/schemas.html
10dc825dcabd-0
Source code for langchain.callbacks.tracers.evaluation """A tracer that runs evaluators over completed runs.""" from concurrent.futures import Future, ThreadPoolExecutor, wait from typing import Any, Optional, Sequence, Set, Union from uuid import UUID from langchainplus_sdk import LangChainPlusClient, RunEvaluator fro...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/evaluation.html
10dc825dcabd-1
def __init__( self, evaluators: Sequence[RunEvaluator], max_workers: Optional[int] = None, client: Optional[LangChainPlusClient] = None, example_id: Optional[Union[UUID, str]] = None, **kwargs: Any ) -> None: super().__init__(**kwargs) self.example_id ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/evaluation.html
582e0941f8e0-0
Source code for langchain.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 from uuid import UUID from langchain.callbacks.base i...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html
582e0941f8e0-1
"""End a trace for a run.""" if not run.parent_run_id: self._persist_run(run) else: parent_run = self.run_map.get(str(run.parent_run_id)) if parent_run is None: logger.warning(f"Parent run with UUID {run.parent_run_id} not found.") elif ( ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html
582e0941f8e0-2
execution_order = self._get_execution_order(parent_run_id_) llm_run = Run( id=run_id, parent_run_id=parent_run_id, serialized=serialized, inputs={"prompts": prompts}, extra=kwargs, start_time=datetime.utcnow(), execution_order=e...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html