id
stringlengths
14
15
text
stringlengths
44
2.47k
source
stringlengths
61
181
076e04903e55-6
self.payload[run_id] = {"prompts": prompts, "kwargs": kwargs} def _get_message_role(self, message: BaseMessage) -> str: """Get the role of the message.""" if isinstance(message, ChatMessage): return message.role else: return message.__class__.__name__ [docs] def on...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html
076e04903e55-7
"run_id": run_id, "parent_run_id": parent_run_id, "kwargs": kwargs, } [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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html
076e04903e55-8
"""Do nothing when agent takes a specific action.""" pass [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.""" pass [docs] ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/labelstudio_callback.html
7b2f031dc873-0
Source code for langchain.callbacks.promptlayer_callback """Callback handler for promptlayer.""" from __future__ import annotations import datetime from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple from uuid import UUID from langchain.callbacks.base import BaseCallbackHandler from langchain.s...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html
7b2f031dc873-1
tags: Optional[List[str]] = None, **kwargs: Any, ) -> Any: self.runs[run_id] = { "messages": [self._create_message_dicts(m)[0] for m in messages], "invocation_params": kwargs.get("invocation_params", {}), "name": ".".join(serialized["id"]), "request_st...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html
7b2f031dc873-2
generation = response.generations[i][0] resp = { "text": generation.text, "llm_output": response.llm_output, } model_params = run_info.get("invocation_params", {}) is_chat_model = run_info.get("messages", None) is not None model...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html
7b2f031dc873-3
elif isinstance(message, SystemMessage): message_dict = {"role": "system", "content": message.content} elif isinstance(message, ChatMessage): message_dict = {"role": message.role, "content": message.content} else: raise ValueError(f"Got unknown type {message}") ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html
6c87e5f00f8d-0
Source code for langchain.callbacks.infino_callback import time from typing import Any, Dict, List, Optional from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult [docs]def import_infino() -> Any: """Import the infino client.""" try: fr...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html
6c87e5f00f8d-1
key: value, "labels": { "model_id": self.model_id, "model_version": self.model_version, }, } if self.verbose: print(f"Tracking {key} with Infino: {payload}") # Append to Infino time series only if is_ts is True, otherwise ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html
6c87e5f00f8d-2
self._send_to_infino("latency", duration) # Track success or error flag. self._send_to_infino("error", self.error) # Track token usage. if (response.llm_output is not None) and isinstance(response.llm_output, Dict): token_usage = response.llm_output["token_usage"] ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html
6c87e5f00f8d-3
self, serialized: Dict[str, Any], input_str: str, **kwargs: Any, ) -> None: """Do nothing when tool starts.""" pass [docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any: """Do nothing when agent takes a specific action.""" pass [docs]...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/infino_callback.html
1a40a56df824-0
Source code for langchain.callbacks.whylabs_callback from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Optional from langchain.callbacks.base import BaseCallbackHandler from langchain.utils import get_from_env if TYPE_CHECKING: from whylogs.api.logger.logger import Logger diag...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
1a40a56df824-1
""" Callback Handler for logging to WhyLabs. This callback handler utilizes `langkit` to extract features from the prompts & responses when interacting with an LLM. These features can be used to guardrail, evaluate, and observe interactions over time to detect issues relating to hallucinations, prompt e...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
1a40a56df824-2
Optional because the preferred way to specify the dataset id is with environment variable WHYLABS_DEFAULT_DATASET_ID. sentiment (bool): Whether to enable sentiment analysis. Defaults to False. toxicity (bool): Whether to enable toxicity analysis. Defaults to False. themes (bool): Whe...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
1a40a56df824-3
[docs] @classmethod def from_params( cls, *, api_key: Optional[str] = None, org_id: Optional[str] = None, dataset_id: Optional[str] = None, sentiment: bool = False, toxicity: bool = False, themes: bool = False, logger: Optional[Logger] = Non...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
1a40a56df824-4
import whylogs as why from langkit.callback_handler import get_callback_instance from whylogs.api.writer.whylabs import WhyLabsWriter from whylogs.experimental.core.udf_schema import udf_schema if logger is None: api_key = api_key or get_from_env("api_key", "WHYLABS_API_KEY")...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/whylabs_callback.html
3ebdbfd4f159-0
Source code for langchain.callbacks.manager from __future__ import annotations import asyncio import functools import logging import os import uuid from concurrent.futures import ThreadPoolExecutor from contextlib import asynccontextmanager, contextmanager from contextvars import ContextVar from typing import ( TYP...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-1
"openai_callback", default=None ) tracing_callback_var: ContextVar[ Optional[LangChainTracerV1] ] = ContextVar( # noqa: E501 "tracing_callback", default=None ) wandb_tracing_callback_var: ContextVar[ Optional[WandbTracer] ] = ContextVar( # noqa: E501 "tracing_wandb_callback", default=None ) tracing_v2...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-2
"""Get the Deprecated LangChainTracer in a context manager. Args: session_name (str, optional): The name of the session. Defaults to "default". Returns: TracerSessionV1: The LangChainTracer session. Example: >>> with tracing_enabled() as session: ... # Use the L...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-3
Args: project_name (str, optional): The name of the project. Defaults to "default". example_id (str or UUID, optional): The ID of the example. Defaults to None. tags (List[str], optional): The tags to add to the run. Defaults to None. Returns: None...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-4
example_id: Optional[Union[str, UUID]] = None, run_id: Optional[UUID] = None, tags: Optional[List[str]] = None, ) -> Generator[CallbackManagerForChainGroup, None, None]: """Get a callback manager for a chain group in a context manager. Useful for grouping different calls together as a single run even if...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-5
] if callback_manager is None else callback_manager, ) cm = CallbackManager.configure( inheritable_callbacks=cb, inheritable_tags=tags, ) run_manager = cm.on_chain_start({"name": group_name}, inputs or {}, run_id=run_id) child_cm = run_manager.get_child() group_cm...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-6
they aren't composed in a single chain. Args: group_name (str): The name of the chain group. callback_manager (AsyncCallbackManager, optional): The async callback manager to use, which manages tracing and other callback behavior. project_name (str, optional): The name of the proj...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-7
child_cm.handlers, child_cm.inheritable_handlers, child_cm.parent_run_id, parent_run_manager=run_manager, tags=child_cm.tags, inheritable_tags=child_cm.inheritable_tags, metadata=child_cm.metadata, inheritable_metadata=child_cm.inheritable_metadata, ) try:...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-8
*args[2:], **kwargs, ) else: handler_name = handler.__class__.__name__ logger.warning( f"NotImplementedError in {handler_name}.{event_name}" f" callback: {e}" ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-9
for coro in coros: runner.run(coro) # Run pending tasks scheduled by coros until they are all done while pending := asyncio.all_tasks(runner.get_loop()): runner.run(asyncio.wait(pending)) else: # Before Python 3.11 we need to run each coroutine in a ne...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-10
f" callback: {e}" ) except Exception as e: logger.warning( f"Error in {handler.__class__.__name__}.{event_name} callback: {e}" ) if handler.raise_error: raise e async def _ahandle_event( handlers: List[BaseCallbackHandler], event_name: str, ign...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-11
) -> None: """Initialize the run manager. Args: run_id (UUID): The ID of the run. handlers (List[BaseCallbackHandler]): The list of handlers. inheritable_handlers (List[BaseCallbackHandler]): The list of inheritable handlers. parent_run_id ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-12
) -> Any: """Run when text is received. Args: text (str): The received text. Returns: Any: The result of the callback. """ _handle_event( self.handlers, "on_text", None, text, run_id=self.run_id, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-13
[docs] async def on_text( self, text: str, **kwargs: Any, ) -> Any: """Run when text is received. Args: text (str): The received text. Returns: Any: The result of the callback. """ await _ahandle_event( self.handl...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-14
manager.add_tags([tag], False) return manager [docs]class CallbackManagerForLLMRun(RunManager, LLMManagerMixin): """Callback manager for LLM run.""" [docs] def on_llm_new_token( self, token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-15
_handle_event( self.handlers, "on_llm_error", "ignore_llm", error, run_id=self.run_id, parent_run_id=self.parent_run_id, tags=self.tags, **kwargs, ) [docs]class AsyncCallbackManagerForLLMRun(AsyncRunManager, LLMManag...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-16
self, error: BaseException, **kwargs: Any, ) -> None: """Run when LLM errors. Args: error (Exception or KeyboardInterrupt): The error. """ await _ahandle_event( self.handlers, "on_llm_error", "ignore_llm", er...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-17
tags=self.tags, **kwargs, ) [docs] def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any: """Run when agent action is received. Args: action (AgentAction): The agent action. Returns: Any: The result of the callback. """ ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-18
"on_chain_end", "ignore_chain", outputs, run_id=self.run_id, parent_run_id=self.parent_run_id, tags=self.tags, **kwargs, ) [docs] async def on_chain_error( self, error: BaseException, **kwargs: Any, ) -> None:...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-19
"on_agent_finish", "ignore_agent", finish, run_id=self.run_id, parent_run_id=self.parent_run_id, tags=self.tags, **kwargs, ) [docs]class CallbackManagerForToolRun(ParentRunManager, ToolManagerMixin): """Callback manager for tool run."""...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-20
Args: output (str): The output of the tool. """ await _ahandle_event( self.handlers, "on_tool_end", "ignore_agent", output, run_id=self.run_id, parent_run_id=self.parent_run_id, tags=self.tags, **...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-21
"""Run when retriever errors.""" _handle_event( self.handlers, "on_retriever_error", "ignore_retriever", error, run_id=self.run_id, parent_run_id=self.parent_run_id, tags=self.tags, **kwargs, ) [docs]class As...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-22
prompts: List[str], **kwargs: Any, ) -> List[CallbackManagerForLLMRun]: """Run when LLM starts running. Args: serialized (Dict[str, Any]): The serialized LLM. prompts (List[str]): The list of prompts. run_id (UUID, optional): The ID of the run. Defaults to...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-23
Args: serialized (Dict[str, Any]): The serialized LLM. messages (List[List[BaseMessage]]): The list of messages. run_id (UUID, optional): The ID of the run. Defaults to None. Returns: List[CallbackManagerForLLMRun]: A callback manager for each list...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-24
inputs (Union[Dict[str, Any], Any]): The inputs to the chain. run_id (UUID, optional): The ID of the run. Defaults to None. Returns: CallbackManagerForChainRun: The callback manager for the chain run. """ if run_id is None: run_id = uuid.uuid4() _handl...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-25
Returns: CallbackManagerForToolRun: The callback manager for the tool run. """ if run_id is None: run_id = uuid.uuid4() _handle_event( self.handlers, "on_tool_start", "ignore_agent", serialized, input_str, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-26
run_id=run_id, handlers=self.handlers, inheritable_handlers=self.inheritable_handlers, parent_run_id=self.parent_run_id, tags=self.tags, inheritable_tags=self.inheritable_tags, metadata=self.metadata, inheritable_metadata=self.inheritab...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-27
local_callbacks, verbose, inheritable_tags, local_tags, inheritable_metadata, local_metadata, ) [docs]class CallbackManagerForChainGroup(CallbackManager): [docs] def __init__( self, handlers: List[BaseCallbackHandler], inheri...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-28
"""Return whether the handler is async.""" return True [docs] async def on_llm_start( self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any, ) -> List[AsyncCallbackManagerForLLMRun]: """Run when LLM starts running. Args: serialized...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-29
return managers [docs] async def on_chat_model_start( self, serialized: Dict[str, Any], messages: List[List[BaseMessage]], **kwargs: Any, ) -> List[AsyncCallbackManagerForLLMRun]: """Run when LLM starts running. Args: serialized (Dict[str, Any]): The se...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-30
return managers [docs] async def on_chain_start( self, serialized: Dict[str, Any], inputs: Union[Dict[str, Any], Any], run_id: Optional[UUID] = None, **kwargs: Any, ) -> AsyncCallbackManagerForChainRun: """Run when chain starts running. Args: se...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-31
parent_run_id: Optional[UUID] = None, **kwargs: Any, ) -> AsyncCallbackManagerForToolRun: """Run when tool starts running. Args: serialized (Dict[str, Any]): The serialized tool. input_str (str): The input to the tool. run_id (UUID, optional): The ID of th...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-32
"""Run when retriever starts running.""" if run_id is None: run_id = uuid.uuid4() await _ahandle_event( self.handlers, "on_retriever_start", "ignore_retriever", serialized, query, run_id=run_id, parent_run_id...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-33
Defaults to None. local_tags (Optional[List[str]], optional): The local tags. Defaults to None. inheritable_metadata (Optional[Dict[str, Any]], optional): The inheritable metadata. Defaults to None. local_metadata (Optional[Dict[str, Any]], optional): ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-34
[docs] async def on_chain_error( self, error: BaseException, **kwargs: Any, ) -> None: """Run when chain errors. Args: error (Exception or KeyboardInterrupt): The error. """ self.ended = True await self.parent_run_manager.on_chain_error(...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-35
verbose (bool, optional): Whether to enable verbose mode. Defaults to False. inheritable_tags (Optional[List[str]], optional): The inheritable tags. Defaults to None. local_tags (Optional[List[str]], optional): The local tags. Defaults to None. inheritable_metadata (Optional[Dict[str...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-36
callback_manager.add_tags(local_tags or [], False) if inheritable_metadata or local_metadata: callback_manager.add_metadata(inheritable_metadata or {}) callback_manager.add_metadata(local_metadata or {}, False) tracer = tracing_callback_var.get() wandb_tracer = wandb_tracing_callback_var.get...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-37
): callback_manager.add_handler(ConsoleCallbackHandler(), True) if tracing_enabled_ and not any( isinstance(handler, LangChainTracerV1) for handler in callback_manager.handlers ): if tracer: callback_manager.add_handler(tracer, True) ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
3ebdbfd4f159-38
for handler in callback_manager.handlers ): callback_manager.add_handler(run_collector_, False) return callback_manager
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/manager.html
44c17c4e3eb6-0
Source code for langchain.callbacks.openai_info """Callback Handler that prints to std out.""" from typing import Any, Dict, List from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import LLMResult MODEL_COST_PER_1K_TOKENS = { # GPT-4 input "gpt-4": 0.03, "gpt-4-0314": 0.03, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html
44c17c4e3eb6-1
"gpt-3.5-turbo-16k-0613": 0.003, # GPT-3.5 output "gpt-3.5-turbo-completion": 0.002, "gpt-3.5-turbo-0301-completion": 0.002, "gpt-3.5-turbo-0613-completion": 0.002, "gpt-3.5-turbo-instruct-completion": 0.002, "gpt-3.5-turbo-16k-completion": 0.004, "gpt-3.5-turbo-16k-0613-completion": 0.004, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html
44c17c4e3eb6-2
"gpt-35-turbo-0613-completion": 0.002, "gpt-35-turbo-instruct-completion": 0.002, "gpt-35-turbo-16k-completion": 0.004, "gpt-35-turbo-16k-0613-completion": 0.004, # Others "text-ada-001": 0.0004, "ada": 0.0004, "text-babbage-001": 0.0005, "babbage": 0.0005, "text-curie-001": 0.002, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html
44c17c4e3eb6-3
model_name = model_name.lower() if "ft-" in model_name: return model_name.split(":")[0] + "-finetuned" elif is_completion and ( model_name.startswith("gpt-4") or model_name.startswith("gpt-3.5") or model_name.startswith("gpt-35") ): return model_name + "-completion" ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html
44c17c4e3eb6-4
successful_requests: int = 0 total_cost: float = 0.0 def __repr__(self) -> str: return ( f"Tokens Used: {self.total_tokens}\n" f"\tPrompt Tokens: {self.prompt_tokens}\n" f"\tCompletion Tokens: {self.completion_tokens}\n" f"Successful Requests: {self.succes...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html
44c17c4e3eb6-5
completion_cost = get_openai_token_cost_for_model( model_name, completion_tokens, is_completion=True ) prompt_cost = get_openai_token_cost_for_model(model_name, prompt_tokens) self.total_cost += prompt_cost + completion_cost self.total_tokens += token_usage.ge...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/openai_info.html
b8c38bc8d1b8-0
Source code for langchain.callbacks.argilla_callback import os import warnings from typing import Any, Dict, List, Optional from packaging.version import parse from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult [docs]class ArgillaCallbackHandler(Bas...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
b8c38bc8d1b8-1
... dataset_name="my-dataset", ... workspace_name="my-workspace", ... api_url="http://localhost:6900", ... api_key="argilla.apikey", ... ) >>> llm = OpenAI( ... temperature=0, ... callbacks=[argilla_callback], ... verbose=True, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
b8c38bc8d1b8-2
workspace_name: name of the workspace in Argilla where the specified `FeedbackDataset` lives in. Defaults to `None`, which means that the default workspace will be used. api_url: URL of the Argilla Server that we want to use, and where the `FeedbackDataset` li...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
b8c38bc8d1b8-3
) # 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_url` is None, and the env var `ARGILLA_API_URL` is not" f" set, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
b8c38bc8d1b8-4
) from e # Set the Argilla variables self.dataset_name = dataset_name self.workspace_name = workspace_name or rg.get_workspace() # Retrieve the `FeedbackDataset` from Argilla (without existing records) try: extra_args = {} if parse(self.ARGILLA_VERSION) < ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
b8c38bc8d1b8-5
f"`langchain` integration. Supported fields are: {supported_fields}," f" and the current `FeedbackDataset` fields are {[field.name for field in self.dataset.fields]}." # noqa: E501 " For more information on how to create a `langchain`-compatible" f" `FeedbackDataset` in ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
b8c38bc8d1b8-6
prompts = self.prompts[str(kwargs["run_id"])] for prompt, generations in zip(prompts, response.generations): self.dataset.add_records( records=[ { "fields": { "prompt": prompt, "respon...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
b8c38bc8d1b8-7
"""If either the `parent_run_id` or the `run_id` is in `self.prompts`, then log the outputs to Argilla, and pop the run from `self.prompts`. The behavior differs if the output is a list or not. """ if not any( key in self.prompts for key in [str(kwargs["parent_run...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
b8c38bc8d1b8-8
self.prompts.pop(str(kwargs["run_id"])) if parse(self.ARGILLA_VERSION) < parse("1.14.0"): # Push the records to Argilla self.dataset.push_to_argilla() [docs] def on_chain_error(self, error: BaseException, **kwargs: Any) -> None: """Do nothing when LLM chain outputs an error.""...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
47a42c897b6b-0
Source code for langchain.callbacks.confident_callback # flake8: noqa 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 DeepEvalCallbackHandler(BaseCallbackHa...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/confident_callback.html
47a42c897b6b-1
[docs] def __init__( self, metrics: List[Any], implementation_name: Optional[str] = None, ) -> None: """Initializes the `deepevalCallbackHandler`. Args: implementation_name: Name of the implementation you want. metrics: What metrics do you want to t...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/confident_callback.html
47a42c897b6b-2
) -> None: """Store the prompts""" self.prompts = 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 records to de...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/confident_callback.html
47a42c897b6b-3
pass [docs] def on_chain_start( self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any ) -> None: """Do nothing when chain starts""" pass [docs] def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None: """Do nothing when chain ends.""" pa...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/confident_callback.html
093fcef40689-0
Source code for langchain.callbacks.clearml_callback import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Dict, List, Optional, Sequence from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.utils import ( BaseMetadataCallbackHandler, flatten_dic...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
093fcef40689-1
and adds the response to the list of records for both the {method}_records and action. It then logs the response to the ClearML console. """ [docs] def __init__( self, task_type: Optional[str] = "inference", project_name: Optional[str] = "langchain_callback_demo", tags: Option...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
093fcef40689-2
) self.logger.report_text(warning, level=30, print_console=True) self.callback_columns: list = [] self.action_records: list = [] self.complexity_metrics = complexity_metrics self.visualize = visualize self.nlp = spacy.load("en_core_web_sm") def _init_resp(self) -> Dic...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
093fcef40689-3
if self.stream_logs: self.logger.report_text(resp) [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 = self._init_resp() resp.update({"action": "on...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
093fcef40689-4
if isinstance(chain_input, str): input_resp = deepcopy(resp) input_resp["input"] = chain_input self.on_chain_start_records.append(input_resp) self.action_records.append(input_resp) if self.stream_logs: self.logger.report_text(input_resp) ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
093fcef40689-5
self.starts += 1 resp = self._init_resp() resp.update({"action": "on_tool_start", "input_str": input_str}) resp.update(flatten_dict(serialized)) resp.update(self.get_custom_callback_meta()) self.on_tool_start_records.append(resp) self.action_records.append(resp) i...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
093fcef40689-6
"""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/clearml_callback.html
093fcef40689-7
if self.complexity_metrics: 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": texts...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
093fcef40689-8
) dep_output_path = Path( self.temp_dir.name, hash_string(f"dep-{text}") + ".html" ) dep_output_path.open("w", encoding="utf-8").write(dep_out) ent_out = spacy.displacy.render( # type: ignore doc, style="ent", jupyter=False, page=True ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
093fcef40689-9
"automated_readability_index", "dale_chall_readability_score", "difficult_words", "linsear_write_formula", "gunning_fog", "text_standard", "fernandez_huerta", "szigriszt_pazos", "gutierrez_pol...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
093fcef40689-10
Everything after this will be a new table. Args: name: Name of the performed session so far so it is identifiable langchain_asset: The langchain asset to save. finish: Whether to finish the run. Returns: None """ pd = import_pandas(...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
093fcef40689-11
target_filename=name, ) except NotImplementedError as e: print("Could not save model.") print(repr(e)) pass # Cleanup after adding everything to ClearML self.task.flush(wait_for_uploads=True) self.temp_dir.cleanup() ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/clearml_callback.html
2c92cf29b825-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 from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.utils import ( flatten_dict, ) from langchain.schema imp...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/sagemaker_callback.html
2c92cf29b825-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
2c92cf29b825-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
2c92cf29b825-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
2c92cf29b825-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
2c92cf29b825-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
2c92cf29b825-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
ad1031a42eb5-0
Source code for langchain.callbacks.human from typing import Any, Callable, Dict, Optional from uuid import UUID from langchain.callbacks.base import BaseCallbackHandler def _default_approve(_input: str) -> bool: msg = ( "Do you approve of the following input? " "Anything except 'Y'/'Yes' (case-inse...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/human.html
1ea00e92df8f-0
Source code for langchain.callbacks.tracers.log_stream from __future__ import annotations import math import threading from typing import ( Any, AsyncIterator, Dict, List, Optional, Sequence, TypedDict, Union, ) from uuid import UUID import jsonpatch from anyio import create_memory_objec...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/log_stream.html
1ea00e92df8f-1
"""Final output of the run, usually the result of aggregating streamed_output. Only available after the run has finished successfully.""" logs: list[LogEntry] """List of sub-runs contained in this run, if any, in the order they were started. If filters were supplied, this list will contain only the runs...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/log_stream.html
1ea00e92df8f-2
[docs]class RunLog(RunLogPatch): state: RunState """Current state of the log, obtained from applying all ops in sequence.""" [docs] def __init__(self, *ops: Dict[str, Any], state: RunState) -> None: super().__init__(*ops) self.state = state def __add__(self, other: Union[RunLogPatch, Any]...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/log_stream.html
1ea00e92df8f-3
self.exclude_types = exclude_types self.exclude_tags = exclude_tags send_stream, receive_stream = create_memory_object_stream( math.inf, item_type=RunLogPatch ) self.lock = threading.Lock() self.send_stream = send_stream self.receive_stream = receive_stream ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/log_stream.html
1ea00e92df8f-4
# therefore not useful here pass def _on_run_create(self, run: Run) -> None: """Start a run.""" if run.parent_run_id is None: self.send_stream.send_nowait( RunLogPatch( { "op": "replace", "path": ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/log_stream.html
1ea00e92df8f-5
RunLogPatch( { "op": "add", "path": f"/logs/{index}/final_output", "value": run.outputs, }, { "op": "add", "path": f"/logs/{index}/end_time"...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/log_stream.html