id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
a6076a070fdd-0
Source code for langchain.callbacks.arize_callback from datetime import datetime from typing import Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.utils import import_pandas from langchain.schema import AgentAction, AgentFinish, LLMResult [docs]class A...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/arize_callback.html
a6076a070fdd-1
self.arize_client = Client(space_key=SPACE_KEY, api_key=API_KEY) if SPACE_KEY == "SPACE_KEY" or API_KEY == "API_KEY": raise ValueError("❌ CHANGE SPACE AND API KEYS") else: print("✅ Arize client setup done! Now you can start using Arize!") [docs] def on_llm_start( self,...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/arize_callback.html
a6076a070fdd-2
for generations in response.generations: for generation in generations: prompt = self.prompt_records[self.step] self.step = self.step + 1 prompt_embedding = pd.Series( self.generator.generate_embeddings( text_col=pd....
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/arize_callback.html
a6076a070fdd-3
"completion_token", "total_token", ], prompt_column_names=prompt_columns, response_column_names=response_columns, ) response_from_arize = self.arize_client.log( dataframe=df, ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/arize_callback.html
a6076a070fdd-4
pass [docs] def on_tool_end( self, output: str, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any, ) -> None: pass [docs] def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/arize_callback.html
d819d7118f27-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/stable/_modules/langchain/callbacks/clearml_callback.html
d819d7118f27-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. """ def __init__( self, task_type: Optional[str] = "inference", project_name: Optional[str] = "langchain_callback_demo", tags: Optional[Seq...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/clearml_callback.html
d819d7118f27-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/stable/_modules/langchain/callbacks/clearml_callback.html
d819d7118f27-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/stable/_modules/langchain/callbacks/clearml_callback.html
d819d7118f27-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/stable/_modules/langchain/callbacks/clearml_callback.html
d819d7118f27-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/stable/_modules/langchain/callbacks/clearml_callback.html
d819d7118f27-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/stable/_modules/langchain/callbacks/clearml_callback.html
d819d7118f27-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/stable/_modules/langchain/callbacks/clearml_callback.html
d819d7118f27-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/stable/_modules/langchain/callbacks/clearml_callback.html
d819d7118f27-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/stable/_modules/langchain/callbacks/clearml_callback.html
d819d7118f27-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 preformed session so far so it is identifyable langchain_asset: The langchain asset to save. finish: Whether to ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/clearml_callback.html
d819d7118f27-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/stable/_modules/langchain/callbacks/clearml_callback.html
d46655feb9e6-0
Source code for langchain.callbacks.mlflow_callback 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 ( Bas...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-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/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-2
doc, style="ent", jupyter=False, page=True ) text_visualizations = { "dependency_tree": dep_out, "entities": ent_out, } resp.update(text_visualizations) return resp def construct_html_from_prompt_and_generation(prompt: str, generation: str) -> Any: """Cons...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-3
# User can set other env variables described here # > https://www.mlflow.org/docs/latest/tracking.html#logging-to-a-tracking-server experiment_name = get_from_dict_or_env( kwargs, "experiment_name", "MLFLOW_EXPERIMENT_NAME" ) self.mlf_exp = self.mlflow.get_experiment_by_name(...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-4
): self.mlflow.log_metric(key, value) def metrics( self, data: Union[Dict[str, float], Dict[str, int]], step: Optional[int] = 0 ) -> None: """To log all metrics in the input dict.""" with self.mlflow.start_run( run_id=self.run.info.run_id, experiment_id=self.mlf_e...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-5
def artifact(self, path: str) -> None: """To upload the file from given path as artifact.""" with self.mlflow.start_run( run_id=self.run.info.run_id, experiment_id=self.mlf_expid ): self.mlflow.log_artifact(path) def langchain_artifact(self, chain: Any) -> None: ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-6
super().__init__() self.name = name self.experiment = experiment self.tags = tags self.tracking_uri = tracking_uri self.temp_dir = tempfile.TemporaryDirectory() self.mlflg = MlflowLogger( tracking_uri=self.tracking_uri, experiment_name=self.experim...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-7
self.metrics[k] = 0 for k, v in self.records.items(): self.records[k] = [] [docs] def on_llm_start( self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any ) -> None: """Run when LLM starts.""" self.metrics["step"] += 1 self.metrics["llm_starts"] +=...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-8
self.records["on_llm_token_records"].append(resp) self.records["action_records"].append(resp) self.mlflg.jsonf(resp, f"llm_new_tokens_{llm_streams}") [docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Run when LLM ends running.""" self.metrics["step"] += 1 ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-9
dependency_tree = generation_resp["dependency_tree"] entities = generation_resp["entities"] self.mlflg.html(dependency_tree, "dep-" + hash_string(generation.text)) self.mlflg.html(entities, "ent-" + hash_string(generation.text)) [docs] def on_llm_error( self, e...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-10
"""Run when chain ends running.""" self.metrics["step"] += 1 self.metrics["chain_ends"] += 1 self.metrics["ends"] += 1 chain_ends = self.metrics["chain_ends"] resp: Dict[str, Any] = {} chain_output = ",".join([f"{k}={v}" for k, v in outputs.items()]) resp.update({...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-11
self.records["on_tool_start_records"].append(resp) self.records["action_records"].append(resp) self.mlflg.jsonf(resp, f"tool_start_{tool_starts}") [docs] def on_tool_end(self, output: str, **kwargs: Any) -> None: """Run when tool ends running.""" self.metrics["step"] += 1 self...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-12
self.records["on_text_records"].append(resp) self.records["action_records"].append(resp) self.mlflg.jsonf(resp, f"on_text_{text_ctr}") [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Run when agent ends running.""" self.metrics["step"] += 1 sel...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-13
self.mlflg.metrics(self.metrics, step=self.metrics["step"]) self.records["on_agent_action_records"].append(resp) self.records["action_records"].append(resp) self.mlflg.jsonf(resp, f"agent_action_{tool_starts}") def _create_session_analysis_df(self) -> Any: """Create a dataframe with ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-14
[ "step", "text", "token_usage_total_tokens", "token_usage_prompt_tokens", "token_usage_completion_tokens", ] + complexity_metrics_columns + visualizations_columns ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
d46655feb9e6-15
try: langchain_asset.save(langchain_asset_path) self.mlflg.artifact(langchain_asset_path) except ValueError: try: langchain_asset.save_agent(langchain_asset_path) self.mlflg.artifact(langchain_ass...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/mlflow_callback.html
f49d93018420-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 def import_infino() -> Any: try: from infinopy import InfinoClient ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/infino_callback.html
f49d93018420-1
"labels": { "model_id": self.model_id, "model_version": self.model_version, }, } if self.verbose: print(f"Tracking {key} with Infino: {payload}") # Append to Infino time series only if is_ts is True, otherwise # append to Infino log...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/infino_callback.html
f49d93018420-2
# 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_output, Dict): token_usage = response.llm_output["token_usage"] if token_usage is not None: promp...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/infino_callback.html
f49d93018420-3
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]...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/infino_callback.html
0322921a2eaf-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/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-1
"automated_readability_index": textstat.automated_readability_index(text), "dale_chall_readability_score": textstat.dale_chall_readability_score(text), "difficult_words": textstat.difficult_words(text), "linsear_write_formula": textstat.linsear_write_formula(text), "gunning_fog": textsta...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-2
stream_logs (bool): Whether to stream callback actions to Comet 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...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-3
"based on updates to `langchain`. Please report any issues to " "https://github.com/comet-ml/issue-tracking/issues with the tag " "`langchain`." ) self.comet_ml.LOGGER.warning(warning) self.callback_columns: list = [] self.action_records: list = [] self.co...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-4
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, response: LLMResult, **kwargs: Any) -> None: """Run when LLM end...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-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/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-6
if isinstance(chain_output_val, str): output_resp = deepcopy(resp) if self.stream_logs: self._log_stream(chain_output_val, resp, self.step) output_resp.update({chain_output_key: chain_output_val}) self.action_records.append(output_resp)...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-7
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] def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> N...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-8
"""Run on agent action.""" self.step += 1 self.tool_starts += 1 self.starts += 1 tool = action.tool tool_input = str(action.tool_input) log = action.log resp = self._init_resp() resp.update({"action": "on_agent_action", "log": log, "tool": tool}) r...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-9
return resp [docs] def flush_tracker( self, langchain_asset: Any = None, task_type: Optional[str] = "inference", workspace: Optional[str] = None, project_name: Optional[str] = "comet-langchain-demo", tags: Optional[Sequence] = None, name: Optional[str] = None, ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-10
self.experiment.log_text(prompt, metadata=metadata, step=step) def _log_model(self, langchain_asset: Any) -> None: model_parameters = self._get_llm_parameters(langchain_asset) self.experiment.log_parameters(model_parameters, prefix="model") langchain_asset_path = Path(self.temp_dir.name, "mo...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-11
# Log the langchain low-level records as a JSON file directly self.experiment.log_asset_data( self.action_records, "langchain-action_records.json", metadata=metadata ) except Exception: self.comet_ml.LOGGER.warning( "Failed to log session data ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-12
) self.experiment.log_asset_data( html, name=f"langchain-viz-{visualization}-{idx}.html", metadata={"prompt": prompt}, step=idx, ) except Exception as e: ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
0322921a2eaf-13
self.reset_callback_meta() self.temp_dir = tempfile.TemporaryDirectory() def _create_session_analysis_dataframe(self, langchain_asset: Any = None) -> dict: pd = import_pandas() llm_parameters = self._get_llm_parameters(langchain_asset) num_generations_per_prompt = llm_parameters.get(...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/comet_ml_callback.html
7e2dbe72a59d-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/stable/_modules/langchain/callbacks/streaming_stdout.html
7e2dbe72a59d-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/stable/_modules/langchain/callbacks/streaming_stdout.html
c319f8d04476-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/stable/_modules/langchain/callbacks/human.html
af1e87a33343-0
Source code for langchain.callbacks.manager from __future__ import annotations import asyncio import functools import logging import os import warnings from contextlib import asynccontextmanager, contextmanager from contextvars import ContextVar from typing import ( Any, AsyncGenerator, Dict, Generator,...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-1
wandb_tracing_callback_var: ContextVar[ Optional[WandbTracer] ] = ContextVar( # noqa: E501 "tracing_wandb_callback", default=None ) tracing_v2_callback_var: ContextVar[ Optional[LangChainTracer] ] = ContextVar( # noqa: E501 "tracing_callback_v2", default=None ) def _get_debug() -> bool: return lan...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-2
tracing_callback_var.set(cb) yield session tracing_callback_var.set(None) [docs]@contextmanager def wandb_tracing_enabled( session_name: str = "default", ) -> Generator[None, None, None]: """Get the WandbTracer in a context manager. Args: session_name (str, optional): The name of the session...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-3
example_id = UUID(example_id) cb = LangChainTracer( example_id=example_id, project_name=project_name, ) tracing_v2_callback_var.set(cb) yield tracing_v2_callback_var.set(None) @contextmanager def trace_as_chain_group( group_name: str, *, project_name: Optional[str] = None...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-4
) run_manager = cm.on_chain_start({"name": group_name}, {}) yield run_manager.get_child() run_manager.on_chain_end({}) @asynccontextmanager async def atrace_as_chain_group( group_name: str, *, project_name: Optional[str] = None, example_id: Optional[Union[str, UUID]] = None, tags: Option...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-5
try: yield run_manager.get_child() finally: await run_manager.on_chain_end({}) def _handle_event( handlers: List[BaseCallbackHandler], event_name: str, ignore_condition_name: Optional[str], *args: Any, **kwargs: Any, ) -> None: """Generic event handler for CallbackManager."""...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-6
if ignore_condition_name is None or not getattr(handler, ignore_condition_name): event = getattr(handler, event_name) if asyncio.iscoroutinefunction(event): await event(*args, **kwargs) else: if handler.run_inline: event(*args, **kw...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-7
) await asyncio.gather( *( _ahandle_event_for_handler( handler, event_name, ignore_condition_name, *args, **kwargs ) for handler in handlers if not handler.run_inline ) ) BRM = TypeVar("BRM", bound="BaseRunManager") class BaseRunMan...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-8
Returns: BaseRunManager: The noop manager. """ return cls( run_id=uuid4(), handlers=[], inheritable_handlers=[], tags=[], inheritable_tags=[], ) class RunManager(BaseRunManager): """Sync Run Manager.""" def on_text( ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-9
) -> None: """Run when LLM generates a new token. Args: token (str): The new token. """ _handle_event( self.handlers, "on_llm_new_token", "ignore_llm", token=token, run_id=self.run_id, parent_run_id=self....
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-10
"""Run when LLM generates a new token. Args: token (str): The new token. """ await _ahandle_event( self.handlers, "on_llm_new_token", "ignore_llm", token, run_id=self.run_id, parent_run_id=self.parent_run_id, ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-11
Defaults to None. Returns: CallbackManager: The child callback manager. """ manager = CallbackManager(handlers=[], parent_run_id=self.run_id) manager.set_handlers(self.inheritable_handlers) manager.add_tags(self.inheritable_tags) if tag is not None: ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-12
"on_agent_action", "ignore_agent", action, run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> Any: """Run when agent finish is received. Args: ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-13
self.handlers, "on_chain_end", "ignore_chain", outputs, run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) async def on_chain_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any,...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-14
run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) class CallbackManagerForToolRun(RunManager, ToolManagerMixin): """Callback manager for tool run.""" def get_child(self, tag: Optional[str] = None) -> CallbackManager: """Get a child callback manager. ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-15
run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) class AsyncCallbackManagerForToolRun(AsyncRunManager, ToolManagerMixin): """Async callback manager for tool run.""" def get_child(self, tag: Optional[str] = None) -> AsyncCallbackManager: """Get a child cal...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-16
run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs, ) class CallbackManager(BaseCallbackManager): """Callback manager that can be used to handle callbacks from langchain.""" def on_llm_start( self, serialized: Dict[str, Any], prompts: List[str]...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-17
messages: List[List[BaseMessage]], **kwargs: Any, ) -> List[CallbackManagerForLLMRun]: """Run when LLM starts running. Args: serialized (Dict[str, Any]): The serialized LLM. messages (List[List[BaseMessage]]): The list of messages. run_id (UUID, optional):...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-18
inputs (Dict[str, Any]): The inputs to the chain. run_id (UUID, optional): The ID of the run. Defaults to None. Returns: CallbackManagerForChainRun: The callback manager for the chain run. """ if run_id is None: run_id = uuid4() _handle_event( ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-19
run_id = uuid4() _handle_event( self.handlers, "on_tool_start", "ignore_agent", serialized, input_str, run_id=run_id, parent_run_id=self.parent_run_id, tags=self.tags, **kwargs, ) return C...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-20
local_tags, ) class AsyncCallbackManager(BaseCallbackManager): """Async callback manager that can be used to handle callbacks from LangChain.""" @property def is_async(self) -> bool: """Return whether the handler is async.""" return True async def on_llm_start( self, ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-21
) ) await asyncio.gather(*tasks) return managers async def on_chat_model_start( self, serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any, ) -> Any: """Run when LLM starts running. Args: serialized (...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-22
serialized: Dict[str, Any], inputs: Dict[str, Any], 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]): ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-23
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/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-24
Defaults to None. local_tags (Optional[List[str]], optional): The local tags. Defaults to None. Returns: AsyncCallbackManager: The configured async callback manager. """ return _configure( cls, inheritable_callbacks, loc...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-25
Defaults to None. local_tags (Optional[List[str]], optional): The local tags. Defaults to None. Returns: T: The configured callback manager. """ callback_manager = callback_manager_cls(handlers=[]) if inheritable_callbacks or local_callbacks: if isinstance(inheritable_callbacks, ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-26
) tracer_v2 = tracing_v2_callback_var.get() tracing_v2_enabled_ = ( env_var_is_set("LANGCHAIN_TRACING_V2") or tracer_v2 is not None ) tracer_project = os.environ.get( "LANGCHAIN_PROJECT", os.environ.get("LANGCHAIN_SESSION", "default") ) debug = _get_debug() if ( verbo...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
af1e87a33343-27
if tracing_v2_enabled_ and not any( isinstance(handler, LangChainTracer) for handler in callback_manager.handlers ): if tracer_v2: callback_manager.add_handler(tracer_v2, True) else: try: handler = LangChainTrace...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/manager.html
c630145c3a58-0
Source code for langchain.callbacks.argilla_callback import os import warnings from typing import Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult [docs]class ArgillaCallbackHandler(BaseCallbackHandler): """Cal...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/argilla_callback.html
c630145c3a58-1
>>> argilla_callback = ArgillaCallbackHandler( ... dataset_name="my-dataset", ... workspace_name="my-workspace", ... api_url="http://localhost:6900", ... api_key="argilla.apikey", ... ) >>> llm = OpenAI( ... temperature=0, ... callb...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/argilla_callback.html
c630145c3a58-2
`FeedbackDataset` lives in. Defaults to `None`, which means that either `ARGILLA_API_URL` environment variable or the default http://localhost:6900 will be used. api_key: API Key to connect to the Argilla Server. Defaults to `None`, which means that either `AR...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/argilla_callback.html
c630145c3a58-3
" set, it will default to `argilla.apikey`." ), ) # Connect to Argilla with the provided credentials, if applicable try: rg.init( api_key=api_key, api_url=api_url, ) except Exception as e: raise Conne...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/argilla_callback.html
c630145c3a58-4
" If the problem persists please report it to" " https://github.com/argilla-io/argilla/issues with the label" " `langchain`." ) from e supported_fields = ["prompt", "response"] if supported_fields != [field.name for field in self.dataset.fields]: r...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/argilla_callback.html
c630145c3a58-5
[docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None: """Do nothing when a new token is generated.""" pass [docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Log records to Argilla when an LLM ends.""" # Do nothing if there's a parent_run_id...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/argilla_callback.html
c630145c3a58-6
we don't log the same input prompt twice, once when the LLM starts and once when the chain starts. """ if "input" in inputs: self.prompts.update( { str(kwargs["parent_run_id"] or kwargs["run_id"]): ( inputs["input"] ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/argilla_callback.html
c630145c3a58-7
self.dataset.add_records( records=[ { "fields": { "prompt": " ".join(prompts), # type: ignore "response": chain_output_val.strip(), }, ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/argilla_callback.html
c630145c3a58-8
) -> None: """Do nothing when tool outputs an error.""" pass [docs] def on_text(self, text: str, **kwargs: Any) -> None: """Do nothing""" pass [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Do nothing""" pass
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/argilla_callback.html
aa6f172b81d3-0
Source code for langchain.callbacks.aim_callback from copy import deepcopy from typing import Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult def import_aim() -> Any: """Import the aim python package and raise...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/aim_callback.html
aa6f172b81d3-1
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. agent_ends (int): The number of times the agent end method has been call...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/aim_callback.html
aa6f172b81d3-2
"step": self.step, "starts": self.starts, "ends": self.ends, "errors": self.errors, "text_ctr": self.text_ctr, "chain_starts": self.chain_starts, "chain_ends": self.chain_ends, "llm_starts": self.llm_starts, "llm_ends": self...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/aim_callback.html
aa6f172b81d3-3
'default' if not specified. Can be used later to query runs/sequences. system_tracking_interval (:obj:`int`, optional): Sets the tracking interval in seconds for system usage metrics (CPU, Memory, etc.). Set to `None` to disable system metrics tracking. log_system_params (:obj:`...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/aim_callback.html
aa6f172b81d3-4
repo=self.repo, system_tracking_interval=self.system_tracking_interval, ) else: self._run = aim.Run( repo=self.repo, experiment=self.experiment_name, system_tracking_interval=self.system_tracking_...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/aim_callback.html
aa6f172b81d3-5
for generation in generations ] self._run.track( generated, name="on_llm_end", context=resp, ) [docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None: """Run when LLM generates a new token.""" self.step += 1 self.llm_st...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/aim_callback.html
aa6f172b81d3-6
outputs_res = deepcopy(outputs) self._run.track( aim.Text(outputs_res["output"]), name="on_chain_end", context=resp ) [docs] def on_chain_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: """Run when chain errors.""" self.step +=...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/aim_callback.html
aa6f172b81d3-7
""" Run when agent is ending. """ self.step += 1 self.text_ctr += 1 [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Run when agent ends running.""" aim = import_aim() self.step += 1 self.agent_ends += 1 self.ends...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/aim_callback.html
aa6f172b81d3-8
log_system_params: bool = True, langchain_asset: Any = None, reset: bool = True, finish: bool = False, ) -> None: """Flush the tracker and reset the session. Args: repo (:obj:`str`, optional): Aim repository path or Repo object to which Run object ...
https://api.python.langchain.com/en/stable/_modules/langchain/callbacks/aim_callback.html