id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
54
121
5fe6e6d8f65c-4
chain_input = inputs["input"] if isinstance(chain_input, str): input_resp = deepcopy(resp) input_resp["input"] = chain_input self.on_chain_start_records.append(input_resp) self.action_records.append(input_resp) if self.stream_logs: self...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
5fe6e6d8f65c-5
self.step += 1 self.tool_starts += 1 self.starts += 1 resp = self._init_resp() resp.update({"action": "on_tool_start", "input_str": input_str}) resp.update(flatten_dict(serialized)) resp.update(self.get_custom_callback_meta()) self.on_tool_start_records.append(res...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
5fe6e6d8f65c-6
if self.stream_logs: self.logger.report_text(resp) [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Run when agent ends running.""" self.step += 1 self.agent_ends += 1 self.ends += 1 resp = self._init_resp() resp.update( ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
5fe6e6d8f65c-7
""" resp = {} textstat = import_textstat() spacy = import_spacy() if self.complexity_metrics: text_complexity_metrics = { "flesch_reading_ease": textstat.flesch_reading_ease(text), "flesch_kincaid_grade": textstat.flesch_kincaid_grade(text), ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
5fe6e6d8f65c-8
dep_out = spacy.displacy.render( # type: ignore doc, style="dep", jupyter=False, page=True ) dep_output_path = Path( self.temp_dir.name, hash_string(f"dep-{text}") + ".html" ) dep_output_path.open("w", encoding="utf-8").write(dep_out) ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
5fe6e6d8f65c-9
"flesch_kincaid_grade", "smog_index", "coleman_liau_index", "automated_readability_index", "dale_chall_readability_score", "difficult_words", "linsear_write_formula", "gunning_fog", "text_stan...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
5fe6e6d8f65c-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/latest/_modules/langchain/callbacks/clearml_callback.html
5fe6e6d8f65c-11
) output_model.update_weights( weights_filename=str(langchain_asset_path), auto_delete_file=False, target_filename=name, ) except NotImplementedError as e: print("Could not save model.") ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
beaf52c24564-0
Source code for langchain.callbacks.manager from __future__ import annotations import asyncio import functools import logging import os import warnings from contextlib import asynccontextmanager, contextmanager from contextvars import ContextVar from typing import ( Any, AsyncGenerator, Dict, Generator,...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
beaf52c24564-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/latest/_modules/langchain/callbacks/manager.html
2bb75dbc000d-0
Source code for langchain.callbacks.openai_info """Callback Handler that prints to std out.""" from typing import Any, Dict, List from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import LLMResult MODEL_COST_PER_1K_TOKENS = { # GPT-4 input "gpt-4": 0.03, "gpt-4-0314": 0.03, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html
2bb75dbc000d-1
"gpt-3.5-turbo-16k-0613": 0.003, # GPT-3.5 output "gpt-3.5-turbo-completion": 0.002, "gpt-3.5-turbo-0301-completion": 0.002, "gpt-3.5-turbo-0613-completion": 0.002, "gpt-3.5-turbo-16k-completion": 0.004, "gpt-3.5-turbo-16k-0613-completion": 0.004, # Others "gpt-35-turbo": 0.002, # Azure...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html
2bb75dbc000d-2
is_completion: bool = False, ) -> str: """ Standardize the model name to a format that can be used in the OpenAI API. Args: model_name: Model name to standardize. is_completion: Whether the model is used for completion or not. Defaults to False. Returns: Standardized ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html
2bb75dbc000d-3
[docs]class OpenAICallbackHandler(BaseCallbackHandler): """Callback Handler that tracks OpenAI info.""" total_tokens: int = 0 prompt_tokens: int = 0 completion_tokens: int = 0 successful_requests: int = 0 total_cost: float = 0.0 def __repr__(self) -> str: return ( f"Token...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html
2bb75dbc000d-4
prompt_tokens = token_usage.get("prompt_tokens", 0) model_name = standardize_model_name(response.llm_output.get("model_name", "")) if model_name in MODEL_COST_PER_1K_TOKENS: completion_cost = get_openai_token_cost_for_model( model_name, completion_tokens, is_completion=True ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html
cb1b74b447f3-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/latest/_modules/langchain/callbacks/infino_callback.html
cb1b74b447f3-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/latest/_modules/langchain/callbacks/infino_callback.html
cb1b74b447f3-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/latest/_modules/langchain/callbacks/infino_callback.html
cb1b74b447f3-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/latest/_modules/langchain/callbacks/infino_callback.html
35b2b2a31324-0
Source code for langchain.callbacks.human from typing import Any, Callable, Dict, Optional from uuid import UUID from langchain.callbacks.base import BaseCallbackHandler def _default_approve(_input: str) -> bool: msg = ( "Do you approve of the following input? " "Anything except 'Y'/'Yes' (case-inse...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/human.html
62f9a75fcba8-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
62f9a75fcba8-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_stdout_final_only.html
ae9d10aaa559-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
ae9d10aaa559-1
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 visualization files to. Returns: (dict): A dictionary co...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
ae9d10aaa559-2
"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: doc = nlp(text) dep_out = spacy.displacy.render( # typ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
ae9d10aaa559-3
return wandb.Html( f""" <p style="color:black;">{formatted_prompt}:</p> <blockquote> <p style="color:green;"> {formatted_generation} </p> </blockquote> """, inject=False, ) [docs]class WandbCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler): """...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
ae9d10aaa559-4
notes: Optional[str] = None, visualize: bool = False, complexity_metrics: bool = False, stream_logs: bool = False, ) -> None: """Initialize callback handler.""" wandb = import_wandb() import_pandas() import_textstat() spacy = import_spacy() sup...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
ae9d10aaa559-5
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 resp = self._init_resp() ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
ae9d10aaa559-6
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: generation_resp = deepcopy(resp) generation_...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
ae9d10aaa559-7
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_resp.update(inp) self.on_chain_start_records....
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
ae9d10aaa559-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
ae9d10aaa559-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
ae9d10aaa559-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
ae9d10aaa559-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
ae9d10aaa559-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
d027cc07e3dd-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/latest/_modules/langchain/callbacks/arize_callback.html
d027cc07e3dd-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/latest/_modules/langchain/callbacks/arize_callback.html
d027cc07e3dd-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/latest/_modules/langchain/callbacks/arize_callback.html
d027cc07e3dd-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/latest/_modules/langchain/callbacks/arize_callback.html
d027cc07e3dd-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/latest/_modules/langchain/callbacks/arize_callback.html
649364316cd6-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/latest/_modules/langchain/callbacks/aim_callback.html
649364316cd6-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/latest/_modules/langchain/callbacks/aim_callback.html
649364316cd6-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/latest/_modules/langchain/callbacks/aim_callback.html
649364316cd6-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/latest/_modules/langchain/callbacks/aim_callback.html
649364316cd6-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/latest/_modules/langchain/callbacks/aim_callback.html
649364316cd6-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/latest/_modules/langchain/callbacks/aim_callback.html
649364316cd6-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/latest/_modules/langchain/callbacks/aim_callback.html
649364316cd6-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/latest/_modules/langchain/callbacks/aim_callback.html
649364316cd6-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/latest/_modules/langchain/callbacks/aim_callback.html
649364316cd6-9
log_system_params=log_system_params if log_system_params else self.log_system_params, )
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
058163f5341f-0
Source code for langchain.callbacks.whylabs_callback from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, Generation, LLMResult from langchain.u...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
058163f5341f-1
return langkit [docs]class WhyLabsCallbackHandler(BaseCallbackHandler): """WhyLabs CallbackHandler.""" def __init__(self, logger: Logger): """Initiate the rolling logger""" super().__init__() self.logger = logger diagnostic_logger.info( "Initialized WhyLabs callback h...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
058163f5341f-2
"""Do nothing.""" [docs] def on_chain_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: """Do nothing.""" pass [docs] def on_tool_start( self, serialized: Dict[str, Any], input_str: str, **kwargs: Any, ) -> None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
058163f5341f-3
[docs] def close(self) -> None: self.logger.close() diagnostic_logger.info("Closing WhyLabs logger, see you next time!") def __enter__(self) -> WhyLabsCallbackHandler: return self def __exit__( self, exception_type: Any, exception_value: Any, traceback: Any ) -> None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
058163f5341f-4
metric. """ # langkit library will import necessary whylogs libraries import_langkit(sentiment=sentiment, toxicity=toxicity, themes=themes) import whylogs as why from whylogs.api.writer.whylabs import WhyLabsWriter from whylogs.core.schema import DeclarativeSchema ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
c64dbede48f0-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 import LLMResult # TODO If used by two LLM runs in parallel this w...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter.html
c64dbede48f0-1
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()), asyncio.ensure_future(self.done.wait...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter.html
97b544f127d5-0
Source code for langchain.callbacks.streaming_stdout """Callback Handler streams to stdout on new llm token.""" import sys from typing import Any, Dict, List, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult [docs]class StreamingStdOutCallba...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout.html
97b544f127d5-1
) -> None: """Run when chain errors.""" [docs] def on_tool_start( self, serialized: Dict[str, Any], input_str: str, **kwargs: Any ) -> None: """Run when tool starts running.""" [docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any: """Run on agent action."...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout.html
611bde63148b-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.input import print_text from langchain.schema import AgentAction, AgentFinish [docs]class FileCallbackHandle...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/file.html
611bde63148b-1
) -> Any: """Run on agent action.""" print_text(action.log, color=color if color else 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
ecbd189a9b76-0
Source code for langchain.callbacks.stdout """Callback Handler that prints to std out.""" from typing import Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.input import print_text from langchain.schema import AgentAction, AgentFinish, LLMResult [docs]class StdOu...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/stdout.html
ecbd189a9b76-1
"""Print out that we finished a chain.""" print("\n\033[1m> Finished chain.\033[0m") [docs] def on_chain_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: """Do nothing.""" pass [docs] def on_tool_start( self, serialized: Dict[str...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/stdout.html
ecbd189a9b76-2
color: Optional[str] = None, end: str = "", **kwargs: Any, ) -> None: """Run when agent ends.""" print_text(text, color=color if color else self.color, end=end) [docs] def on_agent_finish( self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any ) -> None:...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/stdout.html
6cc2d514820a-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/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-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
6cc2d514820a-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/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-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/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-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/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-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/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-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/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-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/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-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/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-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/latest/_modules/langchain/callbacks/mlflow_callback.html