id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
170f9c169d98-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 |
fb8860cdeb6a-0 | Source code for langchain.callbacks.utils
import hashlib
from pathlib import Path
from typing import Any, Dict, Iterable, Tuple, Union
[docs]def import_spacy() -> Any:
"""Import the spacy python package and raise an error if it is not installed."""
try:
import spacy
except ImportError:
raise... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html |
fb8860cdeb6a-1 | parent_key (str): The prefix to prepend to the keys of the flattened dict.
sep (str): The separator to use between the parent key and the key of the
flattened dictionary.
Yields:
(str, any): A key-value pair from the flattened dictionary.
"""
for key, value in nested_dict.items()... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html |
fb8860cdeb6a-2 | """Load json file to a string.
Parameters:
json_path (str): The path to the json file.
Returns:
(str): The string representation of the json file.
"""
with open(json_path, "r") as f:
data = f.read()
return data
[docs]class BaseMetadataCallbackHandler:
"""This class handle... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html |
fb8860cdeb6a-3 | tool_ends (int): The number of times the tool end method has been called.
agent_ends (int): The number of times the agent end method has been called.
on_llm_start_records (list): A list of records of the on_llm_start method.
on_llm_token_records (list): A list of records of the on_llm_token meth... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html |
fb8860cdeb6a-4 | self.on_llm_token_records: list = []
self.on_llm_end_records: list = []
self.on_chain_start_records: list = []
self.on_chain_end_records: list = []
self.on_tool_start_records: list = []
self.on_tool_end_records: list = []
self.on_text_records: list = []
self.on_ag... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html |
fb8860cdeb6a-5 | }
[docs] def reset_callback_meta(self) -> None:
"""Reset the callback metadata."""
self.step = 0
self.starts = 0
self.ends = 0
self.errors = 0
self.text_ctr = 0
self.ignore_llm_ = False
self.ignore_chain_ = False
self.ignore_agent_ = False
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/utils.html |
68633560183b-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 |
68633560183b-1 | labeling logic.
"""
[docs] def get_initial_label(self) -> str:
"""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:... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
68633560183b-2 | a tool.
"""
return f"{CHECKMARK_EMOJI} **Complete!**"
[docs]class LLMThought:
"""A thought in the LLM's thought stream."""
[docs] def __init__(
self,
parent_container: DeltaGenerator,
labeler: LLMThoughtLabeler,
expanded: bool,
collapse_on_complete: bool,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
68633560183b-3 | self._reset_llm_token_stream()
[docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
# This is only called when the LLM is initialized with `streaming=True`
self._llm_token_stream += _convert_newlines(token)
self._llm_token_writer_idx = self._container.markdown(
se... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
68633560183b-4 | )
[docs] def on_tool_end(
self,
output: str,
color: Optional[str] = None,
observation_prefix: Optional[str] = None,
llm_prefix: Optional[str] = None,
**kwargs: Any,
) -> None:
self._container.markdown(f"**{output}**")
[docs] def on_tool_error(
se... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
68633560183b-5 | else:
self._container.update(new_label=final_label)
[docs] def clear(self) -> None:
"""Remove the thought from the screen. A cleared thought can't be reused."""
self._container.clear()
[docs]class StreamlitCallbackHandler(BaseCallbackHandler):
"""A callback handler that writes to a St... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
68633560183b-6 | self._parent_container = parent_container
self._history_parent = parent_container.container()
self._history_container: Optional[MutableExpander] = None
self._current_thought: Optional[LLMThought] = None
self._completed_thoughts: List[LLMThought] = []
self._max_thought_containers ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
68633560183b-7 | if self._current_thought is not None:
count += 1
return count
def _complete_current_thought(self, final_label: Optional[str] = None) -> None:
"""Complete the current thought, optionally assigning it a new label.
Add it to our _completed_thoughts list.
"""
thought ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
68633560183b-8 | self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
) -> None:
if self._current_thought is None:
self._current_thought = LLMThought(
parent_container=self._parent_container,
expanded=self._expand_new_thoughts,
collapse_on_complete=s... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
68633560183b-9 | [docs] def on_tool_end(
self,
output: str,
color: Optional[str] = None,
observation_prefix: Optional[str] = None,
llm_prefix: Optional[str] = None,
**kwargs: Any,
) -> None:
self._require_current_thought().on_tool_end(
output, color, observation... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
68633560183b-10 | self._prune_old_thought_containers()
[docs] def on_agent_finish(
self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any
) -> None:
if self._current_thought is not None:
self._current_thought.complete(
self._thought_labeler.get_final_agent_thought_label()... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
3069448efa01-0 | Source code for langchain.callbacks.streamlit.mutable_expander
from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional
if TYPE_CHECKING:
from streamlit.delta_generator import DeltaGenerator
from streamlit.type_util import SupportsStr
[docs... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html |
3069448efa01-1 | def label(self) -> str:
"""The expander's label string."""
return self._label
@property
def expanded(self) -> bool:
"""True if the expander was created with `expanded=True`."""
return self._expanded
[docs] def clear(self) -> None:
"""Remove the container and its conten... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html |
3069448efa01-2 | [docs] def markdown(
self,
body: SupportsStr,
unsafe_allow_html: bool = False,
*,
help: Optional[str] = None,
index: Optional[int] = None,
) -> int:
"""Add a Markdown element to the container and return its index."""
kwargs = {"body": body, "unsafe_... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html |
3069448efa01-3 | the existing record at that index. Otherwise, append the record to the
end of the list.
Return the index of the added record.
"""
if index is not None:
# Replace existing child
self._child_records[index] = record
return index
# Append new child... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html |
8fe95f5bc9a3-0 | Source code for langchain.callbacks.tracers.run_collector
"""A tracer that collects all nested runs in a list."""
from typing import Any, List, Optional, Union
from uuid import UUID
from langchain.callbacks.tracers.base import BaseTracer
from langchain.callbacks.tracers.schemas import Run
[docs]class RunCollectorCallba... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/run_collector.html |
748d98644da0-0 | Source code for langchain.callbacks.tracers.base
"""Base interfaces for tracing runs."""
from __future__ import annotations
import logging
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Any, Dict, List, Optional, Sequence, Union, cast
from uuid import UUID
from tenacity import Retr... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
748d98644da0-1 | self.run_map[str(run.id)] = run
def _end_trace(self, run: Run) -> None:
"""End a trace for a run."""
if not run.parent_run_id:
self._persist_run(run)
else:
parent_run = self.run_map.get(str(run.parent_run_id))
if parent_run is None:
logger.... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
748d98644da0-2 | **kwargs: Any,
) -> None:
"""Start a trace for an LLM run."""
parent_run_id_ = str(parent_run_id) if parent_run_id else None
execution_order = self._get_execution_order(parent_run_id_)
start_time = datetime.utcnow()
if metadata:
kwargs.update({"metadata": metadata... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
748d98644da0-3 | {
"name": "new_token",
"time": datetime.utcnow(),
"kwargs": {"token": token},
},
)
[docs] def on_retry(
self,
retry_state: RetryCallState,
*,
run_id: UUID,
**kwargs: Any,
) -> None:
if not run_id:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
748d98644da0-4 | """End a trace for an LLM run."""
if not run_id:
raise TracerException("No run_id provided for on_llm_end callback.")
run_id_ = str(run_id)
llm_run = self.run_map.get(run_id_)
if llm_run is None or llm_run.run_type != "llm":
raise TracerException(f"No LLM Run foun... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
748d98644da0-5 | llm_run.error = repr(error)
llm_run.end_time = datetime.utcnow()
llm_run.events.append({"name": "error", "time": llm_run.end_time})
self._end_trace(llm_run)
self._on_chain_error(llm_run)
[docs] def on_chain_start(
self,
serialized: Dict[str, Any],
inputs: Dict[... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
748d98644da0-6 | ) -> None:
"""End a trace for a chain run."""
if not run_id:
raise TracerException("No run_id provided for on_chain_end callback.")
chain_run = self.run_map.get(str(run_id))
if chain_run is None:
raise TracerException(f"No chain Run found to be traced for {run_id}... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
748d98644da0-7 | metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
"""Start a trace for a tool run."""
parent_run_id_ = str(parent_run_id) if parent_run_id else None
execution_order = self._get_execution_order(parent_run_id_)
start_time = datetime.utcnow()
if metada... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
748d98644da0-8 | self._on_tool_end(tool_run)
[docs] def on_tool_error(
self,
error: Union[Exception, KeyboardInterrupt],
*,
run_id: UUID,
**kwargs: Any,
) -> None:
"""Handle an error for a tool run."""
if not run_id:
raise TracerException("No run_id provided for... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
748d98644da0-9 | parent_run_id=parent_run_id,
serialized=serialized,
inputs={"query": query},
extra=kwargs,
events=[{"name": "start", "time": start_time}],
start_time=start_time,
execution_order=execution_order,
child_execution_order=execution_order,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
748d98644da0-10 | raise TracerException("No run_id provided for on_retriever_end callback.")
retrieval_run = self.run_map.get(str(run_id))
if retrieval_run is None or retrieval_run.run_type != "retriever":
raise TracerException(f"No retriever Run found to be traced for {run_id}")
retrieval_run.outputs... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
748d98644da0-11 | """Process the Tool Run."""
def _on_tool_error(self, run: Run) -> None:
"""Process the Tool Run upon error."""
def _on_chat_model_start(self, run: Run) -> None:
"""Process the Chat Model Run upon start."""
def _on_retriever_start(self, run: Run) -> None:
"""Process the Retriever Run ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
30b7c147151b-0 | Source code for langchain.callbacks.tracers.wandb
"""A Tracer Implementation that records activity to Weights & Biases."""
from __future__ import annotations
import json
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Optional,
Sequence,
Tuple,
TypedDict,
Union,
)
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
30b7c147151b-1 | return span
except Exception as e:
if PRINT_WARNINGS:
self.wandb.termwarn(
f"Skipping trace saving - unable to safely convert LangChain Run "
f"into W&B Trace due to: {e}"
)
return None
def _convert_run_to_wb_spa... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
30b7c147151b-2 | self.trace_tree.Result(
inputs={"prompt": prompt},
outputs={
f"gen_{g_i}": gen["text"]
for g_i, gen in enumerate(run.outputs["generations"][ndx])
}
if (
run.outputs is not None
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
30b7c147151b-3 | :param run: The LangChain Tool Run to convert.
:return: The converted W&B Trace Span.
"""
base_span = self._convert_run_to_wb_span(run)
base_span.results = [
self.trace_tree.Result(
inputs=_serialize_inputs(run.inputs), outputs=run.outputs
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
30b7c147151b-4 | "id",
"name",
"serialized",
"inputs",
"outputs",
"parent_run_id",
"execution_order",
)
processed = self.truncate_run_iterative(processed, keep_keys=keep_keys)
exact_keys, partial_keys = ("... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
30b7c147151b-5 | ) -> List[Dict[str, Any]]:
"""Utility to truncate a list of runs dictionaries to only keep the specified
keys in each run.
:param runs: The list of runs to truncate.
:param keep_keys: The keys to keep in each run.
:return: The truncated list of runs.
"""
def t... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
30b7c147151b-6 | field.
:return: The modified list of runs.
"""
def remove_exact_and_partial_keys(obj: Dict[str, Any]) -> Dict[str, Any]:
"""Recursively removes exact and partial keys from a dictionary.
:param obj: The dictionary to remove keys from.
:return: The modified dict... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
30b7c147151b-7 | obj.pop("id", None)
obj.pop("name", None)
if "kwargs" in obj:
kwargs = obj.pop("kwargs")
for k, v in kwargs.items():
obj[k] = v
for k, v in obj.items():
obj[k] = handle... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
30b7c147151b-8 | }
return output_dict
return list(map(transform_run, runs))
[docs] def build_tree(self, runs: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Builds a nested dictionary from a list of runs.
:param runs: The list of runs to build the tree from.
:return: The nested dictionary rep... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
30b7c147151b-9 | name: Optional[str]
notes: Optional[str]
magic: Optional[Union[dict, str, bool]]
config_exclude_keys: Optional[List[str]]
config_include_keys: Optional[List[str]]
anonymous: Optional[str]
mode: Optional[str]
allow_val_change: Optional[bool]
resume: Optional[Union[bool, str]]
force: O... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
30b7c147151b-10 | tracer = WandbTracer()
chain = LLMChain(llm, callbacks=[tracer])
# ...end of notebook / script:
tracer.finish()
```
"""
super().__init__(**kwargs)
try:
import wandb
from wandb.sdk.data_types import trace_tree
except ImportError as e... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
30b7c147151b-11 | """Ensures an active W&B run exists.
If not, will start a new run with the provided run_args.
"""
if self._wandb.run is None:
# Make a shallow copy of the run args, so we don't modify the original
run_args = self._run_args or {} # type: ignore
run_args: dict ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
73eb8b1f8b98-0 | Source code for langchain.callbacks.tracers.langchain_v1
from __future__ import annotations
import logging
import os
from typing import Any, Dict, Optional, Union
import requests
from langchain.callbacks.tracers.base import BaseTracer
from langchain.callbacks.tracers.schemas import (
ChainRun,
LLMRun,
Run,
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain_v1.html |
73eb8b1f8b98-1 | if not isinstance(session, TracerSessionV1):
raise ValueError(
"LangChainTracerV1 is not compatible with"
f" session of type {type(session)}"
)
if run.run_type == "llm":
if "prompts" in run.inputs:
prompts = run.inputs["prompts"... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain_v1.html |
73eb8b1f8b98-2 | outputs=run.outputs,
error=run.error,
extra=run.extra,
child_llm_runs=[run for run in child_runs if isinstance(run, LLMRun)],
child_chain_runs=[
run for run in child_runs if isinstance(run, ChainRun)
],
c... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain_v1.html |
73eb8b1f8b98-3 | v1_run = self._convert_to_v1_run(run)
else:
v1_run = run
if isinstance(v1_run, LLMRun):
endpoint = f"{self._endpoint}/llm-runs"
elif isinstance(v1_run, ChainRun):
endpoint = f"{self._endpoint}/chain-runs"
else:
endpoint = f"{self._endpoint}... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain_v1.html |
73eb8b1f8b98-4 | r = requests.get(url, headers=self._headers)
tracer_session = TracerSessionV1(**r.json()[0])
except Exception as e:
session_type = "default" if not session_name else session_name
logger.warning(
f"Failed to load {session_type} session, using empty session: {e}... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain_v1.html |
939f96cb11b3-0 | Source code for langchain.callbacks.tracers.schemas
"""Schemas for tracers."""
from __future__ import annotations
import datetime
import warnings
from typing import Any, Dict, List, Optional
from uuid import UUID
from langsmith.schemas import RunBase as BaseRunV2
from langsmith.schemas import RunTypeEnum as RunTypeEnum... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/schemas.html |
939f96cb11b3-1 | uuid: str
parent_uuid: Optional[str] = None
start_time: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)
end_time: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)
extra: Optional[Dict[str, Any]] = None
execution_order: int
child_execution_order: int
ser... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/schemas.html |
939f96cb11b3-2 | tags: Optional[List[str]] = Field(default_factory=list)
@root_validator(pre=True)
def assign_name(cls, values: dict) -> dict:
"""Assign name to the run."""
if values.get("name") is None:
if "name" in values["serialized"]:
values["name"] = values["serialized"]["name"]
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/schemas.html |
2cdc46bd2c7b-0 | Source code for langchain.callbacks.tracers.langchain
"""A Tracer implementation that records to LangChain endpoint."""
from __future__ import annotations
import logging
import os
from concurrent.futures import Future, ThreadPoolExecutor, wait
from datetime import datetime
from typing import Any, Callable, Dict, List, ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
2cdc46bd2c7b-1 | self,
example_id: Optional[Union[UUID, str]] = None,
project_name: Optional[str] = None,
client: Optional[Client] = None,
tags: Optional[List[str]] = None,
use_threading: bool = True,
**kwargs: Any,
) -> None:
"""Initialize the LangChain tracer."""
sup... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
2cdc46bd2c7b-2 | parent_run_id_ = str(parent_run_id) if parent_run_id else None
execution_order = self._get_execution_order(parent_run_id_)
start_time = datetime.utcnow()
if metadata:
kwargs.update({"metadata": metadata})
chat_model_run = Run(
id=run_id,
parent_run_id=... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
2cdc46bd2c7b-3 | # Errors are swallowed by the thread executor so we need to log them here
log_error_once("post", e)
raise
def _update_run_single(self, run: Run) -> None:
"""Update a run."""
try:
run_dict = run.dict()
run_dict["tags"] = self._get_tags(run)
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
2cdc46bd2c7b-4 | """Process the LLM Run upon error."""
self._submit(self._update_run_single, run.copy(deep=True))
def _on_chain_start(self, run: Run) -> None:
"""Process the Chain Run upon start."""
if run.parent_run_id is None:
run.reference_example_id = self.example_id
self._submit(self... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
2cdc46bd2c7b-5 | self._submit(self._persist_run_single, run.copy(deep=True))
def _on_retriever_end(self, run: Run) -> None:
"""Process the Retriever Run."""
self._submit(self._update_run_single, run.copy(deep=True))
def _on_retriever_error(self, run: Run) -> None:
"""Process the Retriever Run upon error.... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
0f584d33f283-0 | Source code for langchain.callbacks.tracers.evaluation
"""A tracer that runs evaluators over completed runs."""
from __future__ import annotations
import logging
from concurrent.futures import Future, ThreadPoolExecutor, wait
from typing import Any, List, Optional, Sequence, Set, Union
from uuid import UUID
from langsm... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/evaluation.html |
0f584d33f283-1 | Attributes
----------
example_id : Union[UUID, None]
The example ID associated with the runs.
client : Client
The LangSmith client instance used for evaluating the runs.
evaluators : Sequence[RunEvaluator]
The sequence of run evaluators to be executed.
executor : ThreadPoolEx... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/evaluation.html |
0f584d33f283-2 | global _TRACERS
_TRACERS.append(self)
def _evaluate_in_project(self, run: Run, evaluator: RunEvaluator) -> None:
"""Evaluate the run in the project.
Parameters
----------
run : Run
The run to be evaluated.
evaluator : RunEvaluator
The evaluator... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/evaluation.html |
6dbc3854648f-0 | Source code for langchain.callbacks.tracers.stdout
import json
from typing import Any, Callable, List
from langchain.callbacks.tracers.base import BaseTracer
from langchain.callbacks.tracers.schemas import Run
from langchain.utils.input import get_bolded_text, get_colored_text
[docs]def try_json_stringify(obj: Any, fal... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html |
6dbc3854648f-1 | super().__init__(**kwargs)
self.function_callback = function
def _persist_run(self, run: Run) -> None:
pass
[docs] def get_parents(self, run: Run) -> List[Run]:
parents = []
current_run = run
while current_run.parent_run_id:
parent = self.run_map.get(str(curren... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html |
6dbc3854648f-2 | )
+ f"{try_json_stringify(run.outputs, '[outputs]')}"
)
def _on_chain_error(self, run: Run) -> None:
crumbs = self.get_breadcrumbs(run)
self.function_callback(
f"{get_colored_text('[chain/error]', color='red')} "
+ get_bolded_text(
f"[{crum... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html |
6dbc3854648f-3 | crumbs = self.get_breadcrumbs(run)
self.function_callback(
f"{get_colored_text('[llm/error]', color='red')} "
+ get_bolded_text(
f"[{crumbs}] [{elapsed(run)}] LLM run errored with error:\n"
)
+ f"{try_json_stringify(run.error, '[error]')}"
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html |
6dbc3854648f-4 | """Tracer that prints to the console."""
name = "console_callback_handler"
[docs] def __init__(self, **kwargs: Any) -> None:
super().__init__(function=print, **kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html |
5deb15263d89-0 | Source code for langchain.utilities.dalle_image_generator
"""Util that calls OpenAI's Dall-E Image Generator."""
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class DallEAPIWrapper(BaseModel):
"""Wrapper for OpenAI... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dalle_image_generator.html |
5deb15263d89-1 | )
return values
[docs] def run(self, query: str) -> str:
"""Run query through OpenAI and parse result."""
image_url = self._dalle_image_url(query)
if image_url is None or image_url == "":
# We don't want to return the assumption alone if answer is empty
return ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dalle_image_generator.html |
de314e6776f3-0 | Source code for langchain.utilities.powerbi
"""Wrapper around a Power BI endpoint."""
from __future__ import annotations
import asyncio
import logging
import os
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
import aiohttp
import requests
from aiohttp import ServerTimeoutError
from pydanti... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
de314e6776f3-1 | """Fix the table names."""
return [fix_table_name(table) for table in table_names]
@root_validator(pre=True, allow_reuse=True)
def token_or_credential_present(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that at least one of token and credentials is present."""
if "token" ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
de314e6776f3-2 | "Could not get a token from the supplied credentials."
) from exc
raise ClientAuthenticationError("No credential or token supplied.")
[docs] def get_table_names(self) -> Iterable[str]:
"""Get names of tables available."""
return self.table_names
[docs] def get_schemas(self)... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
de314e6776f3-3 | if isinstance(table_names, str) and table_names != "":
if table_names not in self.table_names:
_LOGGER.warning("Table %s not found in dataset.", table_names)
return None
return [fix_table_name(table_names)]
return self.table_names
def _... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
de314e6776f3-4 | tables_todo = self._get_tables_todo(tables_requested)
await asyncio.gather(*[self._aget_schema(table) for table in tables_todo])
return self._get_schema_for_tables(tables_requested)
def _get_schema(self, table: str) -> None:
"""Get the schema for a table."""
try:
result =... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
de314e6776f3-5 | self.schemas[table] = "unknown"
def _create_json_content(self, command: str) -> dict[str, Any]:
"""Create the json content for the request."""
return {
"queries": [{"query": rf"{command}"}],
"impersonatedUserName": self.impersonated_user_name,
"serializerSettings"... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
de314e6776f3-6 | async with session.post(
self.request_url,
headers=self.headers,
json=self._create_json_content(command),
timeout=10,
) as response:
if response.status == 403:
return "TokenError: Could not login to PowerBI, ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
f79dd9249302-0 | Source code for langchain.utilities.arxiv
"""Util that calls Arxiv."""
import logging
import os
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, root_validator
from langchain.schema import Document
logger = logging.getLogger(__name__)
[docs]class ArxivAPIWrapper(BaseModel):
"""Wrapper ar... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
f79dd9249302-1 | load_max_docs = 3,
load_all_available_meta = False,
doc_content_chars_max = 40000
)
arxiv.run("tree of thought llm)
"""
arxiv_search: Any #: :meta private:
arxiv_exceptions: Any # :meta private:
top_k_results: int = 3
ARXIV_MAX_QUERY_LENGTH =... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
f79dd9249302-2 | """ # noqa: E501
try:
results = self.arxiv_search( # type: ignore
query[: self.ARXIV_MAX_QUERY_LENGTH], max_results=self.top_k_results
).results()
except self.arxiv_exceptions as ex:
return f"Arxiv exception: {ex}"
docs = [
f"Publ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
f79dd9249302-3 | ).results()
except self.arxiv_exceptions as ex:
logger.debug("Error on arxiv: %s", ex)
return []
docs: List[Document] = []
for result in results:
try:
doc_file_name: str = result.download_pdf()
with fitz.open(doc_file_name) as d... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
09b56df6cd9e-0 | Source code for langchain.utilities.sql_database
"""SQLAlchemy wrapper around a database."""
from __future__ import annotations
import warnings
from typing import Any, Iterable, List, Optional, Sequence
import sqlalchemy
from sqlalchemy import MetaData, Table, create_engine, inspect, select, text
from sqlalchemy.engine... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
09b56df6cd9e-1 | max_string_length: int = 300,
):
"""Create engine from database URI."""
self._engine = engine
self._schema = schema
if include_tables and ignore_tables:
raise ValueError("Cannot specify both include_tables and ignore_tables")
self._inspector = inspect(self._engine... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
09b56df6cd9e-2 | self._custom_table_info = custom_table_info
if self._custom_table_info:
if not isinstance(self._custom_table_info, dict):
raise TypeError(
"table_info must be a dictionary with table names as keys and the "
"desired table info as values"
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
09b56df6cd9e-3 | **kwargs: Any,
) -> SQLDatabase:
"""
Class method to create an SQLDatabase instance from a Databricks connection.
This method requires the 'databricks-sql-connector' package. If not installed,
it can be added using `pip install databricks-sql-connector`.
Args:
cat... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
09b56df6cd9e-4 | cluster the notebook is attached to. Defaults to None.
engine_args (Optional[dict]): The arguments to be used when connecting
Databricks. Defaults to None.
**kwargs (Any): Additional keyword arguments for the `from_uri` method.
Returns:
SQLDatabase: An instanc... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
09b56df6cd9e-5 | "Need to provide either 'warehouse_id' or 'cluster_id'."
)
if warehouse_id and cluster_id:
raise ValueError("Can't have both 'warehouse_id' or 'cluster_id'.")
if warehouse_id:
http_path = f"/sql/1.0/warehouses/{warehouse_id}"
else:
http_path = ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
09b56df6cd9e-6 | with a default value of "".
tenant (str): The name of the tenant used to connect to the CnosDB service,
with a default value of "cnosdb".
database (str): The name of the database in the CnosDB tenant.
Returns:
SQLDatabase: An instance of SQLDatabase configured... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
09b56df6cd9e-7 | """Get information about specified tables.
Follows best practices as specified in: Rajkumar et al, 2022
(https://arxiv.org/abs/2204.00498)
If `sample_rows_in_table_info`, the specified number of sample rows will be
appended to each table description. This can increase performance as
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
09b56df6cd9e-8 | if has_extra_info:
table_info += "*/"
tables.append(table_info)
tables.sort()
final_str = "\n\n".join(tables)
return final_str
def _get_table_indexes(self, table: Table) -> str:
indexes = self._inspector.get_indexes(table.name)
indexes_formatted = ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
09b56df6cd9e-9 | """
Executes SQL command through underlying engine.
If the statement returns no rows, an empty list is returned.
"""
with self._engine.begin() as connection:
if self._schema is not None:
if self.dialect == "snowflake":
connection.exec_drive... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
09b56df6cd9e-10 | for r in result
]
else:
res = tuple(
truncate_word(c, length=self._max_string_length) for c in result
)
return str(res)
[docs] def get_table_info_no_throw(self, table_names: Optional[List[str]] = None) -> str:
"""Get information about specif... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
0ece27268d20-0 | Source code for langchain.utilities.openapi
"""Utility functions for parsing an OpenAPI spec."""
import copy
import json
import logging
import re
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional, Union
import requests
import yaml
from openapi_schema_pydantic import (
Components... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
0ece27268d20-1 | @property
def _components_strict(self) -> Components:
"""Get components or err."""
if self.components is None:
raise ValueError("No components found in spec. ")
return self.components
@property
def _parameters_strict(self) -> Dict[str, Union[Parameter, Reference]]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
0ece27268d20-2 | parameter = self._get_referenced_parameter(ref)
while isinstance(parameter, Reference):
parameter = self._get_referenced_parameter(parameter)
return parameter
[docs] def get_referenced_schema(self, ref: Reference) -> Schema:
"""Get a schema (or nested reference) or err."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
0ece27268d20-3 | while isinstance(request_body, Reference):
request_body = self._get_referenced_request_body(request_body)
return request_body
@staticmethod
def _alert_unsupported_spec(obj: dict) -> None:
"""Alert if the spec is not supported."""
warning_message = (
" This may res... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
0ece27268d20-4 | for key in keys[:-1]:
item = item[key]
item.pop(keys[-1], None)
return cls.parse_obj(new_obj)
[docs] @classmethod
def from_spec_dict(cls, spec_dict: dict) -> "OpenAPISpec":
"""Get an OpenAPI spec from a dict."""
return cls.parse_obj(spec_dict)
[docs... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
0ece27268d20-5 | path_item = self._get_path_strict(path)
results = []
for method in HTTPVerb:
operation = getattr(path_item, method.value, None)
if isinstance(operation, Operation):
results.append(method.value)
return results
[docs] def get_parameters_for_path(self, pat... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
0ece27268d20-6 | return request_body
[docs] @staticmethod
def get_cleaned_operation_id(operation: Operation, path: str, method: str) -> str:
"""Get a cleaned operation id from an operation id."""
operation_id = operation.operationId
if operation_id is None:
# Replace all punctuation of any kin... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.