id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
e13a71a3d9d2-6 | """Run when chain ends running."""
aim = import_aim()
self.step += 1
self.chain_ends += 1
self.ends += 1
resp = {"action": "on_chain_end"}
resp.update(self.get_custom_callback_meta())
outputs_res = deepcopy(outputs)
self._run.track(
aim.Text(ou... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
e13a71a3d9d2-7 | [docs] def on_tool_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Run when tool errors."""
self.step += 1
self.errors += 1
[docs] def on_text(self, text: str, **kwargs: Any) -> None:
"""
Run when agent is ending.
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
e13a71a3d9d2-8 | action_res.tool_input, action_res.log
)
self._run.track(aim.Text(text), name="on_agent_action", context=resp)
[docs] def flush_tracker(
self,
repo: Optional[str] = None,
experiment_name: Optional[str] = None,
system_tracking_interval: Optional[int] = 10,
log_sy... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
e13a71a3d9d2-9 | self._run.close()
self.reset_callback_meta()
if reset:
self.__init__( # type: ignore
repo=repo if repo else self.repo,
experiment_name=experiment_name
if experiment_name
else self.experiment_name,
system_tra... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
303b763cae62-0 | Source code for langchain.callbacks.whylabs_callback
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Optional
from langchain.callbacks.base import BaseCallbackHandler
from langchain.utils import get_from_env
if TYPE_CHECKING:
from whylogs.api.logger.logger import Logger
diag... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
303b763cae62-1 | """
Callback Handler for logging to WhyLabs. This callback handler utilizes
`langkit` to extract features from the prompts & responses when interacting with
an LLM. These features can be used to guardrail, evaluate, and observe interactions
over time to detect issues relating to hallucinations, prompt e... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
303b763cae62-2 | Optional because the preferred way to specify the dataset id is
with environment variable WHYLABS_DEFAULT_DATASET_ID.
sentiment (bool): Whether to enable sentiment analysis. Defaults to False.
toxicity (bool): Whether to enable toxicity analysis. Defaults to False.
themes (bool): Whe... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
303b763cae62-3 | [docs] @classmethod
def from_params(
cls,
*,
api_key: Optional[str] = None,
org_id: Optional[str] = None,
dataset_id: Optional[str] = None,
sentiment: bool = False,
toxicity: bool = False,
themes: bool = False,
logger: Optional[Logger] = Non... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
303b763cae62-4 | import whylogs as why
from langkit.callback_handler import get_callback_instance
from whylogs.api.writer.whylabs import WhyLabsWriter
from whylogs.experimental.core.udf_schema import udf_schema
if logger is None:
api_key = api_key or get_from_env("api_key", "WHYLABS_API_KEY")... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
0fc2f64e89e9-0 | Source code for langchain.callbacks.flyte_callback
"""FlyteKit callback handler."""
from __future__ import annotations
import logging
from copy import deepcopy
from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union
from langchain.callbacks.base import BaseCallbackHandler
from langchain.callbacks.utils import (... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
0fc2f64e89e9-1 | Returns:
(dict): A dictionary containing the complexity metrics and visualization
files serialized to HTML string.
"""
resp: Dict[str, Any] = {}
if textstat is not None:
text_complexity_metrics = {
"flesch_reading_ease": textstat.flesch_reading_ease(text),
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
0fc2f64e89e9-2 | dep_out = spacy.displacy.render( # type: ignore
doc, style="dep", jupyter=False, page=True
)
ent_out = spacy.displacy.render( # type: ignore
doc, style="ent", jupyter=False, page=True
)
text_visualizations = {
"dependency_tree": dep_out,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
0fc2f64e89e9-3 | " for certain metrics. To download,"
" run the following command in your terminal:"
" `python -m spacy download en_core_web_sm`"
)
self.table_renderer = renderer.TableRenderer
self.markdown_renderer = renderer.MarkdownRenderer
self.deck = f... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
0fc2f64e89e9-4 | self.ends += 1
resp: Dict[str, Any] = {}
resp.update({"action": "on_llm_end"})
resp.update(flatten_dict(response.llm_output or {}))
resp.update(self.get_custom_callback_meta())
self.deck.append(self.markdown_renderer().to_html("### LLM End"))
self.deck.append(self.table_r... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
0fc2f64e89e9-5 | [docs] def on_llm_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Run when LLM errors."""
self.step += 1
self.errors += 1
[docs] def on_chain_start(
self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
) -> Non... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
0fc2f64e89e9-6 | self.deck.append(self.markdown_renderer().to_html("### Chain End"))
self.deck.append(
self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
)
[docs] def on_chain_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Run when... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
0fc2f64e89e9-7 | )
[docs] def on_tool_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Run when tool errors."""
self.step += 1
self.errors += 1
[docs] def on_text(self, text: str, **kwargs: Any) -> None:
"""
Run when agent is ending.
"... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
0fc2f64e89e9-8 | """Run on agent action."""
self.step += 1
self.tool_starts += 1
self.starts += 1
resp: Dict[str, Any] = {}
resp.update(
{
"action": "on_agent_action",
"tool": action.tool,
"tool_input": action.tool_input,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
ab24c895dda3-0 | Source code for langchain.callbacks.file
"""Callback Handler that writes to a file."""
from typing import Any, Dict, Optional, TextIO, cast
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import AgentAction, AgentFinish
from langchain.utils.input import print_text
[docs]class FileCallback... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/file.html |
ab24c895dda3-1 | ) -> Any:
"""Run on agent action."""
print_text(action.log, color=color or self.color, file=self.file)
[docs] def on_tool_end(
self,
output: str,
color: Optional[str] = None,
observation_prefix: Optional[str] = None,
llm_prefix: Optional[str] = None,
**... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/file.html |
f55c67cca186-0 | Source code for langchain.callbacks.comet_ml_callback
import tempfile
from copy import deepcopy
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Union
import langchain
from langchain.callbacks.base import BaseCallbackHandler
from langchain.callbacks.utils import (
BaseMetad... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-1 | "smog_index": textstat.smog_index(text),
"coleman_liau_index": textstat.coleman_liau_index(text),
"automated_readability_index": textstat.automated_readability_index(text),
"dale_chall_readability_score": textstat.dale_chall_readability_score(text),
"difficult_words": textstat.difficult_... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-2 | task_name (str): Name of the comet_ml task
visualize (bool): Whether to visualize the run.
complexity_metrics (bool): Whether to log complexity metrics
stream_logs (bool): Whether to stream callback actions to Comet
This handler will utilize the associated callback method and formats
the... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-3 | self.experiment.set_name(self.name)
warning = (
"The comet_ml callback is currently in beta and is subject to change "
"based on updates to `langchain`. Please report any issues to "
"https://github.com/comet-ml/issue-tracking/issues with the tag "
"`langchain`."
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-4 | """Run when LLM generates a new token."""
self.step += 1
self.llm_streams += 1
resp = self._init_resp()
resp.update({"action": "on_llm_new_token", "token": token})
resp.update(self.get_custom_callback_meta())
self.action_records.append(resp)
[docs] def on_llm_end(self,... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-5 | self._log_text_metrics(output_complexity_metrics, step=self.step)
self._log_text_metrics(output_custom_metrics, step=self.step)
[docs] def on_llm_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Run when LLM errors."""
self.step += 1
sel... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-6 | resp.update({"action": "on_chain_end"})
resp.update(self.get_custom_callback_meta())
for chain_output_key, chain_output_val in outputs.items():
if isinstance(chain_output_val, str):
output_resp = deepcopy(resp)
if self.stream_logs:
self._lo... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-7 | self.tool_ends += 1
self.ends += 1
resp = self._init_resp()
resp.update({"action": "on_tool_end"})
resp.update(self.get_custom_callback_meta())
if self.stream_logs:
self._log_stream(output, resp, self.step)
resp.update({"output": output})
self.action_r... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-8 | resp.update({"output": output})
self.action_records.append(resp)
[docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
"""Run on agent action."""
self.step += 1
self.tool_starts += 1
self.starts += 1
tool = action.tool
tool_input = str(ac... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-9 | """
resp = {}
if self.custom_metrics:
custom_metrics = self.custom_metrics(generation, prompt_idx, gen_idx)
resp.update(custom_metrics)
return resp
[docs] def flush_tracker(
self,
langchain_asset: Any = None,
task_type: Optional[str] = "inferenc... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-10 | visualizations,
complexity_metrics,
custom_metrics,
)
def _log_stream(self, prompt: str, metadata: dict, step: int) -> None:
self.experiment.log_text(prompt, metadata=metadata, step=step)
def _log_model(self, langchain_asset: Any) -> None:
model_parame... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-11 | exc_info=True,
extra={"show_traceback": True},
)
try:
metadata = {"langchain_version": str(langchain.__version__)}
# Log the langchain low-level records as a JSON file directly
self.experiment.log_asset_data(
self.action_records, "l... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-12 | sentence_spans,
style=visualization,
options={"compact": True},
jupyter=False,
page=True,
)
self.experiment.log_asset_data(
html,
name=f... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-13 | visualizations=_visualizations,
complexity_metrics=_complexity_metrics,
custom_metrics=_custom_metrics,
)
self.reset_callback_meta()
self.temp_dir = tempfile.TemporaryDirectory()
def _create_session_analysis_dataframe(self, langchain_asset: Any = None) -> dict:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
f55c67cca186-14 | else:
llm_parameters = langchain_asset.dict()
except Exception:
return {}
return llm_parameters | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
34f5aecfd25a-0 | Source code for langchain.callbacks.clearml_callback
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,
flat... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
34f5aecfd25a-1 | and adds the response to the list of records for both the {method}_records and
action. It then logs the response to the ClearML console.
"""
[docs] def __init__(
self,
task_type: Optional[str] = "inference",
project_name: Optional[str] = "langchain_callback_demo",
tags: Option... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
34f5aecfd25a-2 | )
self.logger.report_text(warning, level=30, print_console=True)
self.callback_columns: list = []
self.action_records: list = []
self.complexity_metrics = complexity_metrics
self.visualize = visualize
self.nlp = spacy.load("en_core_web_sm")
def _init_resp(self) -> Dic... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
34f5aecfd25a-3 | if self.stream_logs:
self.logger.report_text(resp)
[docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
"""Run when LLM ends running."""
self.step += 1
self.llm_ends += 1
self.ends += 1
resp = self._init_resp()
resp.update({"action": "on... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
34f5aecfd25a-4 | chain_input = inputs["input"]
if isinstance(chain_input, str):
input_resp = deepcopy(resp)
input_resp["input"] = chain_input
self.on_chain_start_records.append(input_resp)
self.action_records.append(input_resp)
if self.stream_logs:
self... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
34f5aecfd25a-5 | self.step += 1
self.tool_starts += 1
self.starts += 1
resp = self._init_resp()
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(res... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
34f5aecfd25a-6 | if self.stream_logs:
self.logger.report_text(resp)
[docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
"""Run when agent ends running."""
self.step += 1
self.agent_ends += 1
self.ends += 1
resp = self._init_resp()
resp.update(
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
34f5aecfd25a-7 | """
resp = {}
textstat = import_textstat()
spacy = import_spacy()
if self.complexity_metrics:
text_complexity_metrics = {
"flesch_reading_ease": textstat.flesch_reading_ease(text),
"flesch_kincaid_grade": textstat.flesch_kincaid_grade(text),
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
34f5aecfd25a-8 | dep_out = spacy.displacy.render( # type: ignore
doc, style="dep", jupyter=False, page=True
)
dep_output_path = Path(
self.temp_dir.name, hash_string(f"dep-{text}") + ".html"
)
dep_output_path.open("w", encoding="utf-8").write(dep_out)
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
34f5aecfd25a-9 | "flesch_kincaid_grade",
"smog_index",
"coleman_liau_index",
"automated_readability_index",
"dale_chall_readability_score",
"difficult_words",
"linsear_write_formula",
"gunning_fog",
"text_stan... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
34f5aecfd25a-10 | finish: bool = False,
) -> None:
"""Flush the tracker and setup the session.
Everything after this will be a new table.
Args:
name: Name of the performed session so far so it is identifiable
langchain_asset: The langchain asset to save.
finish: Whether to ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
34f5aecfd25a-11 | )
output_model.update_weights(
weights_filename=str(langchain_asset_path),
auto_delete_file=False,
target_filename=name,
)
except NotImplementedError as e:
print("Could not save model.")
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
6d26820732b7-0 | Source code for langchain.callbacks.manager
from __future__ import annotations
import asyncio
import functools
import logging
import os
import uuid
from contextlib import asynccontextmanager, contextmanager
from contextvars import ContextVar
from typing import (
TYPE_CHECKING,
Any,
AsyncGenerator,
Dict,... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-1 | tracing_callback_var: ContextVar[
Optional[LangChainTracerV1]
] = ContextVar( # noqa: E501
"tracing_callback", default=None
)
wandb_tracing_callback_var: ContextVar[
Optional[WandbTracer]
] = ContextVar( # noqa: E501
"tracing_wandb_callback", default=None
)
tracing_v2_callback_var: ContextVar[
Opt... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-2 | Example:
>>> with tracing_enabled() as session:
... # Use the LangChainTracer session
"""
cb = LangChainTracerV1()
session = cast(TracerSessionV1, cb.load_session(session_name))
tracing_callback_var.set(cb)
yield session
tracing_callback_var.set(None)
[docs]@contextmanager
de... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-3 | Defaults to None.
Returns:
None
Example:
>>> with tracing_v2_enabled():
... # LangChain code will automatically be traced
"""
if isinstance(example_id, str):
example_id = UUID(example_id)
cb = LangChainTracer(
example_id=example_id,
project_name=pr... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-4 | ... llm.predict("Foo", callbacks=manager)
"""
cb = cast(
Callbacks,
[
LangChainTracer(
project_name=project_name,
example_id=example_id,
)
]
if callback_manager is None
else callback_manager,
)
cm = Callb... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-5 | >>> async with atrace_as_chain_group("group_name") as manager:
... # Use the async callback manager for the chain group
... await llm.apredict("Foo", callbacks=manager)
"""
cb = cast(
Callbacks,
[
LangChainTracer(
project_name=project_name,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-6 | **kwargs,
)
else:
logger.warning(
f"NotImplementedError in {handler.__class__.__name__}.{event_name}"
f" callback: {e}"
)
except Exception as e:
logger.warning(
f"Error in {handler.__c... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-7 | )
except Exception as e:
logger.warning(
f"Error in {handler.__class__.__name__}.{event_name} callback: {e}"
)
if handler.raise_error:
raise e
async def _ahandle_event(
handlers: List[BaseCallbackHandler],
event_name: str,
ignore_condition_name: Optional[s... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-8 | ) -> None:
"""Initialize the run manager.
Args:
run_id (UUID): The ID of the run.
handlers (List[BaseCallbackHandler]): The list of handlers.
inheritable_handlers (List[BaseCallbackHandler]):
The list of inheritable handlers.
parent_run_id ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-9 | ) -> Any:
"""Run when text is received.
Args:
text (str): The received text.
Returns:
Any: The result of the callback.
"""
_handle_event(
self.handlers,
"on_text",
None,
text,
run_id=self.run_id,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-10 | [docs] async def on_text(
self,
text: str,
**kwargs: Any,
) -> Any:
"""Run when text is received.
Args:
text (str): The received text.
Returns:
Any: The result of the callback.
"""
await _ahandle_event(
self.handl... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-11 | manager.add_tags([tag], False)
return manager
[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 token.
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-12 | "ignore_llm",
error,
run_id=self.run_id,
parent_run_id=self.parent_run_id,
tags=self.tags,
**kwargs,
)
[docs]class AsyncCallbackManagerForLLMRun(AsyncRunManager, LLMManagerMixin):
"""Async callback manager for LLM run."""
[docs] async def on_llm... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-13 | """
await _ahandle_event(
self.handlers,
"on_llm_error",
"ignore_llm",
error,
run_id=self.run_id,
parent_run_id=self.parent_run_id,
tags=self.tags,
**kwargs,
)
[docs]class CallbackManagerForChainRun(ParentRun... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-14 | Returns:
Any: The result of the callback.
"""
_handle_event(
self.handlers,
"on_agent_action",
"ignore_agent",
action,
run_id=self.run_id,
parent_run_id=self.parent_run_id,
tags=self.tags,
**kwarg... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-15 | ) -> None:
"""Run when chain errors.
Args:
error (Exception or KeyboardInterrupt): The error.
"""
await _ahandle_event(
self.handlers,
"on_chain_error",
"ignore_chain",
error,
run_id=self.run_id,
parent_r... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-16 | [docs] def on_tool_end(
self,
output: str,
**kwargs: Any,
) -> None:
"""Run when tool ends running.
Args:
output (str): The output of the tool.
"""
_handle_event(
self.handlers,
"on_tool_end",
"ignore_agent",
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-17 | **kwargs,
)
[docs] async def on_tool_error(
self,
error: Union[Exception, KeyboardInterrupt],
**kwargs: Any,
) -> None:
"""Run when tool errors.
Args:
error (Exception or KeyboardInterrupt): The error.
"""
await _ahandle_event(
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-18 | tags=self.tags,
**kwargs,
)
[docs]class AsyncCallbackManagerForRetrieverRun(
AsyncParentRunManager,
RetrieverManagerMixin,
):
"""Async callback manager for retriever run."""
[docs] async def on_retriever_end(
self, documents: Sequence[Document], **kwargs: Any
) -> None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-19 | prompts (List[str]): The list of prompts.
run_id (UUID, optional): The ID of the run. Defaults to None.
Returns:
List[CallbackManagerForLLMRun]: A callback manager for each
prompt as an LLM run.
"""
managers = []
for prompt in prompts:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-20 | list of messages as an LLM run.
"""
managers = []
for message_list in messages:
run_id_ = uuid.uuid4()
_handle_event(
self.handlers,
"on_chat_model_start",
"ignore_chat_model",
serialized,
[me... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-21 | "ignore_chain",
serialized,
inputs,
run_id=run_id,
parent_run_id=self.parent_run_id,
tags=self.tags,
metadata=self.metadata,
**kwargs,
)
return CallbackManagerForChainRun(
run_id=run_id,
handlers=... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-22 | tags=self.tags,
metadata=self.metadata,
**kwargs,
)
return CallbackManagerForToolRun(
run_id=run_id,
handlers=self.handlers,
inheritable_handlers=self.inheritable_handlers,
parent_run_id=self.parent_run_id,
tags=self.tag... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-23 | local_callbacks: Callbacks = None,
verbose: bool = False,
inheritable_tags: Optional[List[str]] = None,
local_tags: Optional[List[str]] = None,
inheritable_metadata: Optional[Dict[str, Any]] = None,
local_metadata: Optional[Dict[str, Any]] = None,
) -> CallbackManager:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-24 | 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.
prompts (List[str]): The list of prompts.
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-25 | messages: List[List[BaseMessage]],
**kwargs: Any,
) -> List[AsyncCallbackManagerForLLMRun]:
"""Run when LLM starts running.
Args:
serialized (Dict[str, Any]): The serialized LLM.
messages (List[List[BaseMessage]]): The list of messages.
run_id (UUID, optio... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-26 | run_id: Optional[UUID] = None,
**kwargs: Any,
) -> AsyncCallbackManagerForChainRun:
"""Run when chain starts running.
Args:
serialized (Dict[str, Any]): The serialized chain.
inputs (Dict[str, Any]): The inputs to the chain.
run_id (UUID, optional): The ID... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-27 | 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:
AsyncCallbackManagerForToolRun: The async callback manager
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-28 | "ignore_retriever",
serialized,
query,
run_id=run_id,
parent_run_id=self.parent_run_id,
tags=self.tags,
metadata=self.metadata,
**kwargs,
)
return AsyncCallbackManagerForRetrieverRun(
run_id=run_id,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-29 | metadata. Defaults to None.
local_metadata (Optional[Dict[str, Any]], optional): The local metadata.
Defaults to None.
Returns:
AsyncCallbackManager: The configured async callback manager.
"""
return _configure(
cls,
inheritable_cal... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-30 | Defaults to None.
verbose (bool, optional): Whether to enable verbose mode. Defaults to False.
inheritable_tags (Optional[List[str]], optional): The inheritable tags.
Defaults to None.
local_tags (Optional[List[str]], optional): The local tags. Defaults to None.
inheritable_m... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-31 | callback_manager.add_tags(inheritable_tags or [])
callback_manager.add_tags(local_tags or [], False)
if inheritable_metadata or local_metadata:
callback_manager.add_metadata(inheritable_metadata or {})
callback_manager.add_metadata(local_metadata or {}, False)
tracer = tracing_callback_v... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
6d26820732b7-32 | ):
callback_manager.add_handler(ConsoleCallbackHandler(), True)
if tracing_enabled_ and not any(
isinstance(handler, LangChainTracerV1)
for handler in callback_manager.handlers
):
if tracer:
callback_manager.add_handler(tracer, True)
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html |
95b16aa4a2e4-0 | Source code for langchain.callbacks.streaming_aiter
from __future__ import annotations
import asyncio
from typing import Any, AsyncIterator, Dict, List, Literal, Union, cast
from langchain.callbacks.base import AsyncCallbackHandler
from langchain.schema.output import LLMResult
# TODO If used by two LLM runs in parallel... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter.html |
95b16aa4a2e4-1 | # Wait for the next token in the queue,
# but stop waiting if the done event is set
done, other = await asyncio.wait(
[
# NOTE: If you add other tasks here, update the code below,
# which assumes each set has exactly one task each
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter.html |
8246b67c569d-0 | Source code for langchain.callbacks.human
from typing import Any, Callable, Dict, Optional
from uuid import UUID
from langchain.callbacks.base import BaseCallbackHandler
def _default_approve(_input: str) -> bool:
msg = (
"Do you approve of the following input? "
"Anything except 'Y'/'Yes' (case-inse... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/human.html |
7c3f11145481-0 | Source code for langchain.callbacks.stdout
"""Callback Handler that prints to std out."""
from typing import Any, Dict, List, Optional, Union
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import AgentAction, AgentFinish, LLMResult
from langchain.utils.input import print_text
[docs]class... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/stdout.html |
7c3f11145481-1 | [docs] def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
"""Print out that we finished a chain."""
print("\n\033[1m> Finished chain.\033[0m")
[docs] def on_chain_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Do nothin... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/stdout.html |
7c3f11145481-2 | [docs] def on_text(
self,
text: str,
color: Optional[str] = None,
end: str = "",
**kwargs: Any,
) -> None:
"""Run when agent ends."""
print_text(text, color=color or self.color, end=end)
[docs] def on_agent_finish(
self, finish: AgentFinish, colo... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/stdout.html |
b6ec16216ac6-0 | Source code for langchain.callbacks.openai_info
"""Callback Handler that prints to std out."""
from typing import Any, Dict, List
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import LLMResult
MODEL_COST_PER_1K_TOKENS = {
# GPT-4 input
"gpt-4": 0.03,
"gpt-4-0314": 0.03,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html |
b6ec16216ac6-1 | "gpt-3.5-turbo-16k-0613": 0.003,
# GPT-3.5 output
"gpt-3.5-turbo-completion": 0.002,
"gpt-3.5-turbo-0301-completion": 0.002,
"gpt-3.5-turbo-0613-completion": 0.002,
"gpt-3.5-turbo-16k-completion": 0.004,
"gpt-3.5-turbo-16k-0613-completion": 0.004,
# Others
"gpt-35-turbo": 0.002, # Azure... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html |
b6ec16216ac6-2 | is_completion: bool = False,
) -> str:
"""
Standardize the model name to a format that can be used in the OpenAI API.
Args:
model_name: Model name to standardize.
is_completion: Whether the model is used for completion or not.
Defaults to False.
Returns:
Standardized ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html |
b6ec16216ac6-3 | [docs]class OpenAICallbackHandler(BaseCallbackHandler):
"""Callback Handler that tracks OpenAI info."""
total_tokens: int = 0
prompt_tokens: int = 0
completion_tokens: int = 0
successful_requests: int = 0
total_cost: float = 0.0
def __repr__(self) -> str:
return (
f"Token... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html |
b6ec16216ac6-4 | prompt_tokens = token_usage.get("prompt_tokens", 0)
model_name = standardize_model_name(response.llm_output.get("model_name", ""))
if model_name in MODEL_COST_PER_1K_TOKENS:
completion_cost = get_openai_token_cost_for_model(
model_name, completion_tokens, is_completion=True
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html |
a6cff80983b2-0 | Source code for langchain.callbacks.infino_callback
import time
from typing import Any, Dict, List, Optional, Union
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import AgentAction, AgentFinish, LLMResult
[docs]def import_infino() -> Any:
"""Import the infino client."""
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html |
a6cff80983b2-1 | payload = {
"date": int(time.time()),
key: value,
"labels": {
"model_id": self.model_id,
"model_version": self.model_version,
},
}
if self.verbose:
print(f"Tracking {key} with Infino: {payload}")
# Append... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html |
a6cff80983b2-2 | self.end_time = time.time()
duration = self.end_time - self.start_time
self._send_to_infino("latency", duration)
# Track success or error flag.
self._send_to_infino("error", self.error)
# Track token usage.
if (response.llm_output is not None) and isinstance(response.llm_... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html |
a6cff80983b2-3 | ) -> None:
"""Need to log the error."""
pass
[docs] def on_tool_start(
self,
serialized: Dict[str, Any],
input_str: str,
**kwargs: Any,
) -> None:
"""Do nothing when tool starts."""
pass
[docs] def on_agent_action(self, action: AgentAction, **kwa... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html |
3029047a5b5d-0 | Source code for langchain.callbacks.streaming_stdout
"""Callback Handler streams to stdout on new llm token."""
import sys
from typing import Any, Dict, List, Union
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import AgentAction, AgentFinish, LLMResult
[docs]class StreamingStdOutCallba... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout.html |
3029047a5b5d-1 | ) -> None:
"""Run when chain errors."""
[docs] def on_tool_start(
self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
) -> None:
"""Run when tool starts running."""
[docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
"""Run on agent action."... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout.html |
170f9c169d98-0 | Source code for langchain.callbacks.promptlayer_callback
"""Callback handler for promptlayer."""
from __future__ import annotations
import datetime
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple
from uuid import UUID
from langchain.callbacks.base import BaseCallbackHandler
from langchain.s... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html |
170f9c169d98-1 | tags: Optional[List[str]] = None,
**kwargs: Any,
) -> Any:
self.runs[run_id] = {
"messages": [self._create_message_dicts(m)[0] for m in messages],
"invocation_params": kwargs.get("invocation_params", {}),
"name": ".".join(serialized["id"]),
"request_st... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html |
170f9c169d98-2 | generation = response.generations[i][0]
resp = {
"text": generation.text,
"llm_output": response.llm_output,
}
model_params = run_info.get("invocation_params", {})
is_chat_model = run_info.get("messages", None) is not None
model... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.