id
stringlengths
14
16
text
stringlengths
4
1.28k
source
stringlengths
54
121
0416b27147b9-10
self.mlflow.log_artifact(path) def langchain_artifact(self, chain: Any) -> None: with self.mlflow.start_run( run_id=self.run.info.run_id, experiment_id=self.mlf_expid ): self.mlflow.langchain.log_model(chain, "langchain-model") [docs]class MlflowCallbackHandler(BaseMetadataCa...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-11
and adds the response to the list of records for both the {method}_records and action. It then logs the response to mlflow server. """ def __init__( self, name: Optional[str] = "langchainrun-%", experiment: Optional[str] = "langchain", tags: Optional[Dict] = {}, track...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-12
tracking_uri=self.tracking_uri, experiment_name=self.experiment, run_name=self.name, run_tags=self.tags, ) self.action_records: list = [] self.nlp = spacy.load("en_core_web_sm") self.metrics = { "step": 0, "starts": 0, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-13
"on_llm_start_records": [], "on_llm_token_records": [], "on_llm_end_records": [], "on_chain_start_records": [], "on_chain_end_records": [], "on_tool_start_records": [], "on_tool_end_records": [], "on_text_records": [], "on_a...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-14
"""Run when LLM starts.""" self.metrics["step"] += 1 self.metrics["llm_starts"] += 1 self.metrics["starts"] += 1 llm_starts = self.metrics["llm_starts"] resp: Dict[str, Any] = {} resp.update({"action": "on_llm_start"}) resp.update(flatten_dict(serialized)) ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-15
[docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None: """Run when LLM generates a new token.""" self.metrics["step"] += 1 self.metrics["llm_streams"] += 1 llm_streams = self.metrics["llm_streams"] resp: Dict[str, Any] = {} resp.update({"action": "on_llm...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-16
"""Run when LLM ends running.""" self.metrics["step"] += 1 self.metrics["llm_ends"] += 1 self.metrics["ends"] += 1 llm_ends = self.metrics["llm_ends"] resp: Dict[str, Any] = {} resp.update({"action": "on_llm_end"}) resp.update(flatten_dict(response.llm_output or {...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-17
) ) complexity_metrics: Dict[str, float] = generation_resp.pop("text_complexity_metrics") # type: ignore # noqa: E501 self.mlflg.metrics( complexity_metrics, step=self.metrics["step"], ) self.record...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-18
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: """Run when LLM errors.""" self.metrics["step"] += 1 self.metrics["errors"] += 1 [docs] def on_chain_start( self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any ) -> None: """...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-19
chain_input = ",".join([f"{k}={v}" for k, v in inputs.items()]) input_resp = deepcopy(resp) input_resp["inputs"] = chain_input self.records["on_chain_start_records"].append(input_resp) self.records["action_records"].append(input_resp) self.mlflg.jsonf(input_resp, f"chain_start_{c...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-20
chain_output = ",".join([f"{k}={v}" for k, v in outputs.items()]) resp.update({"action": "on_chain_end", "outputs": chain_output}) resp.update(self.metrics) self.mlflg.metrics(self.metrics, step=self.metrics["step"]) self.records["on_chain_end_records"].append(resp) self.records[...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-21
) -> None: """Run when tool starts running.""" self.metrics["step"] += 1 self.metrics["tool_starts"] += 1 self.metrics["starts"] += 1 tool_starts = self.metrics["tool_starts"] resp: Dict[str, Any] = {} resp.update({"action": "on_tool_start", "input_str": input_str...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-22
"""Run when tool ends running.""" self.metrics["step"] += 1 self.metrics["tool_ends"] += 1 self.metrics["ends"] += 1 tool_ends = self.metrics["tool_ends"] resp: Dict[str, Any] = {} resp.update({"action": "on_tool_end", "output": output}) resp.update(self.metrics) ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-23
self.metrics["step"] += 1 self.metrics["errors"] += 1 [docs] def on_text(self, text: str, **kwargs: Any) -> None: """ Run when agent is ending. """ self.metrics["step"] += 1 self.metrics["text_ctr"] += 1 text_ctr = self.metrics["text_ctr"] resp: Dict[st...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-24
[docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Run when agent ends running.""" self.metrics["step"] += 1 self.metrics["agent_ends"] += 1 self.metrics["ends"] += 1 agent_ends = self.metrics["agent_ends"] resp: Dict[str, Any] = {} ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-25
[docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any: """Run on agent action.""" self.metrics["step"] += 1 self.metrics["tool_starts"] += 1 self.metrics["starts"] += 1 tool_starts = self.metrics["tool_starts"] resp: Dict[str, Any] = {} re...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-26
def _create_session_analysis_df(self) -> Any: """Create a dataframe with all the information from the session.""" pd = import_pandas() on_llm_start_records_df = pd.DataFrame(self.records["on_llm_start_records"]) on_llm_end_records_df = pd.DataFrame(self.records["on_llm_end_records"]) ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-27
"automated_readability_index", "dale_chall_readability_score", "difficult_words", "linsear_write_formula", "gunning_fog", # "text_standard", "fernandez_huerta", "szigriszt_pazos", "gutierrez_polini", "crawford", ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-28
.dropna(axis=1) .rename({"step": "output_step", "text": "output"}, axis=1) ) session_analysis_df = pd.concat([llm_input_prompts_df, llm_outputs_df], axis=1) session_analysis_df["chat_html"] = session_analysis_df[ ["prompt", "output"] ].apply( lambda ro...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-29
chat_html = session_analysis_df.pop("chat_html") chat_html = chat_html.replace("\n", "", regex=True) self.mlflg.table("session_analysis", pd.DataFrame(session_analysis_df)) self.mlflg.html("".join(chat_html.tolist()), "chat_html") if langchain_asset: # To avoid circular impor...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
0416b27147b9-30
self.mlflg.artifact(langchain_asset_path) except AttributeError: print("Could not save model.") traceback.print_exc() pass except NotImplementedError: print("Could not save model.") ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
5ceddaa19b29-0
Source code for langchain.callbacks.argilla_callback import os import warnings from typing import Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult [docs]class ArgillaCallbackHandler(BaseCallbackHandler): """Cal...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-1
default workspace will be used. api_url: URL of the Argilla Server that we want to use, and where the `FeedbackDataset` lives in. Defaults to `None`, which means that either `ARGILLA_API_URL` environment variable or the default http://localhost:6900 will be used. api_...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-2
>>> argilla_callback = ArgillaCallbackHandler( ... dataset_name="my-dataset", ... workspace_name="my-workspace", ... api_url="http://localhost:6900", ... api_key="argilla.apikey", ... ) >>> llm = OpenAI( ... temperature=0, ... callb...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-3
api_url: Optional[str] = None, api_key: Optional[str] = None, ) -> None: """Initializes the `ArgillaCallbackHandler`. Args: dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must exist in advance. If you need help on how to create a `FeedbackDat...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-4
`ARGILLA_API_URL` environment variable or the default http://localhost:6900 will be used. api_key: API Key to connect to the Argilla Server. Defaults to `None`, which means that either `ARGILLA_API_KEY` environment variable or the default `argilla.apikey` will...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-5
"Python package installed. Please install it with `pip install argilla`" ) # Show a warning message if Argilla will assume the default values will be used if api_url is None and os.getenv("ARGILLA_API_URL") is None: warnings.warn( ( "Since `api...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-6
), ) # Connect to Argilla with the provided credentials, if applicable try: rg.init( api_key=api_key, api_url=api_url, ) except Exception as e: raise ConnectionError( f"Could not connect to Argilla wi...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-7
try: self.dataset = rg.FeedbackDataset.from_argilla( name=self.dataset_name, workspace=self.workspace_name, with_records=False, ) except Exception as e: raise FileNotFoundError( "`FeedbackDataset` retrieval from ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-8
" https://github.com/argilla-io/argilla/issues with the label" " `langchain`." ) from e supported_fields = ["prompt", "response"] if supported_fields != [field.name for field in self.dataset.fields]: raise ValueError( f"`FeedbackDataset` with name=...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-9
" https://docs.argilla.io/en/latest/guides/llms/practical_guides/use_argilla_callback_in_langchain.html." # noqa: E501 ) self.prompts: Dict[str, List[str]] = {} warnings.warn( ( "The `ArgillaCallbackHandler` is currently in beta and is subject to " ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-10
self.prompts.update({str(kwargs["parent_run_id"] or kwargs["run_id"]): prompts}) [docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None: """Do nothing when a new token is generated.""" pass [docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Log record...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-11
records=[ { "fields": { "prompt": prompt, "response": generation.text.strip(), }, } for generation in generations ] ) # ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-12
either the `parent_run_id` or the `run_id` as the key. This is done so that we don't log the same input prompt twice, once when the LLM starts and once when the chain starts. """ if "input" in inputs: self.prompts.update( { str(kwargs["pare...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-13
differs if the output is a list or not. """ if not any( key in self.prompts for key in [str(kwargs["parent_run_id"]), str(kwargs["run_id"])] ): return prompts = self.prompts.get(str(kwargs["parent_run_id"])) or self.prompts.get( str(kwargs[...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-14
) ] ) else: # Creates the records and adds them to the `FeedbackDataset` self.dataset.add_records( records=[ { "fields": { "prompt": " "...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-15
) -> None: """Do nothing when LLM chain outputs an error.""" pass [docs] def on_tool_start( self, serialized: Dict[str, Any], input_str: str, **kwargs: Any, ) -> None: """Do nothing when tool starts.""" pass [docs] def on_agent_action(self, actio...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5ceddaa19b29-16
[docs] def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: """Do nothing when tool outputs an error.""" pass [docs] def on_text(self, text: str, **kwargs: Any) -> None: """Do nothing""" pass [docs] def on_agent_finish(self, f...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
5e069f085165-0
Source code for langchain.callbacks.comet_ml_callback import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Sequence, Union import langchain from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.utils import ( BaseMetad...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-1
" `pip install comet_ml`" ) return comet_ml def _get_experiment( workspace: Optional[str] = None, project_name: Optional[str] = None ) -> Any: comet_ml = import_comet_ml() experiment = comet_ml.Experiment( # type: ignore workspace=workspace, project_name=project_name, ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-2
"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": tex...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-3
"gulpease_index": textstat.gulpease_index(text), "osman": textstat.osman(text), } return text_complexity_metrics def _summarize_metrics_for_generated_outputs(metrics: Sequence) -> dict: pd = import_pandas() metrics_df = pd.DataFrame(metrics) metrics_summary = metrics_df.describe() return...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-4
complexity_metrics (bool): Whether to log complexity metrics stream_logs (bool): Whether to stream callback actions to Comet This handler will utilize the associated callback method and formats the input of each callback function with metadata regarding the state of LLM run, and adds the response to...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-5
stream_logs: bool = True, ) -> None: """Initialize callback handler.""" self.comet_ml = import_comet_ml() super().__init__() self.task_type = task_type self.workspace = workspace self.project_name = project_name self.tags = tags self.visualizations = v...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-6
"based on updates to `langchain`. Please report any issues to " "https://github.com/comet-ml/issue-tracking/issues with the tag " "`langchain`." ) self.comet_ml.LOGGER.warning(warning) self.callback_columns: list = [] self.action_records: list = [] self.co...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-7
"""Run when LLM starts.""" self.step += 1 self.llm_starts += 1 self.starts += 1 metadata = self._init_resp() metadata.update({"action": "on_llm_start"}) metadata.update(flatten_dict(serialized)) metadata.update(self.get_custom_callback_meta()) for prompt i...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-8
self.llm_streams += 1 resp = self._init_resp() resp.update({"action": "on_llm_new_token", "token": token}) resp.update(self.get_custom_callback_meta()) self.action_records.append(resp) [docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Run when LLM end...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-9
for gen_idx, generation in enumerate(generations): text = generation.text generation_resp = deepcopy(metadata) generation_resp.update(flatten_dict(generation.dict())) complexity_metrics = self._get_complexity_metrics(text) if complexity_met...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-10
[docs] def on_llm_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: """Run when LLM errors.""" self.step += 1 self.errors += 1 [docs] def on_chain_start( self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any ) -> Non...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-11
input_resp = deepcopy(resp) if self.stream_logs: self._log_stream(chain_input_val, resp, self.step) input_resp.update({chain_input_key: chain_input_val}) self.action_records.append(input_resp) else: self.comet_ml.LOGGER.warn...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-12
if isinstance(chain_output_val, str): output_resp = deepcopy(resp) if self.stream_logs: self._log_stream(chain_output_val, resp, self.step) output_resp.update({chain_output_key: chain_output_val}) self.action_records.append(output_resp)...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-13
) -> None: """Run when tool starts running.""" self.step += 1 self.tool_starts += 1 self.starts += 1 resp = self._init_resp() resp.update({"action": "on_tool_start"}) resp.update(flatten_dict(serialized)) resp.update(self.get_custom_callback_meta()) ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-14
resp.update(self.get_custom_callback_meta()) if self.stream_logs: self._log_stream(output, resp, self.step) resp.update({"output": output}) self.action_records.append(resp) [docs] def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> N...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-15
if self.stream_logs: self._log_stream(text, resp, self.step) resp.update({"text": text}) self.action_records.append(resp) [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Run when agent ends running.""" self.step += 1 self.agent_ends...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-16
self.action_records.append(resp) [docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any: """Run on agent action.""" self.step += 1 self.tool_starts += 1 self.starts += 1 tool = action.tool tool_input = str(action.tool_input) log = action.lo...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-17
Parameters: text (str): The text to analyze. Returns: (dict): A dictionary containing the complexity metrics. """ resp = {} if self.complexity_metrics: text_complexity_metrics = _fetch_text_complexity_metrics(text) resp.update(text_complexi...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-18
if self.custom_metrics: custom_metrics = self.custom_metrics(generation, prompt_idx, gen_idx) resp.update(custom_metrics) return resp [docs] def flush_tracker( self, langchain_asset: Any = None, task_type: Optional[str] = "inference", workspace: Optiona...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-19
Args: name: Name of the preformed session so far so it is identifyable langchain_asset: The langchain asset to save. finish: Whether to finish the run. Returns: None """ self._log_session(langchain_asset) if langchain_asset: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-20
custom_metrics, ) def _log_stream(self, prompt: str, metadata: dict, step: int) -> None: self.experiment.log_text(prompt, metadata=metadata, step=step) def _log_model(self, langchain_asset: Any) -> None: model_parameters = self._get_llm_parameters(langchain_asset) self.experi...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-21
langchain_asset.save_agent(langchain_asset_path) self.experiment.log_model(model_name, str(langchain_asset_path)) else: self.comet_ml.LOGGER.error( f"{e}" " Could not save Langchain Asset " f"for {langchain_asset.__c...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-22
) try: metadata = {"langchain_version": str(langchain.__version__)} # Log the langchain low-level records as a JSON file directly self.experiment.log_asset_data( self.action_records, "langchain-action_records.json", metadata=metadata ) exce...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-23
if not metrics: return metrics_summary = _summarize_metrics_for_generated_outputs(metrics) for key, value in metrics_summary.items(): self.experiment.log_metrics(value, prefix=key, step=step) def _log_visualizations(self, session_df: Any) -> None: if not (self.visuali...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-24
options={"compact": True}, jupyter=False, page=True, ) self.experiment.log_asset_data( html, name=f"langchain-viz-{visualization}-{idx}.html", metadata={"prompt...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-25
complexity_metrics: bool = False, custom_metrics: Optional[Callable] = None, ) -> None: _task_type = task_type if task_type else self.task_type _workspace = workspace if workspace else self.workspace _project_name = project_name if project_name else self.project_name _tags = ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-26
visualizations=_visualizations, complexity_metrics=_complexity_metrics, custom_metrics=_custom_metrics, ) self.reset_callback_meta() self.temp_dir = tempfile.TemporaryDirectory() def _create_session_analysis_dataframe(self, langchain_asset: Any = None) -> dict: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-27
llm_session_df = pd.merge( llm_start_records_df, llm_end_records_df, left_index=True, right_index=True, suffixes=["_llm_start", "_llm_end"], ) return llm_session_df def _get_llm_parameters(self, langchain_asset: Any = None) -> dict: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
5e069f085165-28
except Exception: return {} return llm_parameters
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
89fa09f1071d-0
Source code for langchain.callbacks.streamlit from __future__ import annotations from typing import TYPE_CHECKING, Optional from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.streamlit.streamlit_callback_handler import ( LLMThoughtLabeler as LLMThoughtLabeler, ) from langchain.callbac...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit.html
89fa09f1071d-1
) -> BaseCallbackHandler: """Construct a new StreamlitCallbackHandler. This CallbackHandler is geared towards use with a LangChain Agent; it displays the Agent's LLM and tool-usage "thoughts" inside a series of Streamlit expanders. Parameters ---------- parent_container The `st.container...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit.html
89fa09f1071d-2
collapse_completed_thoughts If True, LLM thought expanders will be collapsed when completed. Defaults to True. thought_labeler An optional custom LLMThoughtLabeler instance. If unspecified, the handler will use the default thought labeling logic. Defaults to None. Returns ---...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit.html
89fa09f1071d-3
from streamlit.external.langchain import ( StreamlitCallbackHandler as OfficialStreamlitCallbackHandler, # type: ignore # noqa: 501 ) return OfficialStreamlitCallbackHandler( parent_container, max_thought_containers=max_thought_containers, expand_new_thou...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit.html
dba41798e94d-0
Source code for langchain.callbacks.streamlit.streamlit_callback_handler """Callback Handler that prints to streamlit.""" from __future__ import annotations from enum import Enum from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-1
HISTORY_EMOJI = ":books:" EXCEPTION_EMOJI = "⚠️" class LLMThoughtState(Enum): # The LLM is thinking about what to do next. We don't know which tool we'll run. THINKING = "THINKING" # The LLM has decided to run a tool. We don't have results from the tool yet. RUNNING_TOOL = "RUNNING_TOOL" # We have r...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-2
"""Return the markdown label for a new LLMThought that doesn't have an associated tool yet. """ return f"{THINKING_EMOJI} **Thinking...**" [docs] def get_tool_label(self, tool: ToolRecord, is_complete: bool) -> str: """Return the label for an LLMThought that has an associated ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-3
emoji = EXCEPTION_EMOJI name = "Parsing error" idx = min([60, len(input)]) input = input[0:idx] if len(tool.input_str) > idx: input = input + "..." input = input.replace("\n", " ") label = f"{emoji} **{name}:** {input}" return label [docs] def g...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-4
a tool. """ return f"{CHECKMARK_EMOJI} **Complete!**" class LLMThought: def __init__( self, parent_container: DeltaGenerator, labeler: LLMThoughtLabeler, expanded: bool, collapse_on_complete: bool, ): self._container = MutableExpander( ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-5
"""The container we're writing into.""" return self._container @property def last_tool(self) -> Optional[ToolRecord]: """The last tool executed by this thought""" return self._last_tool def _reset_llm_token_stream(self) -> None: self._llm_token_stream = "" self._llm_t...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-6
self._llm_token_stream, index=self._llm_token_writer_idx ) def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: # `response` is the concatenation of all the tokens received by the LLM. # If we're receiving streaming tokens from `on_llm_new_token`, this response # data is...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-7
) -> None: # Called with the name of the tool we're about to run (in `serialized[name]`), # and its input. We change our container's label to be the tool name. self._state = LLMThoughtState.RUNNING_TOOL tool_name = serialized["name"] self._last_tool = ToolRecord(name=tool_name, i...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-8
def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: self._container.markdown("**Tool encountered an error...**") self._container.exception(error) def on_agent_action( self, action: AgentAction, color: Optional[str] = None, **kwargs: Any ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-9
"""Finish the thought.""" if final_label is None and self._state == LLMThoughtState.RUNNING_TOOL: assert ( self._last_tool is not None ), "_last_tool should never be null when _state == RUNNING_TOOL" final_label = self._labeler.get_tool_label( ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-10
parent_container: DeltaGenerator, *, max_thought_containers: int = 4, expand_new_thoughts: bool = True, collapse_completed_thoughts: bool = True, thought_labeler: Optional[LLMThoughtLabeler] = None, ): """Create a StreamlitCallbackHandler instance. Parameters ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-11
that expander is expanded by default. Defaults to True. collapse_completed_thoughts If True, LLM thought expanders will be collapsed when completed. Defaults to True. thought_labeler An optional custom LLMThoughtLabeler instance. If unspecified, the handler ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-12
self._thought_labeler = thought_labeler or LLMThoughtLabeler() def _require_current_thought(self) -> LLMThought: """Return our current LLMThought. Raise an error if we have no current thought. """ if self._current_thought is None: raise RuntimeError("Current LLMThought is...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-13
"""The number of 'thought containers' we're currently showing: the number of completed thought containers, the history container (if it exists), and the current thought container (if it exists). """ count = len(self._completed_thoughts) if self._history_container is not None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-14
self._current_thought = None def _prune_old_thought_containers(self) -> None: """If we have too many thoughts onscreen, move older thoughts to the 'history container.' """ while ( self._num_thought_containers > self._max_thought_containers and len(self._comple...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-15
expanded=False, ) oldest_thought = self._completed_thoughts.pop(0) if self._history_container is not None: self._history_container.markdown(oldest_thought.container.label) self._history_container.append_copy(oldest_thought.container) ol...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-16
# We don't prune_old_thought_containers here, because our container won't # be visible until it has a child. def on_llm_new_token(self, token: str, **kwargs: Any) -> None: self._require_current_thought().on_llm_new_token(token, **kwargs) self._prune_old_thought_containers() def on_llm_en...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-17
def on_tool_start( self, serialized: Dict[str, Any], input_str: str, **kwargs: Any ) -> None: self._require_current_thought().on_tool_start(serialized, input_str, **kwargs) self._prune_old_thought_containers() def on_tool_end( self, output: str, color: Optional[st...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-18
) -> None: self._require_current_thought().on_tool_error(error, **kwargs) self._prune_old_thought_containers() def on_text( self, text: str, color: Optional[str] = None, end: str = "", **kwargs: Any, ) -> None: pass def on_chain_start( ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
dba41798e94d-19
pass def on_agent_action( self, action: AgentAction, color: Optional[str] = None, **kwargs: Any ) -> Any: self._require_current_thought().on_agent_action(action, color, **kwargs) self._prune_old_thought_containers() def on_agent_finish( self, finish: AgentFinish, color: Optio...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
26728bf71168-0
Source code for langchain.retrievers.zep from __future__ import annotations from typing import TYPE_CHECKING, Dict, List, Optional from langchain.schema import BaseRetriever, Document if TYPE_CHECKING: from zep_python import MemorySearchResult [docs]class ZepRetriever(BaseRetriever): """A Retriever implementati...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html
26728bf71168-1
For server installation instructions, see: https://getzep.github.io/deployment/quickstart/ """ def __init__( self, session_id: str, url: str, top_k: Optional[int] = None, ): try: from zep_python import ZepClient except ImportError: ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html
26728bf71168-2
page_content=r.message.pop("content"), metadata={"score": r.dist, **r.message}, ) for r in results if r.message ] [docs] def get_relevant_documents( self, query: str, metadata: Optional[Dict] = None ) -> List[Document]: from zep_python i...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html
26728bf71168-3
from zep_python import MemorySearchPayload payload: MemorySearchPayload = MemorySearchPayload( text=query, metadata=metadata ) results: List[MemorySearchResult] = await self.zep_client.asearch_memory( self.session_id, payload, limit=self.top_k ) return sel...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html
808bbf9ed015-0
Source code for langchain.retrievers.chatgpt_plugin_retriever from __future__ import annotations from typing import List, Optional import aiohttp import requests from pydantic import BaseModel from langchain.schema import BaseRetriever, Document [docs]class ChatGPTPluginRetriever(BaseRetriever, BaseModel): url: str...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
808bbf9ed015-1
results = response.json()["results"][0]["results"] docs = [] for d in results: content = d.pop("text") metadata = d.pop("metadata", d) if metadata.get("source_id"): metadata["source"] = metadata.pop("source_id") docs.append(Document(page_co...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
808bbf9ed015-2
) as response: res = await response.json() results = res["results"][0]["results"] docs = [] for d in results: content = d.pop("text") metadata = d.pop("metadata", d) if metadata.get("source_id"): metadata["source"] = metadata.po...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
808bbf9ed015-3
"Content-Type": "application/json", "Authorization": f"Bearer {self.bearer_token}", } return url, json, headers
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
1145c28da0ec-0
Source code for langchain.retrievers.databerry from typing import List, Optional import aiohttp import requests from langchain.schema import BaseRetriever, Document [docs]class DataberryRetriever(BaseRetriever): """Retriever that uses the Databerry API.""" datastore_url: str top_k: Optional[int] api_key...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html