id
stringlengths
14
15
text
stringlengths
44
2.47k
source
stringlengths
61
181
9c3ef4382793-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
9c3ef4382793-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
9c3ef4382793-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
9c3ef4382793-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
9c3ef4382793-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
5b24fd510b65-0
Source code for langchain.callbacks.utils import hashlib from pathlib import Path from typing import Any, Dict, Iterable, Tuple, Union [docs]def import_spacy() -> Any: """Import the spacy python package and raise an error if it is not installed.""" try: import spacy except ImportError: raise...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html
5b24fd510b65-1
parent_key (str): The prefix to prepend to the keys of the flattened dict. sep (str): The separator to use between the parent key and the key of the flattened dictionary. Yields: (str, any): A key-value pair from the flattened dictionary. """ for key, value in nested_dict.items()...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html
5b24fd510b65-2
"""Load json file to a string. Parameters: json_path (str): The path to the json file. Returns: (str): The string representation of the json file. """ with open(json_path, "r") as f: data = f.read() return data [docs]class BaseMetadataCallbackHandler: """This class handle...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html
5b24fd510b65-3
tool_ends (int): The number of times the tool end method has been called. agent_ends (int): The number of times the agent end method has been called. on_llm_start_records (list): A list of records of the on_llm_start method. on_llm_token_records (list): A list of records of the on_llm_token meth...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html
5b24fd510b65-4
self.on_llm_token_records: list = [] self.on_llm_end_records: list = [] self.on_chain_start_records: list = [] self.on_chain_end_records: list = [] self.on_tool_start_records: list = [] self.on_tool_end_records: list = [] self.on_text_records: list = [] self.on_ag...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html
5b24fd510b65-5
} [docs] def reset_callback_meta(self) -> None: """Reset the callback metadata.""" self.step = 0 self.starts = 0 self.ends = 0 self.errors = 0 self.text_ctr = 0 self.ignore_llm_ = False self.ignore_chain_ = False self.ignore_agent_ = False ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html
758409e2edec-0
Source code for langchain.callbacks.stdout """Callback Handler that prints to std out.""" from typing import Any, Dict, List, Optional from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult from langchain.utils.input import print_text [docs]class StdOut...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/stdout.html
758409e2edec-1
"""Print out that we finished a chain.""" print("\n\033[1m> Finished chain.\033[0m") [docs] def on_chain_error(self, error: BaseException, **kwargs: Any) -> None: """Do nothing.""" pass [docs] def on_tool_start( self, serialized: Dict[str, Any], input_str: str, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/stdout.html
758409e2edec-2
) -> None: """Run when agent ends.""" print_text(text, color=color or self.color, end=end) [docs] def on_agent_finish( self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any ) -> None: """Run on agent end.""" print_text(finish.log, color=color or self.color,...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/stdout.html
63dd96d18a5b-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
63dd96d18a5b-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
6d8028e4e39a-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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
6d8028e4e39a-1
llm_ends (int): The number of times the llm end method has been called. llm_streams (int): The number of times the text method has been called. tool_starts (int): The number of times the tool start method has been called. tool_ends (int): The number of times the tool end method has been called. ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
6d8028e4e39a-2
"""Whether to ignore agent callbacks.""" return self.ignore_agent_ @property def ignore_retriever(self) -> bool: """Whether to ignore retriever callbacks.""" return self.ignore_retriever_ [docs] def get_custom_callback_meta(self) -> Dict[str, Any]: return { "step":...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
6d8028e4e39a-3
"""Callback Handler that logs to Aim. Parameters: repo (:obj:`str`, optional): Aim repository path or Repo object to which Run object is bound. If skipped, default Repo is used. experiment_name (:obj:`str`, optional): Sets Run's `experiment` property. 'default' if not specifi...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
6d8028e4e39a-4
self._run_hash = self._run.hash self.action_records: list = [] [docs] def setup(self, **kwargs: Any) -> None: aim = import_aim() if not self._run: if self._run_hash: self._run = aim.Run( self._run_hash, repo=self.repo, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
6d8028e4e39a-5
self.llm_ends += 1 self.ends += 1 resp = {"action": "on_llm_end"} resp.update(self.get_custom_callback_meta()) response_res = deepcopy(response) generated = [ aim.Text(generation.text) for generations in response_res.generations for generation ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
6d8028e4e39a-6
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(outputs_res["output"]), name="on_chain_end", ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
6d8028e4e39a-7
"""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. """ self.step += 1 self.text_ctr += 1 [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
6d8028e4e39a-8
[docs] def flush_tracker( self, repo: Optional[str] = None, experiment_name: Optional[str] = None, system_tracking_interval: Optional[int] = 10, log_system_params: bool = True, langchain_asset: Any = None, reset: bool = True, finish: bool = False, )...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
6d8028e4e39a-9
repo=repo if repo else self.repo, experiment_name=experiment_name if experiment_name else self.experiment_name, system_tracking_interval=system_tracking_interval if system_tracking_interval else self.system_tracking_interval...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
e58bdd542509-0
Source code for langchain.callbacks.streaming_stdout_final_only """Callback Handler streams to stdout on new llm token.""" import sys from typing import Any, Dict, List, Optional from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler DEFAULT_ANSWER_PREFIX_TOKENS = ["Final", "Answer", ":"] [docs...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout_final_only.html
e58bdd542509-1
reached) stream_prefix: Should answer prefix itself also be streamed? """ 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 str...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout_final_only.html
a6fe3dc4c768-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-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: "...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-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(...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-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": [], ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-9
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) self.mlflg.jsonf(resp, f"llm_end_...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-10
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], **kwargs: Any) -> None: """Run when chain ends running.""" sel...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-11
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["on_tool_start_records"].append(resp) self.r...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-12
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) self.records["action_records"]...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-13
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.metrics, step=self.metrics["step"]) ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-14
visualizations_columns = [] complexity_metrics_columns = [ "flesch_reading_ease", "flesch_kincaid_grade", "smog_index", "coleman_liau_index", "automated_readability_index", "dale_chall_readability_score", "difficult_words", ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a6fe3dc4c768-15
pd = import_pandas() self.mlflg.table("action_records", pd.DataFrame(self.records["action_records"])) session_analysis_df = self._create_session_analysis_df() chat_html = session_analysis_df.pop("chat_html") chat_html = chat_html.replace("\n", "", regex=True) self.mlflg.table("se...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0ff95f41506c-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 from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult from langchain.schema.messages import Ba...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout.html
0ff95f41506c-1
"""Run when chain ends running.""" [docs] def on_chain_error(self, error: BaseException, **kwargs: Any) -> 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] ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout.html
c76d6bcd25f1-0
Source code for langchain.callbacks.base """Base callback handler that can be used to handle callbacks in langchain.""" from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, TypeVar, Union from uuid import UUID from tenacity import RetryCallState if TYPE_CHECKING: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c76d6bcd25f1-1
Args: token (str): The new token. chunk (GenerationChunk | ChatGenerationChunk): The new generated chunk, containing content and other information. """ [docs] def on_llm_end( self, response: LLMResult, *, run_id: UUID, parent_run_id:...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c76d6bcd25f1-2
) -> Any: """Run on agent action.""" [docs] def on_agent_finish( self, finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any, ) -> Any: """Run on agent end.""" [docs]class ToolManagerMixin: """Mixin for tool c...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c76d6bcd25f1-3
messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> Any: """Run when a chat model starts running.""" raise NotImpleme...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c76d6bcd25f1-4
metadata: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> Any: """Run when tool starts running.""" [docs]class RunManagerMixin: """Mixin for run manager.""" [docs] def on_text( self, text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None,...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c76d6bcd25f1-5
return False @property def ignore_retriever(self) -> bool: """Whether to ignore retriever callbacks.""" return False @property def ignore_chat_model(self) -> bool: """Whether to ignore chat model callbacks.""" return False [docs]class AsyncCallbackHandler(BaseCallbackHand...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c76d6bcd25f1-6
run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any, ) -> None: """Run on new LLM token. Only available when streaming is enabled.""" [docs] async def on_llm_end( self, response: LLMResult, *, run_id: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c76d6bcd25f1-7
**kwargs: Any, ) -> None: """Run when chain ends running.""" [docs] async def on_chain_error( self, error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any, ) -> None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c76d6bcd25f1-8
run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any, ) -> None: """Run on arbitrary text.""" [docs] async def on_retry( self, retry_state: RetryCallState, *, run_id: UUID, parent_run_id: Option...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c76d6bcd25f1-9
[docs] async def on_retriever_end( self, documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any, ) -> None: """Run on retriever end.""" [docs] async def on_retriever_e...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c76d6bcd25f1-10
self.inheritable_tags = inheritable_tags or [] self.metadata = metadata or {} self.inheritable_metadata = inheritable_metadata or {} [docs] def copy(self: T) -> T: """Copy the callback manager.""" return self.__class__( handlers=self.handlers, inheritable_handl...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c76d6bcd25f1-11
"""Set handler as the only handler on the callback manager.""" self.set_handlers([handler], inherit=inherit) [docs] def add_tags(self, tags: List[str], inherit: bool = True) -> None: for tag in tags: if tag in self.tags: self.remove_tags([tag]) self.tags.extend(tag...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
c410b1c0d1fb-0
Source code for langchain.callbacks.llmonitor_callback import os import traceback from contextvars import ContextVar from datetime import datetime from typing import Any, Dict, List, Literal, Union from uuid import UUID import requests from langchain.callbacks.base import BaseCallbackHandler from langchain.schema.agent...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html
c410b1c0d1fb-1
if not raw_input: return None if not isinstance(raw_input, dict): return _serialize(raw_input) input_value = raw_input.get("input") inputs_value = raw_input.get("inputs") question_value = raw_input.get("question") query_value = raw_input.get("query") if input_value: retur...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html
c410b1c0d1fb-2
return None def _get_user_id(metadata: Any) -> Any: if user_ctx.get() is not None: return user_ctx.get() metadata = metadata or {} user_id = metadata.get("user_id") if user_id is None: user_id = metadata.get("userId") # legacy, to delete in the future return user_id def _get_user_pr...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html
c410b1c0d1fb-3
- `ValueError`: if `app_id` is not provided either as an argument or as an environment variable. - `ConnectionError`: if the connection to the API fails. #### Example: ```python from langchain.llms import OpenAI from langchain.callbacks import LLMonitorCallbackHandler llmonitor_callb...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html
c410b1c0d1fb-4
) from e def __send_event(self, event: Dict[str, Any]) -> None: headers = {"Content-Type": "application/json"} event = {**event, "app": self.__app_id, "timestamp": str(datetime.utcnow())} if self.__verbose: print("llmonitor_callback", event) data = {"events": event} ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html
c410b1c0d1fb-5
messages: List[List[BaseMessage]], *, run_id: UUID, parent_run_id: Union[UUID, None] = None, tags: Union[List[str], None] = None, metadata: Union[Dict[str, Any], None] = None, **kwargs: Any, ) -> Any: user_id = _get_user_id(metadata) user_props = _get_...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html
c410b1c0d1fb-6
and "function_call" in generation.message.additional_kwargs else {} ), } for generation in response.generations[0] ] event = { "event": "end", "type": "llm", "runId": str(run_id), "parent_run_id":...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html
c410b1c0d1fb-7
self, output: str, *, run_id: UUID, parent_run_id: Union[UUID, None] = None, tags: Union[List[str], None] = None, **kwargs: Any, ) -> None: event = { "event": "end", "type": "tool", "runId": str(run_id), "parent_...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html
c410b1c0d1fb-8
event = { "event": "start", "type": type, "userId": user_id, "runId": str(run_id), "parentRunId": str(parent_run_id) if parent_run_id else None, "input": _parse_input(inputs), "tags": tags, "metadata": metadata, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html
c410b1c0d1fb-9
finish: AgentFinish, *, run_id: UUID, parent_run_id: Union[UUID, None] = None, **kwargs: Any, ) -> Any: event = { "event": "end", "type": "agent", "runId": str(run_id), "parentRunId": str(parent_run_id) if parent_run_id else Non...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html
c410b1c0d1fb-10
} self.__send_event(event) [docs] def on_llm_error( self, error: BaseException, *, run_id: UUID, parent_run_id: Union[UUID, None] = None, **kwargs: Any, ) -> Any: event = { "event": "error", "type": "llm", "runId"...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/llmonitor_callback.html
1bf8c31c416a-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
1bf8c31c416a-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
1bf8c31c416a-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
1bf8c31c416a-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
1bf8c31c416a-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
1bf8c31c416a-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
1bf8c31c416a-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
1bf8c31c416a-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
1bf8c31c416a-8
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] def on_tool_end(self, output: str, **kwargs: Any) -> None: """...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
1bf8c31c416a-9
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, } ) resp.update(self.get_custom_callback_m...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
1bf8c31c416a-10
) complexity_metrics_columns = [] visualizations_columns = [] if self.complexity_metrics: complexity_metrics_columns = [ "flesch_reading_ease", "flesch_kincaid_grade", "smog_index", "coleman_liau_index", ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
1bf8c31c416a-11
), 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] = None, entity: Optional[str] = Non...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
1bf8c31c416a-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
77d8ca46d9fa-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, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/trubrics_callback.html
77d8ca46d9fa-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/trubrics_callback.html
77d8ca46d9fa-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/trubrics_callback.html
52c41d5d3587-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: "...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html
52c41d5d3587-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."), ... ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html
52c41d5d3587-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html
52c41d5d3587-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html
f1f6764a2557-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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html
f1f6764a2557-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(...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html
f1f6764a2557-2
# If yes, then put tokens from now on if self.answer_reached: self.queue.put_nowait(token)
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html
6b4f7496e6cd-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
6b4f7496e6cd-1
# 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 asyncio.ensure_future(self.queue.get()), ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter.html
076e04903e55-0
Source code for langchain.callbacks.labelstudio_callback import os import warnings from datetime import datetime from enum import Enum from typing import Any, Dict, List, Optional, Tuple, Union from uuid import UUID from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import ( AgentAction,...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html
076e04903e55-1
textKey="content" nameKey="role" granularity="sentence"/> <Header value="Final response:"/> <TextArea name="response" toName="dialogue" maxSubmissions="1" editable="true" required="true"/> </View> <Header value="Rate the response:"/> <Rating name="rating" ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html
076e04903e55-2
self, api_key: Optional[str] = None, url: Optional[str] = None, project_id: Optional[int] = None, project_name: str = DEFAULT_PROJECT_NAME, project_config: Optional[str] = None, mode: Union[str, LabelStudioMode] = LabelStudioMode.PROMPT, ): super().__init__() ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html
076e04903e55-3
) self.api_key = api_key if not url: if os.getenv("LABEL_STUDIO_URL"): url = os.getenv("LABEL_STUDIO_URL") else: warnings.warn( f"Label Studio URL is not provided, " f"using default URL: {ls.LABEL_STUDIO_DEFA...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html
076e04903e55-4
) self.project_id = self.ls_project.id self.parsed_label_config = self.ls_project.parsed_label_config # Find the first TextArea tag # "from_name", "to_name", "value" will be used to create predictions self.from_name, self.to_name, self.value, self.input_type = ( ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html
076e04903e55-5
) -> None: # Create tasks in Label Studio tasks = [] prompts = self.payload[run_id]["prompts"] model_version = ( self.payload[run_id]["kwargs"] .get("invocation_params", {}) .get("model_name") ) for prompt, generation in zip(prompts, ge...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html