id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
655999c04061-4 | # 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 |
655999c04061-5 | [docs] def on_llm_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Set the error flag."""
self.error = 1
[docs] def on_chain_start(
self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
) -> None:
"""Do nothing w... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html |
655999c04061-6 | 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 |
655999c04061-7 | 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/latest/_modules/langchain/callbacks/infino_callback.html |
2ade66ce795a-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 |
2ade66ce795a-1 | raise_error: bool = True
def __init__(
self,
approve: Callable[[Any], bool] = _default_approve,
should_check: Callable[[Dict[str, Any]], bool] = _default_true,
):
self._approve = approve
self._should_check = should_check
[docs] def on_tool_start(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/human.html |
eb197056c0be-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 |
eb197056c0be-1 | [docs] def check_if_answer_reached(self) -> bool:
if self.strip_tokens:
return self.last_tokens_stripped == self.answer_prefix_tokens_stripped
else:
return self.last_tokens == self.answer_prefix_tokens
def __init__(
self,
*,
answer_prefix_tokens: Op... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout_final_only.html |
eb197056c0be-2 | """
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 |
eb197056c0be-3 | """Run when LLM starts running."""
self.answer_reached = False
[docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
"""Run on new LLM token. Only available when streaming is enabled."""
# Remember the last n tokens, where n = len(answer_prefix_tokens)
self.append_to_l... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout_final_only.html |
030b9aa6a245-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 |
030b9aa6a245-1 | "package installed. Please install it with `pip install wandb`"
)
return wandb
def load_json_to_dict(json_path: Union[str, Path]) -> dict:
"""Load json file to a dictionary.
Parameters:
json_path (str): The path to the json file.
Returns:
(dict): The dictionary representation of ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-2 | 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 |
030b9aa6a245-3 | "coleman_liau_index": textstat.coleman_liau_index(text),
"automated_readability_index": textstat.automated_readability_index(text),
"dale_chall_readability_score": textstat.dale_chall_readability_score(text),
"difficult_words": textstat.difficult_words(text),
"linsear_wri... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-4 | "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( # type: ignore
doc, style="dep", jupyter=F... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-5 | ent_output_path.open("w", encoding="utf-8").write(ent_out)
text_visualizations = {
"dependency_tree": wandb.Html(str(dep_output_path)),
"entities": wandb.Html(str(ent_output_path)),
}
resp.update(text_visualizations)
return resp
def construct_html_from_prompt_and_gene... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-6 | f"""
<p style="color:black;">{formatted_prompt}:</p>
<blockquote>
<p style="color:green;">
{formatted_generation}
</p>
</blockquote>
""",
inject=False,
)
[docs]class WandbCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
"""Callback Handler that logs ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-7 | complexity_metrics (bool): Whether to log complexity metrics.
stream_logs (bool): Whether to stream callback actions to W&B
This handler will utilize the associated callback method called and formats
the input of each callback function with metadata regarding the state of LLM run,
and adds the respo... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-8 | 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()
super().__init__()
self.job_type... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-9 | entity=self.entity,
tags=self.tags,
group=self.group,
name=self.name,
notes=self.notes,
)
warning = (
"DEPRECATION: The `WandbCallbackHandler` will soon be deprecated in favor "
"of the `WandbTracer`. Please update your code to use ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-10 | 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()
resp.update({"action": "on_llm_start"})
resp.update(flatten_dict(serialized)... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-11 | self.step += 1
self.llm_streams += 1
resp = self._init_resp()
resp.update({"action": "on_llm_new_token", "token": token})
resp.update(self.get_custom_callback_meta())
self.on_llm_token_records.append(resp)
self.action_records.append(resp)
if self.stream_logs:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-12 | resp.update(self.get_custom_callback_meta())
for generations in response.generations:
for generation in generations:
generation_resp = deepcopy(resp)
generation_resp.update(flatten_dict(generation.dict()))
generation_resp.update(
an... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-13 | self.errors += 1
[docs] def on_chain_start(
self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
) -> None:
"""Run when chain starts running."""
self.step += 1
self.chain_starts += 1
self.starts += 1
resp = self._init_resp()
resp.update({... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-14 | elif isinstance(chain_input, list):
for inp in chain_input:
input_resp = deepcopy(resp)
input_resp.update(inp)
self.on_chain_start_records.append(input_resp)
self.action_records.append(input_resp)
if self.stream_logs:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-15 | self.action_records.append(resp)
if self.stream_logs:
self.run.log(resp)
[docs] def on_chain_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Run when chain errors."""
self.step += 1
self.errors += 1
[docs] def on_tool_sta... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-16 | 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:
"""Run when tool ends running."""
self.st... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-17 | ) -> None:
"""Run when tool errors."""
self.step += 1
self.errors += 1
[docs] def on_text(self, text: str, **kwargs: Any) -> None:
"""
Run when agent is ending.
"""
self.step += 1
self.text_ctr += 1
resp = self._init_resp()
resp.update({... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-18 | 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_meta())
self.on_agent_... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-19 | "tool": action.tool,
"tool_input": action.tool_input,
"log": action.log,
}
)
resp.update(self.get_custom_callback_meta())
self.on_agent_action_records.append(resp)
self.action_records.append(resp)
if self.stream_logs:
self.r... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-20 | )
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 |
030b9aa6a245-21 | llm_outputs_df = (
on_llm_end_records_df[
[
"step",
"text",
"token_usage_total_tokens",
"token_usage_prompt_tokens",
"token_usage_completion_tokens",
]
+ comple... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-22 | )
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] = None,
tags: Optional[Seque... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-23 | finish: Whether to finish the run.
job_type: The job type.
project: The project.
entity: The entity.
tags: The tags.
group: The group.
name: The name.
notes: The notes.
visualize: Whether to visualize.
complexity... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-24 | )
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, name="session... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
030b9aa6a245-25 | print(repr(e))
pass
self.run.log_artifact(model_artifact)
if finish or reset:
self.run.finish()
self.temp_dir.cleanup()
self.reset_callback_meta()
if reset:
self.__init__( # type: ignore
job_type=job_type if job... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html |
4c220890e33d-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 |
4c220890e33d-1 | self.api_key = API_KEY
self.prompt_records: List[str] = []
self.response_records: List[str] = []
self.prediction_ids: List[str] = []
self.pred_timestamps: List[int] = []
self.response_embeddings: List[float] = []
self.prompt_embeddings: List[float] = []
self.promp... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
4c220890e33d-2 | batch_size=256,
)
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] ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
4c220890e33d-3 | """Do nothing."""
pass
[docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
pd = import_pandas()
from arize.utils.types import (
EmbeddingColumnNames,
Environments,
ModelTypes,
Schema,
)
# Safe check if 'llm_o... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
4c220890e33d-4 | )
else:
self.prompt_tokens = (
self.total_tokens
) = self.completion_tokens = 0 # assign default value
for generations in response.generations:
for generation in generations:
prompt = self.prompt_records[self.step]
self... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
4c220890e33d-5 | columns = [
"prediction_ts",
"response",
"prompt",
"response_vector",
"prompt_vector",
"prompt_token",
"completion_token",
"total_token",
]
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
4c220890e33d-6 | )
schema = Schema(
timestamp_column_name="prediction_ts",
tag_column_names=[
"prompt_token",
"completion_token",
"total_token",
],
prompt_column_names=p... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
4c220890e33d-7 | self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Do nothing."""
pass
[docs] def on_chain_start(
self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
) -> None:
pass
[docs] def on_chain_end(self, outputs: Dict[str, Any], **kwar... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
4c220890e33d-8 | ) -> None:
pass
[docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
"""Do nothing."""
pass
[docs] def on_tool_end(
self,
output: str,
observation_prefix: Optional[str] = None,
llm_prefix: Optional[str] = None,
**kwargs: Any,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html |
6e11bc6cf22f-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 |
6e11bc6cf22f-1 | ends (int): The number of times the end method has been called.
errors (int): The number of times the error method has been called.
text_ctr (int): The number of times the text method has been called.
ignore_llm_ (bool): Whether to ignore llm callbacks.
ignore_chain_ (bool): Whether to i... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-2 | 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 |
6e11bc6cf22f-3 | self.llm_ends = 0
self.llm_streams = 0
self.tool_starts = 0
self.tool_ends = 0
self.agent_ends = 0
@property
def always_verbose(self) -> bool:
"""Whether to call verbose callbacks even if verbose is False."""
return self.always_verbose_
@property
def ignor... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-4 | "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 |
6e11bc6cf22f-5 | self.ignore_llm_ = False
self.ignore_chain_ = False
self.ignore_agent_ = False
self.always_verbose_ = False
self.chain_starts = 0
self.chain_ends = 0
self.llm_starts = 0
self.llm_ends = 0
self.llm_streams = 0
self.tool_starts = 0
self.tool_... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-6 | '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 |
6e11bc6cf22f-7 | ) -> None:
"""Initialize callback handler."""
super().__init__()
aim = import_aim()
self.repo = repo
self.experiment_name = experiment_name
self.system_tracking_interval = system_tracking_interval
self.log_system_params = log_system_params
self._run = aim.... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-8 | 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 |
6e11bc6cf22f-9 | resp.update(self.get_custom_callback_meta())
prompts_res = deepcopy(prompts)
self._run.track(
[aim.Text(prompt) for prompt in prompts_res],
name="on_llm_start",
context=resp,
)
[docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-10 | 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_streams += 1
[docs] def on_llm_error(
self, error: Union[Exception, ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-11 | self.step += 1
self.chain_starts += 1
self.starts += 1
resp = {"action": "on_chain_start"}
resp.update(self.get_custom_callback_meta())
inputs_res = deepcopy(inputs)
self._run.track(
aim.Text(inputs_res["input"]), name="on_chain_start", context=resp
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-12 | 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 += 1
self.errors += 1
[docs] de... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-13 | resp.update(self.get_custom_callback_meta())
self._run.track(aim.Text(input_str), name="on_tool_start", context=resp)
[docs] def on_tool_end(self, output: str, **kwargs: Any) -> None:
"""Run when tool ends running."""
aim = import_aim()
self.step += 1
self.tool_ends += 1
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-14 | 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) -> None:
"""Run when agent ends running."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-15 | )
self._run.track(aim.Text(text), name="on_agent_finish", context=resp)
[docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
"""Run on agent action."""
aim = import_aim()
self.step += 1
self.tool_starts += 1
self.starts += 1
resp = {
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-16 | 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,
) -> None:
"""Flush the tracke... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-17 | in seconds for system usage metrics (CPU, Memory, etc.). Set to `None`
to disable system metrics tracking.
log_system_params (:obj:`bool`, optional): Enable/Disable logging of system
params such as installed packages, git info, environment variables, etc.
langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
6e11bc6cf22f-18 | 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,
log_system_params=log_system_par... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html |
3d30f753ca1d-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 |
3d30f753ca1d-1 | themes: Whether to import the langkit.themes module. Defaults to False.
Returns:
The imported langkit module.
"""
try:
import langkit # noqa: F401
import langkit.regexes # noqa: F401
import langkit.textstat # noqa: F401
if sentiment:
import langkit.sent... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
3d30f753ca1d-2 | """WhyLabs CallbackHandler."""
def __init__(self, logger: Logger):
"""Initiate the rolling logger"""
super().__init__()
self.logger = logger
diagnostic_logger.info(
"Initialized WhyLabs callback handler with configured whylogs Logger."
)
def _profile_generatio... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
3d30f753ca1d-3 | """Pass the generated response to the logger."""
for generations in response.generations:
self._profile_generations(generations)
[docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
"""Do nothing."""
pass
[docs] def on_llm_error(
self, error: Union[Exce... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
3d30f753ca1d-4 | [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:
"""Do nothing."... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
3d30f753ca1d-5 | ) -> None:
"""Do nothing."""
[docs] def on_tool_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Do nothing."""
pass
[docs] def on_text(self, text: str, **kwargs: Any) -> None:
"""Do nothing."""
[docs] def on_agent_finish(
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
3d30f753ca1d-6 | 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:
self.close()
[docs] @classmethod
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
3d30f753ca1d-7 | way to specify the API key is with environment variable
WHYLABS_API_KEY.
org_id (Optional[str]): WhyLabs organization id to write profiles to.
If not set must be specified in environment variable
WHYLABS_DEFAULT_ORG_ID.
dataset_id (Optional[str]): ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
3d30f753ca1d-8 | 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 |
3d30f753ca1d-9 | )
langkit_schema = DeclarativeSchema(generate_udf_schema())
whylabs_logger = why.logger(
mode="rolling", interval=5, when="M", schema=langkit_schema
)
whylabs_logger.append_writer(writer=whylabs_writer)
diagnostic_logger.info(
"Started whylogs Logger with ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html |
93c20d534c8e-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 |
93c20d534c8e-1 | ) -> None:
# If two calls are made in a row, this resets the state
self.done.clear()
[docs] async def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
self.queue.put_nowait(token)
[docs] async def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
self.done.set... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter.html |
93c20d534c8e-2 | 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 |
7e9d83ff53a2-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 |
7e9d83ff53a2-1 | sys.stdout.flush()
[docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
"""Run when LLM ends running."""
[docs] def on_llm_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Run when LLM errors."""
[docs] def on_chain_start(
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout.html |
7e9d83ff53a2-2 | ) -> 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 |
7e9d83ff53a2-3 | """Run on arbitrary text."""
[docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
"""Run on agent end.""" | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout.html |
3696370b4a47-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 |
3696370b4a47-1 | [docs] def on_chain_start(
self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
) -> None:
"""Print out that we are entering a chain."""
class_name = serialized["name"]
print_text(
f"\n\n\033[1m> Entering new {class_name} chain...\033[0m",
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/file.html |
3696370b4a47-2 | [docs] def on_agent_action(
self, action: AgentAction, color: Optional[str] = None, **kwargs: Any
) -> 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: ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/file.html |
3696370b4a47-3 | if llm_prefix is not None:
print_text(f"\n{llm_prefix}", file=self.file)
[docs] def on_text(
self,
text: str,
color: Optional[str] = None,
end: str = "",
**kwargs: Any,
) -> None:
"""Run when agent ends."""
print_text(text, color=color if color ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/file.html |
261117434e88-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 |
261117434e88-1 | """Do nothing."""
pass
[docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
"""Do nothing."""
pass
[docs] def on_llm_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> None:
"""Do nothing."""
pass
[docs] def on_chain_... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/stdout.html |
261117434e88-2 | """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 |
261117434e88-3 | self,
output: str,
color: Optional[str] = None,
observation_prefix: Optional[str] = None,
llm_prefix: Optional[str] = None,
**kwargs: Any,
) -> None:
"""If not the final action, print out observation."""
if observation_prefix is not None:
print_tex... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/stdout.html |
261117434e88-4 | 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 |
0416b27147b9-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 |
0416b27147b9-1 | "package installed. Please install it with `pip install mlflow>=2.3.0`"
)
return mlflow
def analyze_text(
text: str,
nlp: Any = None,
) -> dict:
"""Analyze text using textstat and spacy.
Parameters:
text (str): The text to analyze.
nlp (spacy.lang): The spacy language model t... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
0416b27147b9-2 | "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(text),
"dale_chall_readability_score": textstat.dale_chall_re... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
0416b27147b9-3 | "szigriszt_pazos": textstat.szigriszt_pazos(text),
"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": text_complexity_m... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
0416b27147b9-4 | )
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:
"""Construct an html element from a prompt and a generatio... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
0416b27147b9-5 | """
class MlflowLogger:
"""Callback Handler that logs metrics and artifacts to mlflow server.
Parameters:
name (str): Name of the run.
experiment (str): Name of the experiment.
tags (dict): Tags to be attached for the run.
tracking_uri (str): MLflow tracking server uri.
This ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
0416b27147b9-6 | # > 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(experiment_name)
if self.mlf_exp is not None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
0416b27147b9-7 | name = name.replace("%", rname)
self.run = self.mlflow.MlflowClient().create_run(
self.mlf_expid, run_name=name, tags=tags
)
def finish_run(self) -> None:
"""To finish the run."""
with self.mlflow.start_run(
run_id=self.run.info.run_id, experiment_id=self.mlf_... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
0416b27147b9-8 | ) -> 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_expid
):
self.mlflow.log_metrics(data)
def jsonf(self, data: Dict[str, Any], filename: str) -> None:
"""To log the input data... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
0416b27147b9-9 | """To log the input html string as html file artifact."""
with self.mlflow.start_run(
run_id=self.run.info.run_id, experiment_id=self.mlf_expid
):
self.mlflow.log_text(html, f"{filename}.html")
def text(self, text: str, filename: str) -> None:
"""To log the input text... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.