viruPVS/langchain-docs huggingface dataset:
tokenizer_max_length=512,
            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]    def on_llm_start(
        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
    ) -> None:
        for prompt in prompts:
            self.prompt_records.append(prompt.replace("\n", ""))
[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
        """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_output' and 'token_usage' exist
        if response.llm_output and "token_usage" in response.llm_output:
            self.prompt_tokens = response.llm_output["token_usage"].get(
                "prompt_tokens", 0
            )
            self.total_tokens = response.llm_output["token_usage"].get(
                "total_tokens", 0
            )
            self.completion_tokens = response.llm_output["token_usage"].get(
                "completion_tokens", 0
            )
        else:
            self.prompt_tokens = (
                self.total_tokens
)
        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.step = self.step + 1
                prompt_embedding = pd.Series(
                    self.generator.generate_embeddings(
                        text_col=pd.Series(prompt.replace("\n", " "))
                    ).reset_index(drop=True)
                )
                # Assigning text to response_text instead of response
                response_text = generation.text.replace("\n", " ")
                response_embedding = pd.Series(
                    self.generator.generate_embeddings(
                        text_col=pd.Series(generation.text.replace("\n", " "))
                    ).reset_index(drop=True)
                )
                pred_timestamp = datetime.now().timestamp()
                # Define the columns and data
                columns = [
                    "prediction_ts",
                    "response",
                    "prompt",
                    "response_vector",
                    "prompt_vector",
                    "prompt_token",
                    "completion_token",
                    "total_token",
                ]
                data = [
                    [
                        pred_timestamp,
                        response_text,
                        prompt,
                        response_embedding[0],
                        prompt_embedding[0],
                        self.prompt_tokens,
                        self.total_tokens,
                        self.completion_tokens,
                    ]
                ]
                # Create the DataFrame
                df = pd.DataFrame(data, columns=columns)
                # Declare prompt and response columns
                prompt_columns = EmbeddingColumnNames(
                    vector_column_name="prompt_vector", data_column_name="prompt"
                )
                response_columns = EmbeddingColumnNames(
                    vector_column_name="response_vector", data_column_name="response"
                )
                schema = Schema(
)
                schema = Schema(
                    timestamp_column_name="prediction_ts",
                    tag_column_names=[
                        "prompt_token",
                        "completion_token",
                        "total_token",
                    ],
                    prompt_column_names=prompt_columns,
                    response_column_names=response_columns,
                )
                response_from_arize = self.arize_client.log(
                    dataframe=df,
                    schema=schema,
                    model_id=self.model_id,
                    model_version=self.model_version,
                    model_type=ModelTypes.GENERATIVE_LLM,
                    environment=Environments.PRODUCTION,
                )
                if response_from_arize.status_code == 200:
                    print("✅ Successfully logged data to Arize!")
                else:
                    print(f'❌ Logging failed "{response_from_arize.text}"')
[docs]    def on_llm_error(self, error: BaseException, **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], **kwargs: Any) -> None:
        """Do nothing."""
        pass
[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
        """Do nothing."""
        pass
[docs]    def on_tool_start(
        self,
        serialized: Dict[str, Any],
        input_str: str,
        **kwargs: Any,
    ) -> None:
        pass
[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
        """Do nothing."""
        pass
"""Do nothing."""
        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: BaseException, **kwargs: Any) -> None:
        pass
[docs]    def on_text(self, text: str, **kwargs: Any) -> None:
        pass
[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
        pass
Source code for langchain_community.callbacks.arthur_callback
"""ArthurAI's Callback Handler."""
from __future__ import annotations
import os
import uuid
from collections import defaultdict
from datetime import datetime
from time import time
from typing import TYPE_CHECKING, Any, DefaultDict, Dict, List, Optional
import numpy as np
from langchain_core.agents import AgentAction, AgentFinish
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.outputs import LLMResult
if TYPE_CHECKING:
    import arthurai
    from arthurai.core.models import ArthurModel
PROMPT_TOKENS = "prompt_tokens"
COMPLETION_TOKENS = "completion_tokens"
TOKEN_USAGE = "token_usage"
FINISH_REASON = "finish_reason"
DURATION = "duration"
def _lazy_load_arthur() -> arthurai:
    """Lazy load Arthur."""
    try:
        import arthurai
    except ImportError as e:
        raise ImportError(
            "To use the ArthurCallbackHandler you need the"
            " `arthurai` package. Please install it with"
            " `pip install arthurai`.",
            e,
        )
    return arthurai
[docs]class ArthurCallbackHandler(BaseCallbackHandler):
    """Callback Handler that logs to Arthur platform.
    Arthur helps enterprise teams optimize model operations
    and performance at scale. The Arthur API tracks model
    performance, explainability, and fairness across tabular,
    NLP, and CV models. Our API is model- and platform-agnostic,
    and continuously scales with complex and dynamic enterprise needs.
    To learn more about Arthur, visit our website at
    https://www.arthur.ai/ or read the Arthur docs at
    https://docs.arthur.ai/
    """
https://docs.arthur.ai/
    """
[docs]    def __init__(
        self,
        arthur_model: ArthurModel,
    ) -> None:
        """Initialize callback handler."""
        super().__init__()
        arthurai = _lazy_load_arthur()
        Stage = arthurai.common.constants.Stage
        ValueType = arthurai.common.constants.ValueType
        self.arthur_model = arthur_model
        # save the attributes of this model to be used when preparing
        # inferences to log to Arthur in on_llm_end()
        self.attr_names = set([a.name for a in self.arthur_model.get_attributes()])
        self.input_attr = [
            x
            for x in self.arthur_model.get_attributes()
            if x.stage == Stage.ModelPipelineInput
            and x.value_type == ValueType.Unstructured_Text
        ][0].name
        self.output_attr = [
            x
            for x in self.arthur_model.get_attributes()
            if x.stage == Stage.PredictedValue
            and x.value_type == ValueType.Unstructured_Text
        ][0].name
        self.token_likelihood_attr = None
        if (
            len(
                [
                    x
                    for x in self.arthur_model.get_attributes()
                    if x.value_type == ValueType.TokenLikelihoods
                ]
            )
            > 0
        ):
            self.token_likelihood_attr = [
                x
                for x in self.arthur_model.get_attributes()
                if x.value_type == ValueType.TokenLikelihoods
            ][0].name
        self.run_map: DefaultDict[str, Any] = defaultdict(dict)
[docs]    @classmethod
    def from_credentials(
        cls,
        model_id: str,
def from_credentials(
        cls,
        model_id: str,
        arthur_url: Optional[str] = "https://app.arthur.ai",
        arthur_login: Optional[str] = None,
        arthur_password: Optional[str] = None,
    ) -> ArthurCallbackHandler:
        """Initialize callback handler from Arthur credentials.
        Args:
            model_id (str): The ID of the arthur model to log to.
            arthur_url (str, optional): The URL of the Arthur instance to log to.
                Defaults to "https://app.arthur.ai".
            arthur_login (str, optional): The login to use to connect to Arthur.
                Defaults to None.
            arthur_password (str, optional): The password to use to connect to
                Arthur. Defaults to None.
        Returns:
            ArthurCallbackHandler: The initialized callback handler.
        """
        arthurai = _lazy_load_arthur()
        ArthurAI = arthurai.ArthurAI
        ResponseClientError = arthurai.common.exceptions.ResponseClientError
        # connect to Arthur
        if arthur_login is None:
            try:
                arthur_api_key = os.environ["ARTHUR_API_KEY"]
            except KeyError:
                raise ValueError(
                    "No Arthur authentication provided. Either give"
                    " a login to the ArthurCallbackHandler"
                    " or set an ARTHUR_API_KEY as an environment variable."
                )
            arthur = ArthurAI(url=arthur_url, access_key=arthur_api_key)
        else:
            if arthur_password is None:
                arthur = ArthurAI(url=arthur_url, login=arthur_login)
            else:
                arthur = ArthurAI(
else:
                arthur = ArthurAI(
                    url=arthur_url, login=arthur_login, password=arthur_password
                )
        # get model from Arthur by the provided model ID
        try:
            arthur_model = arthur.get_model(model_id)
        except ResponseClientError:
            raise ValueError(
                f"Was unable to retrieve model with id {model_id} from Arthur."
                " Make sure the ID corresponds to a model that is currently"
                " registered with your Arthur account."
            )
        return cls(arthur_model)
[docs]    def on_llm_start(
        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
    ) -> None:
        """On LLM start, save the input prompts"""
        run_id = kwargs["run_id"]
        self.run_map[run_id]["input_texts"] = prompts
        self.run_map[run_id]["start_time"] = time()
[docs]    def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
        """On LLM end, send data to Arthur."""
        try:
            import pytz  # type: ignore[import]
        except ImportError as e:
            raise ImportError(
                "Could not import pytz. Please install it with 'pip install pytz'."
            ) from e
        run_id = kwargs["run_id"]
        # get the run params from this run ID,
        # or raise an error if this run ID has no corresponding metadata in self.run_map
        try:
            run_map_data = self.run_map[run_id]
        except KeyError as e:
            raise KeyError(
                "This function has been called with a run_id"
raise KeyError(
                "This function has been called with a run_id"
                " that was never registered in on_llm_start()."
                " Restart and try running the LLM again"
            ) from e
        # mark the duration time between on_llm_start() and on_llm_end()
        time_from_start_to_end = time() - run_map_data["start_time"]
        # create inferences to log to Arthur
        inferences = []
        for i, generations in enumerate(response.generations):
            for generation in generations:
                inference = {
                    "partner_inference_id": str(uuid.uuid4()),
                    "inference_timestamp": datetime.now(tz=pytz.UTC),
                    self.input_attr: run_map_data["input_texts"][i],
                    self.output_attr: generation.text,
                }
                if generation.generation_info is not None:
                    # add finish reason to the inference
                    # if generation info contains a finish reason and
                    # if the ArthurModel was registered to monitor finish_reason
                    if (
                        FINISH_REASON in generation.generation_info
                        and FINISH_REASON in self.attr_names
                    ):
                        inference[FINISH_REASON] = generation.generation_info[
                            FINISH_REASON
                        ]
                    # add token likelihoods data to the inference if the ArthurModel
                    # was registered to monitor token likelihoods
                    logprobs_data = generation.generation_info["logprobs"]
                    if (
                        logprobs_data is not None
                        and self.token_likelihood_attr is not None
                    ):
                        logprobs = logprobs_data["top_logprobs"]
                        likelihoods = [
                            {k: np.exp(v) for k, v in logprobs[i].items()}
                            for i in range(len(logprobs))
                        ]
for i in range(len(logprobs))
                        ]
                        inference[self.token_likelihood_attr] = likelihoods
                # add token usage counts to the inference if the
                # ArthurModel was registered to monitor token usage
                if (
                    isinstance(response.llm_output, dict)
                    and TOKEN_USAGE in response.llm_output
                ):
                    token_usage = response.llm_output[TOKEN_USAGE]
                    if (
                        PROMPT_TOKENS in token_usage
                        and PROMPT_TOKENS in self.attr_names
                    ):
                        inference[PROMPT_TOKENS] = token_usage[PROMPT_TOKENS]
                    if (
                        COMPLETION_TOKENS in token_usage
                        and COMPLETION_TOKENS in self.attr_names
                    ):
                        inference[COMPLETION_TOKENS] = token_usage[COMPLETION_TOKENS]
                # add inference duration to the inference if the ArthurModel
                # was registered to monitor inference duration
                if DURATION in self.attr_names:
                    inference[DURATION] = time_from_start_to_end
                inferences.append(inference)
        # send inferences to arthur
        self.arthur_model.send_inferences(inferences)
[docs]    def on_chain_start(
        self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
    ) -> None:
        """On chain start, do nothing."""
[docs]    def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
        """On chain end, do nothing."""
[docs]    def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
        """Do nothing when LLM outputs an error."""
"""Do nothing when LLM outputs an error."""
[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
        """On new token, pass."""
[docs]    def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
        """Do nothing when LLM chain outputs an error."""
[docs]    def on_tool_start(
        self,
        serialized: Dict[str, Any],
        input_str: str,
        **kwargs: Any,
    ) -> None:
        """Do nothing when tool starts."""
[docs]    def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
        """Do nothing when agent takes a specific action."""
[docs]    def on_tool_end(
        self,
        output: str,
        observation_prefix: Optional[str] = None,
        llm_prefix: Optional[str] = None,
        **kwargs: Any,
    ) -> None:
        """Do nothing when tool ends."""
[docs]    def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
        """Do nothing when tool outputs an error."""
[docs]    def on_text(self, text: str, **kwargs: Any) -> None:
        """Do nothing"""
[docs]    def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
        """Do nothing"""
Source code for langchain_community.callbacks.flyte_callback
"""FlyteKit callback handler."""
from __future__ import annotations
import logging
from copy import deepcopy
from typing import TYPE_CHECKING, Any, Dict, List, Tuple
from langchain_core.agents import AgentAction, AgentFinish
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.outputs import LLMResult
from langchain_community.callbacks.utils import (
    BaseMetadataCallbackHandler,
    flatten_dict,
    import_pandas,
    import_spacy,
    import_textstat,
)
if TYPE_CHECKING:
    import flytekit
    from flytekitplugins.deck import renderer
logger = logging.getLogger(__name__)
[docs]def import_flytekit() -> Tuple[flytekit, renderer]:
    """Import flytekit and flytekitplugins-deck-standard."""
    try:
        import flytekit  # noqa: F401
        from flytekitplugins.deck import renderer  # noqa: F401
    except ImportError:
        raise ImportError(
            "To use the flyte callback manager you need"
            "to have the `flytekit` and `flytekitplugins-deck-standard`"
            "packages installed. Please install them with `pip install flytekit`"
            "and `pip install flytekitplugins-deck-standard`."
        )
    return flytekit, renderer
[docs]def analyze_text(
    text: str,
    nlp: Any = None,
    textstat: Any = None,
) -> dict:
    """Analyze text using textstat and spacy.
    Parameters:
        text (str): The text to analyze.
        nlp (spacy.lang): The spacy language model to use for visualization.
    Returns:
Returns:
        (dict): A dictionary containing the complexity metrics and visualization
            files serialized to HTML string.
    """
    resp: Dict[str, Any] = {}
    if textstat is not None:
        text_complexity_metrics = {
            "flesch_reading_ease": textstat.flesch_reading_ease(text),
            "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_readability_score(text),
            "difficult_words": textstat.difficult_words(text),
            "linsear_write_formula": textstat.linsear_write_formula(text),
            "gunning_fog": textstat.gunning_fog(text),
            "fernandez_huerta": textstat.fernandez_huerta(text),
            "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_metrics})
        resp.update(text_complexity_metrics)
    if nlp is not None:
        spacy = import_spacy()
        doc = nlp(text)
        dep_out = spacy.displacy.render(  # type: ignore
dep_out = spacy.displacy.render(  # type: ignore
            doc, style="dep", jupyter=False, page=True
        )
        ent_out = spacy.displacy.render(  # type: ignore
            doc, style="ent", jupyter=False, page=True
        )
        text_visualizations = {
            "dependency_tree": dep_out,
            "entities": ent_out,
        }
        resp.update(text_visualizations)
    return resp
[docs]class FlyteCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
    """This callback handler that is used within a Flyte task."""
[docs]    def __init__(self) -> None:
        """Initialize callback handler."""
        flytekit, renderer = import_flytekit()
        self.pandas = import_pandas()
        self.textstat = None
        try:
            self.textstat = import_textstat()
        except ImportError:
            logger.warning(
                "Textstat library is not installed. \
                It may result in the inability to log \
                certain metrics that can be captured with Textstat."
            )
        spacy = None
        try:
            spacy = import_spacy()
        except ImportError:
            logger.warning(
                "Spacy library is not installed. \
                It may result in the inability to log \
                certain metrics that can be captured with Spacy."
            )
        super().__init__()
        self.nlp = None
        if spacy:
            try:
                self.nlp = spacy.load("en_core_web_sm")
            except OSError:
                logger.warning(
                    "FlyteCallbackHandler uses spacy's en_core_web_sm model"
                    " for certain metrics. To download,"
" for certain metrics. To download,"
                    " run the following command in your terminal:"
                    " `python -m spacy download en_core_web_sm`"
                )
        self.table_renderer = renderer.TableRenderer
        self.markdown_renderer = renderer.MarkdownRenderer
        self.deck = flytekit.Deck(
            "LangChain Metrics",
            self.markdown_renderer().to_html("## LangChain Metrics"),
        )
[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: Dict[str, Any] = {}
        resp.update({"action": "on_llm_start"})
        resp.update(flatten_dict(serialized))
        resp.update(self.get_custom_callback_meta())
        prompt_responses = []
        for prompt in prompts:
            prompt_responses.append(prompt)
        resp.update({"prompts": prompt_responses})
        self.deck.append(self.markdown_renderer().to_html("### LLM Start"))
        self.deck.append(
            self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
        )
[docs]    def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
        """Run when LLM generates a new token."""
[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: Dict[str, Any] = {}