id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
c4d7491a702e-7 | "content": message.content,
}
)
prompts.append(dialog)
self.payload[str(run_id)] = {
"prompts": prompts,
"tags": tags,
"metadata": metadata,
"run_id": run_id,
"parent_run_id": parent_run_id,
"... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html |
c4d7491a702e-8 | 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, **kwargs: Any) -> Any:
"""Do nothing when agent takes a specific action."""
pass
[docs]... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html |
f2c6f2d95e70-0 | Source code for langchain.callbacks.streaming_aiter_final_only
from __future__ import annotations
from typing import Any, Dict, List, Optional
from langchain.callbacks.streaming_aiter import AsyncIteratorCallbackHandler
from langchain.schema import LLMResult
DEFAULT_ANSWER_PREFIX_TOKENS = ["Final", "Answer", ":"]
[docs... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html |
f2c6f2d95e70-1 | """
super().__init__()
if answer_prefix_tokens is None:
self.answer_prefix_tokens = DEFAULT_ANSWER_PREFIX_TOKENS
else:
self.answer_prefix_tokens = answer_prefix_tokens
if strip_tokens:
self.answer_prefix_tokens_stripped = [
token.strip(... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html |
f2c6f2d95e70-2 | # If yes, then put tokens from now on
if self.answer_reached:
self.queue.put_nowait(token) | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html |
19cd28074cbd-0 | Source code for langchain.callbacks.arthur_callback
"""ArthurAI's Callback Handler."""
from __future__ import annotations
import os
import uuid
from collections import defaultdict
from datetime import datetime
from time import time
from typing import TYPE_CHECKING, Any, DefaultDict, Dict, List, Optional
import numpy as... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
19cd28074cbd-1 | """
[docs] def __init__(
self,
arthur_model: ArthurModel,
) -> None:
"""Initialize callback handler."""
super().__init__()
arthurai = _lazy_load_arthur()
Stage = arthurai.common.constants.Stage
ValueType = arthurai.common.constants.ValueType
self.ar... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
19cd28074cbd-2 | arthur_url: Optional[str] = "https://app.arthur.ai",
arthur_login: Optional[str] = None,
arthur_password: Optional[str] = None,
) -> ArthurCallbackHandler:
"""Initialize callback handler from Arthur credentials.
Args:
model_id (str): The ID of the arthur model to log to.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
19cd28074cbd-3 | )
# get model from Arthur by the provided model ID
try:
arthur_model = arthur.get_model(model_id)
except ResponseClientError:
raise ValueError(
f"Was unable to retrieve model with id {model_id} from Arthur."
" Make sure the ID corresponds t... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
19cd28074cbd-4 | " Restart and try running the LLM again"
) from e
# mark the duration time between on_llm_start() and on_llm_end()
time_from_start_to_end = time() - run_map_data["start_time"]
# create inferences to log to Arthur
inferences = []
for i, generations in enumerate(respons... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
19cd28074cbd-5 | # add token usage counts to the inference if the
# ArthurModel was registered to monitor token usage
if (
isinstance(response.llm_output, dict)
and TOKEN_USAGE in response.llm_output
):
token_usage = response.llm... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
19cd28074cbd-6 | """On new token, pass."""
[docs] def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
"""Do nothing when LLM chain outputs an error."""
[docs] def on_tool_start(
self,
serialized: Dict[str, Any],
input_str: str,
**kwargs: Any,
) -> None:
"""Do ... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html |
e6b74a744905-0 | Source code for langchain.callbacks.infino_callback
import time
from typing import Any, Dict, List, Optional, cast
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import AgentAction, AgentFinish, LLMResult
from langchain.schema.messages import BaseMessage
[docs]def import_infino() -> Any:... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html |
e6b74a744905-1 | """Callback Handler that logs to Infino."""
[docs] def __init__(
self,
model_id: Optional[str] = None,
model_version: Optional[str] = None,
verbose: bool = False,
) -> None:
# Set Infino client
self.client = import_infino()
self.model_id = model_id
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html |
e6b74a744905-2 | self,
serialized: Dict[str, Any],
prompts: List[str],
**kwargs: Any,
) -> None:
"""Log the prompts to Infino, and set start time and error flag."""
for prompt in prompts:
self._send_to_infino("prompt", prompt, is_ts=False)
# Set the error flag to indicate ... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html |
e6b74a744905-3 | if token_usage is not None:
prompt_tokens = token_usage["prompt_tokens"]
total_tokens = token_usage["total_tokens"]
completion_tokens = token_usage["completion_tokens"]
self._send_to_infino("prompt_tokens", prompt_tokens)
self._send_to_infi... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html |
e6b74a744905-4 | input_str: str,
**kwargs: Any,
) -> None:
"""Do nothing when tool starts."""
pass
[docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
"""Do nothing when agent takes a specific action."""
pass
[docs] def on_tool_end(
self,
output:... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html |
e6b74a744905-5 | if self.is_chat_openai_model:
invocation_params = kwargs.get("invocation_params")
if invocation_params:
model_name = invocation_params.get("model_name")
if model_name:
self.chat_openai_model_name = model_name
prompt_tokens =... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html |
326a10395acf-0 | Source code for langchain.callbacks.argilla_callback
import os
import warnings
from typing import Any, Dict, List, Optional
from packaging.version import parse
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import AgentAction, AgentFinish, LLMResult
[docs]class ArgillaCallbackHandler(Bas... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html |
326a10395acf-1 | ... dataset_name="my-dataset",
... workspace_name="my-workspace",
... api_url="http://localhost:6900",
... api_key="argilla.apikey",
... )
>>> llm = OpenAI(
... temperature=0,
... callbacks=[argilla_callback],
... verbose=True,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html |
326a10395acf-2 | workspace_name: name of the workspace in Argilla where the specified
`FeedbackDataset` lives in. Defaults to `None`, which means that the
default workspace will be used.
api_url: URL of the Argilla Server that we want to use, and where the
`FeedbackDataset` li... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html |
326a10395acf-3 | )
# Show a warning message if Argilla will assume the default values will be used
if api_url is None and os.getenv("ARGILLA_API_URL") is None:
warnings.warn(
(
"Since `api_url` is None, and the env var `ARGILLA_API_URL` is not"
f" set, ... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html |
326a10395acf-4 | ) from e
# Set the Argilla variables
self.dataset_name = dataset_name
self.workspace_name = workspace_name or rg.get_workspace()
# Retrieve the `FeedbackDataset` from Argilla (without existing records)
try:
extra_args = {}
if parse(self.ARGILLA_VERSION) < ... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html |
326a10395acf-5 | f"`langchain` integration. Supported fields are: {supported_fields},"
f" and the current `FeedbackDataset` fields are {[field.name for field in self.dataset.fields]}." # noqa: E501
" For more information on how to create a `langchain`-compatible"
f" `FeedbackDataset` in ... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html |
326a10395acf-6 | prompts = self.prompts[str(kwargs["run_id"])]
for prompt, generations in zip(prompts, response.generations):
self.dataset.add_records(
records=[
{
"fields": {
"prompt": prompt,
"respon... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html |
326a10395acf-7 | """If either the `parent_run_id` or the `run_id` is in `self.prompts`, then
log the outputs to Argilla, and pop the run from `self.prompts`. The behavior
differs if the output is a list or not.
"""
if not any(
key in self.prompts
for key in [str(kwargs["parent_run... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html |
326a10395acf-8 | self.prompts.pop(str(kwargs["run_id"]))
if parse(self.ARGILLA_VERSION) < parse("1.14.0"):
# Push the records to Argilla
self.dataset.push_to_argilla()
[docs] def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
"""Do nothing when LLM chain outputs an error.""... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html |
8a7e2f463460-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
import langchain
from langchain.callbacks.base import BaseCallbackHandler
from langchain.callbacks.utils import (
BaseMetadataCall... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-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_... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-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`."
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-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,... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-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: BaseException, **kwargs: Any) -> None:
"""Run when LLM errors."""
self.step += 1
self.errors += 1
[docs] def on_chain... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-6 | 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._log_stream(chain_output_val, resp, self.step)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-7 | 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_records.append(resp)
[docs] ... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-12 | sentence_spans,
style=visualization,
options={"compact": True},
jupyter=False,
page=True,
)
self.experiment.log_asset_data(
html,
name=f... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-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:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
8a7e2f463460-14 | else:
llm_parameters = langchain_asset.dict()
except Exception:
return {}
return llm_parameters | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html |
056dc66a5e10-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
056dc66a5e10-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
056dc66a5e10-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
056dc66a5e10-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
056dc66a5e10-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")... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
69cff5503200-0 | Source code for langchain.callbacks.sagemaker_callback
import json
import os
import shutil
import tempfile
from copy import deepcopy
from typing import Any, Dict, List, Optional
from langchain.callbacks.base import BaseCallbackHandler
from langchain.callbacks.utils import (
flatten_dict,
)
from langchain.schema imp... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html |
69cff5503200-1 | # Create a temporary directory
self.temp_dir = tempfile.mkdtemp()
def _reset(self) -> None:
for k, v in self.metrics.items():
self.metrics[k] = 0
[docs] def on_llm_start(
self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
) -> None:
"""Run when LLM... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html |
69cff5503200-2 | [docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
"""Run when LLM ends running."""
self.metrics["step"] += 1
self.metrics["llm_ends"] += 1
self.metrics["ends"] += 1
llm_ends = self.metrics["llm_ends"]
resp: Dict[str, Any] = {}
resp.update... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html |
69cff5503200-3 | resp.update(flatten_dict(serialized))
resp.update(self.metrics)
chain_input = ",".join([f"{k}={v}" for k, v in inputs.items()])
input_resp = deepcopy(resp)
input_resp["inputs"] = chain_input
self.jsonf(input_resp, self.temp_dir, f"chain_start_{chain_starts}")
[docs] def on_cha... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html |
69cff5503200-4 | resp: Dict[str, Any] = {}
resp.update({"action": "on_tool_start", "input_str": input_str})
resp.update(flatten_dict(serialized))
resp.update(self.metrics)
self.jsonf(resp, self.temp_dir, f"tool_start_{tool_starts}")
[docs] def on_tool_end(self, output: str, **kwargs: Any) -> None:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html |
69cff5503200-5 | """Run when agent ends running."""
self.metrics["step"] += 1
self.metrics["agent_ends"] += 1
self.metrics["ends"] += 1
agent_ends = self.metrics["agent_ends"]
resp: Dict[str, Any] = {}
resp.update(
{
"action": "on_agent_finish",
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html |
69cff5503200-6 | save_json(data, file_path)
self.run.log_file(file_path, name=filename, is_output=is_output)
[docs] def flush_tracker(self) -> None:
"""Reset the steps and delete the temporary local directory."""
self._reset()
shutil.rmtree(self.temp_dir) | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html |
fbb9948395eb-0 | Source code for langchain.callbacks.mlflow_callback
import os
import random
import string
import tempfile
import traceback
from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from langchain.callbacks.base import BaseCallbackHandler
from langchain.callbacks.utils import... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-1 | "flesch_reading_ease": textstat.flesch_reading_ease(text),
"flesch_kincaid_grade": textstat.flesch_kincaid_grade(text),
"smog_index": textstat.smog_index(text),
"coleman_liau_index": textstat.coleman_liau_index(text),
"automated_readability_index": textstat.automated_readability_index(te... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-2 | doc, style="ent", jupyter=False, page=True
)
text_visualizations = {
"dependency_tree": dep_out,
"entities": ent_out,
}
resp.update(text_visualizations)
return resp
[docs]def construct_html_from_prompt_and_generation(prompt: str, generation: str) -> Any:
"... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-3 | self.mlf_expid = self.mlflow.tracking.fluent._get_experiment_id()
self.mlf_exp = self.mlflow.get_experiment(self.mlf_expid)
else:
tracking_uri = get_from_dict_or_env(
kwargs, "tracking_uri", "MLFLOW_TRACKING_URI", ""
)
self.mlflow.set_tracking_uri(... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-4 | ):
self.mlflow.end_run()
[docs] def metric(self, key: str, value: float) -> None:
"""To log metric to mlflow server."""
with self.mlflow.start_run(
run_id=self.run.info.run_id, experiment_id=self.mlf_expid
):
self.mlflow.log_metric(key, value)
[docs] def... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-5 | ):
self.mlflow.log_text(html, f"{filename}.html")
[docs] def text(self, text: str, filename: str) -> None:
"""To log the input text as text file artifact."""
with self.mlflow.start_run(
run_id=self.run.info.run_id, experiment_id=self.mlf_expid
):
self.mlflo... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-6 | """
[docs] def __init__(
self,
name: Optional[str] = "langchainrun-%",
experiment: Optional[str] = "langchain",
tags: Optional[Dict] = None,
tracking_uri: Optional[str] = None,
) -> None:
"""Initialize callback handler."""
import_pandas()
import_tex... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-7 | "on_llm_end_records": [],
"on_chain_start_records": [],
"on_chain_end_records": [],
"on_tool_start_records": [],
"on_tool_end_records": [],
"on_text_records": [],
"on_agent_finish_records": [],
"on_agent_action_records": [],
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-8 | """Run when LLM generates a new token."""
self.metrics["step"] += 1
self.metrics["llm_streams"] += 1
llm_streams = self.metrics["llm_streams"]
resp: Dict[str, Any] = {}
resp.update({"action": "on_llm_new_token", "token": token})
resp.update(self.metrics)
self.mlfl... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-9 | ) # type: ignore # noqa: E501
self.mlflg.metrics(
complexity_metrics,
step=self.metrics["step"],
)
self.records["on_llm_end_records"].append(generation_resp)
self.records["action_records"].append(generation_resp)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-10 | input_resp = deepcopy(resp)
input_resp["inputs"] = chain_input
self.records["on_chain_start_records"].append(input_resp)
self.records["action_records"].append(input_resp)
self.mlflg.jsonf(input_resp, f"chain_start_{chain_starts}")
[docs] def on_chain_end(self, outputs: Dict[str, Any],... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-11 | tool_starts = self.metrics["tool_starts"]
resp: Dict[str, Any] = {}
resp.update({"action": "on_tool_start", "input_str": input_str})
resp.update(flatten_dict(serialized))
resp.update(self.metrics)
self.mlflg.metrics(self.metrics, step=self.metrics["step"])
self.records["o... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-12 | self.metrics["text_ctr"] += 1
text_ctr = self.metrics["text_ctr"]
resp: Dict[str, Any] = {}
resp.update({"action": "on_text", "text": text})
resp.update(self.metrics)
self.mlflg.metrics(self.metrics, step=self.metrics["step"])
self.records["on_text_records"].append(resp)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-13 | resp: Dict[str, Any] = {}
resp.update(
{
"action": "on_agent_action",
"tool": action.tool,
"tool_input": action.tool_input,
"log": action.log,
}
)
resp.update(self.metrics)
self.mlflg.metrics(self.met... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-14 | )
complexity_metrics_columns = []
visualizations_columns = []
complexity_metrics_columns = [
"flesch_reading_ease",
"flesch_kincaid_grade",
"smog_index",
"coleman_liau_index",
"automated_readability_index",
"dale_chall_reada... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
fbb9948395eb-15 | ),
axis=1,
)
return session_analysis_df
[docs] def flush_tracker(self, langchain_asset: Any = None, finish: bool = False) -> None:
pd = import_pandas()
self.mlflg.table("action_records", pd.DataFrame(self.records["action_records"]))
session_analysis_df = self._crea... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
4f45b7eb6cb8-0 | Source code for langchain.callbacks.clearml_callback
from __future__ import annotations
import tempfile
from copy import deepcopy
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence
from langchain.callbacks.base import BaseCallbackHandler
from langchain.callbacks.util... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
4f45b7eb6cb8-1 | This handler will utilize the associated callback method and formats
the input of each callback function with metadata regarding the state of LLM run,
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] de... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
4f45b7eb6cb8-2 | "The clearml callback is currently in beta and is subject to change "
"based on updates to `langchain`. Please report any issues to "
"https://github.com/allegroai/clearml/issues with the tag `langchain`."
)
self.logger.report_text(warning, level=30, print_console=True)
s... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
4f45b7eb6cb8-3 | 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.on_llm_token_records.append(resp)
self.action_records.append(resp)
if self.stream_logs:
self.logger.rep... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
4f45b7eb6cb8-4 | self.chain_starts += 1
self.starts += 1
resp = self._init_resp()
resp.update({"action": "on_chain_start"})
resp.update(flatten_dict(serialized))
resp.update(self.get_custom_callback_meta())
chain_input = inputs.get("input", inputs.get("human_input"))
if isinstance... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
4f45b7eb6cb8-5 | """Run when chain errors."""
self.step += 1
self.errors += 1
[docs] def on_tool_start(
self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
) -> None:
"""Run when tool starts running."""
self.step += 1
self.tool_starts += 1
self.starts += 1
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
4f45b7eb6cb8-6 | self.text_ctr += 1
resp = self._init_resp()
resp.update({"action": "on_text", "text": text})
resp.update(self.get_custom_callback_meta())
self.on_text_records.append(resp)
self.action_records.append(resp)
if self.stream_logs:
self.logger.report_text(resp)
[doc... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
4f45b7eb6cb8-7 | [docs] def analyze_text(self, text: str) -> dict:
"""Analyze text using textstat and spacy.
Parameters:
text (str): The text to analyze.
Returns:
(dict): A dictionary containing the complexity metrics.
"""
resp = {}
textstat = import_textstat()
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
4f45b7eb6cb8-8 | "osman": textstat.osman(text),
}
resp.update(text_complexity_metrics)
if self.visualize and self.nlp and self.temp_dir.name is not None:
doc = self.nlp(text)
dep_out = spacy.displacy.render( # type: ignore
doc, style="dep", jupyter=False, page=Tru... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
4f45b7eb6cb8-9 | if rename_map:
llm_df = llm_df.rename(rename_map, axis=1)
return llm_df
def _create_session_analysis_df(self) -> Any:
"""Create a dataframe with all the information from the session."""
pd = import_pandas()
on_llm_end_records_df = pd.DataFrame(self.on_llm_end_records)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
4f45b7eb6cb8-10 | "token_usage_prompt_tokens",
"token_usage_completion_tokens",
]
+ complexity_metrics_columns
+ visualizations_columns,
{"step": "output_step", "text": "output"},
)
session_analysis_df = pd.concat([llm_input_prompts_df, llm_outputs_df], axis... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
4f45b7eb6cb8-11 | output_model = clearml.OutputModel(
task=self.task, config_text=load_json(langchain_asset_path)
)
output_model.update_weights(
weights_filename=str(langchain_asset_path),
auto_delete_file=False,
target_filena... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html |
c8b9ba99d355-0 | Source code for langchain.callbacks.trubrics_callback
import os
from typing import Any, Dict, List, Optional
from uuid import UUID
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import LLMResult
from langchain.schema.messages import (
AIMessage,
BaseMessage,
ChatMessage,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/trubrics_callback.html |
c8b9ba99d355-1 | """
Callback handler for Trubrics.
Args:
project: a trubrics project, default project is "default"
email: a trubrics account email, can equally be set in env variables
password: a trubrics account password, can equally be set in env variables
**kwargs: all other kwargs are parsed... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/trubrics_callback.html |
c8b9ba99d355-2 | serialized: Dict[str, Any],
messages: List[List[BaseMessage]],
**kwargs: Any,
) -> None:
self.messages = [_convert_message_to_dict(message) for message in messages[0]]
self.prompt = self.messages[-1]["content"]
[docs] def on_llm_end(self, response: LLMResult, run_id: UUID, **kwarg... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/trubrics_callback.html |
9a580bfae589-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/human.html |
673a381f6dea-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
from langchain.callbacks.base import BaseCallbackHandler
from langchain.callbacks.utils import (
Ba... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
673a381f6dea-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),
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
673a381f6dea-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,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
673a381f6dea-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
673a381f6dea-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
673a381f6dea-5 | )
self.deck.append(self.markdown_renderer().to_html(generation.text))
[docs] def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
"""Run when LLM errors."""
self.step += 1
self.errors += 1
[docs] def on_chain_start(
self, serialized: Dict[str, An... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
673a381f6dea-6 | resp.update(self.get_custom_callback_meta())
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: BaseException, **kwargs: Any) -> None:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
673a381f6dea-7 | self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
)
[docs] def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
"""Run when tool errors."""
self.step += 1
self.errors += 1
[docs] def on_text(self, text: str, **kwargs: Any) -> None:
"""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
673a381f6dea-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,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/flyte_callback.html |
aee86706e2fc-0 | Source code for langchain.callbacks.context_callback
"""Callback handler for Context AI"""
import os
from typing import Any, Dict, List
from uuid import UUID
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import (
BaseMessage,
LLMResult,
)
[docs]def import_context() -> Any:
"... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html |
aee86706e2fc-1 | >>> chat = ChatOpenAI(
... temperature=0,
... headers={"user_id": "123"},
... callbacks=[context_callback],
... openai_api_key="API_KEY_HERE",
... )
>>> messages = [
... SystemMessage(content="You translate English to French."),
... ... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html |
aee86706e2fc-2 | (
self.context,
self.credential,
self.conversation_model,
self.message_model,
self.message_role_model,
self.rating_model,
) = import_context()
token = token or os.environ.get("CONTEXT_TOKEN") or ""
self.client = self.context... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html |
aee86706e2fc-3 | """Run when LLM ends."""
if len(response.generations) == 0 or len(response.generations[0]) == 0:
return
if not self.chain_run_id:
generation = response.generations[0][0]
self.messages.append(
self.message_model(
message=generation.t... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html |
53ee3b064a1c-0 | Source code for langchain.callbacks.aim_callback
from copy import deepcopy
from typing import Any, Dict, List, Optional
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import AgentAction, AgentFinish, LLMResult
[docs]def import_aim() -> Any:
"""Import the aim python package and raise ... | lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.