id
stringlengths
14
15
text
stringlengths
49
2.47k
source
stringlengths
61
166
c21d412e1ff1-0
Source code for langchain.document_transformers.doctran_text_translate from typing import Any, Optional, Sequence from langchain.schema import BaseDocumentTransformer, Document from langchain.utils import get_from_env [docs]class DoctranTextTranslator(BaseDocumentTransformer): """Translate text documents using doct...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_translate.html
c21d412e1ff1-1
"""Translates text documents using doctran.""" try: from doctran import Doctran doctran = Doctran( openai_api_key=self.openai_api_key, openai_model=self.openai_api_model ) except ImportError: raise ImportError( "Install doct...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_translate.html
83aef77839a7-0
Source code for langchain.document_transformers.openai_functions """Document transformers that use OpenAI Functions models""" from typing import Any, Dict, Optional, Sequence, Type, Union from pydantic import BaseModel from langchain.chains.llm import LLMChain from langchain.chains.openai_functions import create_taggin...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html
83aef77839a7-1
original_documents = [ Document(page_content="Review of The Bee Movie\nBy Roger Ebert\n\This is the greatest movie ever made. 4 out of 5 stars."), Document(page_content="Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.", metadata={"reliable"...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html
83aef77839a7-2
"""Create a DocumentTransformer that uses an OpenAI function chain to automatically tag documents with metadata based on their content and an input schema. Args: metadata_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary is passed in, it's assumed to already be a v...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html
83aef77839a7-3
original_documents = [ Document(page_content="Review of The Bee Movie\nBy Roger Ebert\n\This is the greatest movie ever made. 4 out of 5 stars."), Document(page_content="Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.", metadata={"reliable"...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html
d3302cc9977e-0
Source code for langchain.document_transformers.doctran_text_extract from typing import Any, List, Optional, Sequence from langchain.schema import BaseDocumentTransformer, Document from langchain.utils import get_from_env [docs]class DoctranPropertyExtractor(BaseDocumentTransformer): """Extract properties from text...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_extract.html
d3302cc9977e-1
transformed_document = await qa_transformer.atransform_documents(documents) """ # noqa: E501 [docs] def __init__( self, properties: List[dict], openai_api_key: Optional[str] = None, openai_api_model: Optional[str] = None, ) -> None: self.properties = properties ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_extract.html
ecc6fad720a8-0
Source code for langchain.document_transformers.html2text from typing import Any, Sequence from langchain.schema import BaseDocumentTransformer, Document [docs]class Html2TextTransformer(BaseDocumentTransformer): """Replace occurrences of a particular search pattern with a replacement string Example: .....
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/html2text.html
43248b67c0b6-0
Source code for langchain.document_transformers.embeddings_redundant_filter """Transform documents""" from typing import Any, Callable, List, Sequence import numpy as np from pydantic import BaseModel, Field from langchain.embeddings.base import Embeddings from langchain.schema import BaseDocumentTransformer, Document ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html
43248b67c0b6-1
redundant_stacked = np.column_stack(redundant) redundant_sorted = np.argsort(similarity[redundant])[::-1] included_idxs = set(range(len(embedded_documents))) for first_idx, second_idx in redundant_stacked[redundant_sorted]: if first_idx in included_idxs and second_idx in included_idxs: #...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html
43248b67c0b6-2
) closest_indices = [] # Loop through the number of clusters you have for i in range(num_clusters): # Get the list of distances from that particular cluster center distances = np.linalg.norm( embedded_documents - kmeans.cluster_centers_[i], axis=1 ) # Find the ind...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html
43248b67c0b6-3
) -> Sequence[Document]: """Filter down documents.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embeddings_from_stateful_docs( self.embeddings, stateful_documents ) included_idxs = _filter_similar_embeddings( embedded...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html
43248b67c0b6-4
""" By default duplicated results are skipped and replaced by the next closest vector in the cluster. If remove_duplicates is true no replacement will be done: This could dramatically reduce results when there is a lot of overlap between clusters. """ class Config: """Configuration for thi...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html
e3148d32a137-0
Source code for langchain.document_transformers.long_context_reorder """Reorder documents""" from typing import Any, List, Sequence from pydantic import BaseModel from langchain.schema import BaseDocumentTransformer, Document def _litm_reordering(documents: List[Document]) -> List[Document]: """Los in the middle re...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/long_context_reorder.html
d2815dbbd993-0
Source code for langchain.document_transformers.doctran_text_qa from typing import Any, Optional, Sequence from langchain.schema import BaseDocumentTransformer, Document from langchain.utils import get_from_env [docs]class DoctranQATransformer(BaseDocumentTransformer): """Extract QA from text documents using doctra...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_qa.html
d2815dbbd993-1
from doctran import Doctran doctran = Doctran( openai_api_key=self.openai_api_key, openai_model=self.openai_api_model ) except ImportError: raise ImportError( "Install doctran to use this parser. (pip install doctran)" ) for...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_qa.html
5689a72b0123-0
Source code for langchain.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, Union import n...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html
5689a72b0123-1
""" [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.ar...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html
5689a72b0123-2
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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html
5689a72b0123-3
) # 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 t...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html
5689a72b0123-4
" 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(respons...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html
5689a72b0123-5
# 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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html
5689a72b0123-6
"""On new token, pass.""" [docs] def on_chain_error( self, error: Union[Exception, KeyboardInterrupt], **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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arthur_callback.html
18dfd1e6cb39-0
Source code for langchain.callbacks.streaming_aiter_final_only from __future__ import annotations from typing import Any, Dict, List, Optional from langchain.callbacks.streaming_aiter import AsyncIteratorCallbackHandler from langchain.schema import LLMResult DEFAULT_ANSWER_PREFIX_TOKENS = ["Final", "Answer", ":"] [docs...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html
18dfd1e6cb39-1
""" super().__init__() if answer_prefix_tokens is None: self.answer_prefix_tokens = DEFAULT_ANSWER_PREFIX_TOKENS else: self.answer_prefix_tokens = answer_prefix_tokens if strip_tokens: self.answer_prefix_tokens_stripped = [ token.strip(...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html
18dfd1e6cb39-2
# If yes, then put tokens from now on if self.answer_reached: self.queue.put_nowait(token)
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_aiter_final_only.html
a1713cd8a3bd-0
Source code for langchain.callbacks.context_callback """Callback handler for Context AI""" import os from typing import Any, Dict, List from uuid import UUID from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import ( BaseMessage, LLMResult, ) [docs]def import_context() -> Any: "...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html
a1713cd8a3bd-1
... ) >>> chat = ChatOpenAI( ... temperature=0, ... headers={"user_id": "123"}, ... callbacks=[context_callback], ... openai_api_key="API_KEY_HERE", ... ) >>> messages = [ ... SystemMessage(content="You translate English to French."), ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html
a1713cd8a3bd-2
( self.context, self.credential, self.conversation_model, self.message_model, self.message_role_model, self.rating_model, ) = import_context() token = token or os.environ.get("CONTEXT_TOKEN") or "" self.client = self.context...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html
a1713cd8a3bd-3
"""Run when LLM ends.""" if len(response.generations) == 0 or len(response.generations[0]) == 0: return if not self.chain_run_id: generation = response.generations[0][0] self.messages.append( self.message_model( message=generation.t...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/context_callback.html
7f2162d15652-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
7f2162d15652-1
reached) stream_prefix: Should answer prefix itself also be streamed? """ 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 str...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streaming_stdout_final_only.html
86cf9e6e837e-0
Source code for langchain.callbacks.sagemaker_callback import json import os import shutil import tempfile from copy import deepcopy from typing import Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.utils import ( flatten_dict, ) from langchain.sch...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html
86cf9e6e837e-1
# Create a temporary directory self.temp_dir = tempfile.mkdtemp() def _reset(self) -> None: for k, v in self.metrics.items(): self.metrics[k] = 0 [docs] def on_llm_start( self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any ) -> None: """Run when LLM...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html
86cf9e6e837e-2
[docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html
86cf9e6e837e-3
resp.update(flatten_dict(serialized)) resp.update(self.metrics) chain_input = ",".join([f"{k}={v}" for k, v in inputs.items()]) input_resp = deepcopy(resp) input_resp["inputs"] = chain_input self.jsonf(input_resp, self.temp_dir, f"chain_start_{chain_starts}") [docs] def on_cha...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html
86cf9e6e837e-4
resp: Dict[str, Any] = {} resp.update({"action": "on_tool_start", "input_str": input_str}) resp.update(flatten_dict(serialized)) resp.update(self.metrics) self.jsonf(resp, self.temp_dir, f"tool_start_{tool_starts}") [docs] def on_tool_end(self, output: str, **kwargs: Any) -> None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html
86cf9e6e837e-5
"""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] = {} resp.update( { "action": "on_agent_finish", ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html
86cf9e6e837e-6
save_json(data, file_path) self.run.log_file(file_path, name=filename, is_output=is_output) [docs] def flush_tracker(self) -> None: """Reset the steps and delete the temporary local directory.""" self._reset() shutil.rmtree(self.temp_dir)
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html
1bc9f68bd948-0
Source code for langchain.callbacks.base """Base callback handler that can be used to handle callbacks in langchain.""" from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union from uuid import UUID if TYPE_CHECKING: from langchain.schema.agent import AgentActi...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
1bc9f68bd948-1
response: LLMResult, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any, ) -> Any: """Run when LLM ends running.""" [docs] def on_llm_error( self, error: Union[Exception, KeyboardInterrupt], *, run_id: UUID, parent_...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
1bc9f68bd948-2
**kwargs: Any, ) -> Any: """Run on agent end.""" [docs]class ToolManagerMixin: """Mixin for tool callbacks.""" [docs] def on_tool_end( self, output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any, ) -> Any: """Run ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
1bc9f68bd948-3
) -> Any: """Run when a chat model starts running.""" raise NotImplementedError( f"{self.__class__.__name__} does not implement `on_chat_model_start`" ) [docs] def on_retriever_start( self, serialized: Dict[str, Any], query: str, *, run_id: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
1bc9f68bd948-4
self, text: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any, ) -> Any: """Run on arbitrary text.""" [docs]class BaseCallbackHandler( LLMManagerMixin, ChainManagerMixin, ToolManagerMixin, RetrieverManagerMixin, CallbackMana...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
1bc9f68bd948-5
tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> None: """Run when LLM starts running.""" [docs] async def on_chat_model_start( self, serialized: Dict[str, Any], messages: List[List[BaseMessage]], *, r...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
1bc9f68bd948-6
error: Union[Exception, KeyboardInterrupt], *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any, ) -> None: """Run when LLM errors.""" [docs] async def on_chain_start( self, serialized: Dict[str, An...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
1bc9f68bd948-7
tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> None: """Run when tool starts running.""" [docs] async def on_tool_end( self, output: str, *, run_id: UUID, parent_run_id: Optional[UUID] = None, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
1bc9f68bd948-8
finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, **kwargs: Any, ) -> None: """Run on agent end.""" [docs] async def on_retriever_start( self, serialized: Dict[str, Any], query: str...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
1bc9f68bd948-9
inheritable_handlers: Optional[List[BaseCallbackHandler]] = None, parent_run_id: Optional[UUID] = None, *, tags: Optional[List[str]] = None, inheritable_tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, inheritable_metadata: Optional[Dict[str, A...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
1bc9f68bd948-10
"""Set handlers as the only handlers on the callback manager.""" self.handlers = [] self.inheritable_handlers = [] for handler in handlers: self.add_handler(handler, inherit=inherit) [docs] def set_handler(self, handler: BaseCallbackHandler, inherit: bool = True) -> None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/base.html
efd28c4c050e-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
efd28c4c050e-1
self.arize_client = Client(space_key=SPACE_KEY, api_key=API_KEY) if SPACE_KEY == "SPACE_KEY" or API_KEY == "API_KEY": raise ValueError("❌ CHANGE SPACE AND API KEYS") else: print("✅ Arize client setup done! Now you can start using Arize!") [docs] def on_llm_start( self,...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html
efd28c4c050e-2
for generations in response.generations: for generation in generations: prompt = self.prompt_records[self.step] self.step = self.step + 1 prompt_embedding = pd.Series( self.generator.generate_embeddings( text_col=pd....
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html
efd28c4c050e-3
"completion_token", "total_token", ], prompt_column_names=prompt_columns, response_column_names=response_columns, ) response_from_arize = self.arize_client.log( dataframe=df, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html
efd28c4c050e-4
pass [docs] def on_tool_end( self, output: str, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None, **kwargs: Any, ) -> None: pass [docs] def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/arize_callback.html
78ff214d00ae-0
Source code for langchain.callbacks.mlflow_callback import os 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...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-1
"flesch_reading_ease": textstat.flesch_reading_ease(text), "flesch_kincaid_grade": textstat.flesch_kincaid_grade(text), "smog_index": textstat.smog_index(text), "coleman_liau_index": textstat.coleman_liau_index(text), "automated_readability_index": textstat.automated_readability_index(te...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-2
doc, style="ent", jupyter=False, page=True ) text_visualizations = { "dependency_tree": dep_out, "entities": ent_out, } resp.update(text_visualizations) return resp [docs]def construct_html_from_prompt_and_generation(prompt: str, generation: str) -> Any: "...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-3
self.mlf_expid = self.mlflow.tracking.fluent._get_experiment_id() self.mlf_exp = self.mlflow.get_experiment(self.mlf_expid) else: tracking_uri = get_from_dict_or_env( kwargs, "tracking_uri", "MLFLOW_TRACKING_URI", "" ) self.mlflow.set_tracking_uri(...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-4
): self.mlflow.end_run() [docs] def metric(self, key: str, value: float) -> None: """To log metric to mlflow server.""" with self.mlflow.start_run( run_id=self.run.info.run_id, experiment_id=self.mlf_expid ): self.mlflow.log_metric(key, value) [docs] def...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-5
): self.mlflow.log_text(html, f"{filename}.html") [docs] def text(self, text: str, filename: str) -> None: """To log the input text as text file artifact.""" with self.mlflow.start_run( run_id=self.run.info.run_id, experiment_id=self.mlf_expid ): self.mlflo...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-6
""" [docs] def __init__( self, name: Optional[str] = "langchainrun-%", experiment: Optional[str] = "langchain", tags: Optional[Dict] = {}, tracking_uri: Optional[str] = None, ) -> None: """Initialize callback handler.""" import_pandas() import_texts...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-7
"on_llm_end_records": [], "on_chain_start_records": [], "on_chain_end_records": [], "on_tool_start_records": [], "on_tool_end_records": [], "on_text_records": [], "on_agent_finish_records": [], "on_agent_action_records": [], ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-8
"""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_new_token", "token": token}) resp.update(self.metrics) self.mlfl...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-9
self.mlflg.metrics( complexity_metrics, step=self.metrics["step"], ) self.records["on_llm_end_records"].append(generation_resp) self.records["action_records"].append(generation_resp) self.mlflg.jsonf(resp, f"llm_end_...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-10
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_{chain_starts}") [docs] def on_chain_end(self, outputs: Dict[str, Any],...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-11
self.metrics["starts"] += 1 tool_starts = self.metrics["tool_starts"] resp: Dict[str, Any] = {} resp.update({"action": "on_tool_start", "input_str": input_str}) resp.update(flatten_dict(serialized)) resp.update(self.metrics) self.mlflg.metrics(self.metrics, step=self.metr...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-12
""" self.metrics["step"] += 1 self.metrics["text_ctr"] += 1 text_ctr = self.metrics["text_ctr"] resp: Dict[str, Any] = {} resp.update({"action": "on_text", "text": text}) resp.update(self.metrics) self.mlflg.metrics(self.metrics, step=self.metrics["step"]) ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-13
tool_starts = self.metrics["tool_starts"] resp: Dict[str, Any] = {} resp.update( { "action": "on_agent_action", "tool": action.tool, "tool_input": action.tool_input, "log": action.log, } ) resp.update...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-14
.rename({"step": "prompt_step"}, axis=1) ) complexity_metrics_columns = [] visualizations_columns = [] complexity_metrics_columns = [ "flesch_reading_ease", "flesch_kincaid_grade", "smog_index", "coleman_liau_index", "automated_...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
78ff214d00ae-15
), axis=1, ) return session_analysis_df [docs] def flush_tracker(self, langchain_asset: Any = None, finish: bool = False) -> None: pd = import_pandas() self.mlflg.table("action_records", pd.DataFrame(self.records["action_records"])) session_analysis_df = self._crea...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
a0c6a7c808d4-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
a0c6a7c808d4-1
>>> argilla_callback = ArgillaCallbackHandler( ... dataset_name="my-dataset", ... workspace_name="my-workspace", ... api_url="http://localhost:6900", ... api_key="argilla.apikey", ... ) >>> llm = OpenAI( ... temperature=0, ... callb...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
a0c6a7c808d4-2
`FeedbackDataset` lives in. Defaults to `None`, which means that either `ARGILLA_API_URL` environment variable or the default http://localhost:6900 will be used. api_key: API Key to connect to the Argilla Server. Defaults to `None`, which means that either `AR...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
a0c6a7c808d4-3
" set, it will default to `argilla.apikey`." ), ) # Connect to Argilla with the provided credentials, if applicable try: rg.init( api_key=api_key, api_url=api_url, ) except Exception as e: raise Conne...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
a0c6a7c808d4-4
" If the problem persists please report it to" " https://github.com/argilla-io/argilla/issues with the label" " `langchain`." ) from e supported_fields = ["prompt", "response"] if supported_fields != [field.name for field in self.dataset.fields]: r...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
a0c6a7c808d4-5
[docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None: """Do nothing when a new token is generated.""" pass [docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Log records to Argilla when an LLM ends.""" # Do nothing if there's a parent_run_id...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
a0c6a7c808d4-6
we don't log the same input prompt twice, once when the LLM starts and once when the chain starts. """ if "input" in inputs: self.prompts.update( { str(kwargs["parent_run_id"] or kwargs["run_id"]): ( inputs["input"] ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
a0c6a7c808d4-7
self.dataset.add_records( records=[ { "fields": { "prompt": " ".join(prompts), # type: ignore "response": chain_output_val.strip(), }, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
a0c6a7c808d4-8
) -> None: """Do nothing when tool outputs an error.""" pass [docs] def on_text(self, text: str, **kwargs: Any) -> None: """Do nothing""" pass [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Do nothing""" pass
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
e1a4bfce8eda-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
e1a4bfce8eda-1
Parameters: text (str): The text to analyze. 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 visuali...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e1a4bfce8eda-2
"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) if visualize and nlp and output_dir is not None: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e1a4bfce8eda-3
formatted_prompt = prompt.replace("\n", "<br>") formatted_generation = generation.replace("\n", "<br>") return wandb.Html( f""" <p style="color:black;">{formatted_prompt}:</p> <blockquote> <p style="color:green;"> {formatted_generation} </p> </blockquote> """, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e1a4bfce8eda-4
group: Optional[str] = None, name: Optional[str] = None, notes: Optional[str] = None, visualize: bool = False, complexity_metrics: bool = False, stream_logs: bool = False, ) -> None: """Initialize callback handler.""" wandb = import_wandb() import_pand...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e1a4bfce8eda-5
def _init_resp(self) -> Dict: return {k: None for k in self.callback_columns} [docs] def on_llm_start( self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any ) -> None: """Run when LLM starts.""" self.step += 1 self.llm_starts += 1 self.starts += 1 ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e1a4bfce8eda-6
self.ends += 1 resp = self._init_resp() resp.update({"action": "on_llm_end"}) resp.update(flatten_dict(response.llm_output or {})) resp.update(self.get_custom_callback_meta()) for generations in response.generations: for generation in generations: gene...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e1a4bfce8eda-7
self.on_chain_start_records.append(input_resp) self.action_records.append(input_resp) if self.stream_logs: self.run.log(input_resp) elif isinstance(chain_input, list): for inp in chain_input: input_resp = deepcopy(resp) input_re...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e1a4bfce8eda-8
resp.update({"action": "on_tool_start", "input_str": input_str}) resp.update(flatten_dict(serialized)) resp.update(self.get_custom_callback_meta()) self.on_tool_start_records.append(resp) self.action_records.append(resp) if self.stream_logs: self.run.log(resp) [docs] ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e1a4bfce8eda-9
"""Run when agent ends running.""" self.step += 1 self.agent_ends += 1 self.ends += 1 resp = self._init_resp() resp.update( { "action": "on_agent_finish", "output": finish.return_values["output"], "log": finish.log, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e1a4bfce8eda-10
.dropna(axis=1) .rename({"step": "prompt_step"}, axis=1) ) complexity_metrics_columns = [] visualizations_columns = [] if self.complexity_metrics: complexity_metrics_columns = [ "flesch_reading_ease", "flesch_kincaid_grade", ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e1a4bfce8eda-11
row["prompts"], row["output"] ), axis=1, ) return session_analysis_df [docs] def flush_tracker( self, langchain_asset: Any = None, reset: bool = True, finish: bool = False, job_type: Optional[str] = None, project: Optional[str] =...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e1a4bfce8eda-12
} ) if langchain_asset: langchain_asset_path = Path(self.temp_dir.name, "model.json") model_artifact = wandb.Artifact(name="model", type="model") model_artifact.add(action_records_table, name="action_records") model_artifact.add(session_analysis_table, nam...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/wandb_callback.html
e13a71a3d9d2-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 [docs]def import_aim() -> Any: """Import the aim python package and...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
e13a71a3d9d2-1
llm_ends (int): The number of times the llm end method has been called. 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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
e13a71a3d9d2-2
"""Whether to ignore agent callbacks.""" return self.ignore_agent_ @property def ignore_retriever(self) -> bool: """Whether to ignore retriever callbacks.""" return self.ignore_retriever_ [docs] def get_custom_callback_meta(self) -> Dict[str, Any]: return { "step":...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
e13a71a3d9d2-3
"""Callback Handler that logs to Aim. Parameters: repo (:obj:`str`, optional): Aim repository path or Repo object to which Run object is bound. If skipped, default Repo is used. experiment_name (:obj:`str`, optional): Sets Run's `experiment` property. 'default' if not specifi...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
e13a71a3d9d2-4
self._run_hash = self._run.hash self.action_records: list = [] [docs] def setup(self, **kwargs: Any) -> None: aim = import_aim() if not self._run: if self._run_hash: self._run = aim.Run( self._run_hash, repo=self.repo, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
e13a71a3d9d2-5
self.llm_ends += 1 self.ends += 1 resp = {"action": "on_llm_end"} resp.update(self.get_custom_callback_meta()) response_res = deepcopy(response) generated = [ aim.Text(generation.text) for generations in response_res.generations for generation ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html