id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
966ac633b7a1-0 | Source code for langchain.callbacks.tracers.langchain
"""A Tracer implementation that records to LangChain endpoint."""
from __future__ import annotations
import logging
import os
import weakref
from concurrent.futures import Future, ThreadPoolExecutor, wait
from datetime import datetime
from typing import Any, Callabl... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
966ac633b7a1-1 | global _EXECUTOR
if _EXECUTOR is None:
_EXECUTOR = ThreadPoolExecutor()
return _EXECUTOR
[docs]class LangChainTracer(BaseTracer):
"""An implementation of the SharedTracer that POSTS to the langchain endpoint."""
[docs] def __init__(
self,
example_id: Optional[Union[UUID, str]] = N... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
966ac633b7a1-2 | name: Optional[str] = None,
**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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
966ac633b7a1-3 | run_dict["extra"] = extra
try:
self.client.create_run(**run_dict, project_name=self.project_name)
except Exception as e:
# Errors are swallowed by the thread executor so we need to log them here
log_error_once("post", e)
raise
def _update_run_single(se... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
966ac633b7a1-4 | self._submit(self._update_run_single, run.copy(deep=True))
def _on_llm_error(self, run: Run) -> None:
"""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."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
966ac633b7a1-5 | if run.parent_run_id is None:
run.reference_example_id = self.example_id
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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/langchain.html |
223e1ac632c8-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 |
223e1ac632c8-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 |
223e1ac632c8-2 | + get_bolded_text(
f"[{crumbs}] [{elapsed(run)}] Exiting {run_type} run with output:\n"
)
+ f"{try_json_stringify(run.outputs, '[outputs]')}"
)
def _on_chain_error(self, run: Run) -> None:
crumbs = self.get_breadcrumbs(run)
run_type = run.run_type.capi... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html |
223e1ac632c8-3 | )
+ f"{try_json_stringify(run.outputs, '[response]')}"
)
def _on_llm_error(self, run: Run) -> None:
crumbs = self.get_breadcrumbs(run)
self.function_callback(
f"{get_colored_text('[llm/error]', color='red')} "
+ get_bolded_text(
f"[{crumbs}... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html |
223e1ac632c8-4 | + get_bolded_text(f"[{crumbs}] [{elapsed(run)}] ")
+ f"Tool run errored with error:\n"
f"{run.error}"
)
[docs]class ConsoleCallbackHandler(FunctionCallbackHandler):
"""Tracer that prints to the console."""
name: str = "console_callback_handler"
[docs] def __init__(self, **kwar... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/stdout.html |
d599ef5c48c5-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 |
d599ef5c48c5-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 |
d599ef5c48c5-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 |
d599ef5c48c5-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 |
d599ef5c48c5-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 |
9002bd82c018-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 |
9002bd82c018-1 | parent_run.child_execution_order = max(
parent_run.child_execution_order, run.child_execution_order
)
else:
logger.debug(f"Parent run with UUID {run.parent_run_id} not found.")
self.run_map[str(run.id)] = run
self._on_run_create(run)
de... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
9002bd82c018-2 | self,
serialized: Dict[str, Any],
prompts: List[str],
*,
run_id: UUID,
tags: Optional[List[str]] = None,
parent_run_id: Optional[UUID] = None,
metadata: Optional[Dict[str, Any]] = None,
name: Optional[str] = None,
**kwargs: Any,
) -> Run:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
9002bd82c018-3 | if not run_id:
raise TracerException("No run_id provided for on_llm_new_token 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 found to be traced for {run_id}")
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
9002bd82c018-4 | exception = retry_state.outcome.exception()
retry_d["exception"] = str(exception)
retry_d["exception_type"] = exception.__class__.__name__
else:
retry_d["outcome"] = "success"
retry_d["result"] = str(retry_state.outcome.result())
llm_run.events.append(
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
9002bd82c018-5 | self._on_llm_end(llm_run)
return llm_run
[docs] def on_llm_error(
self,
error: BaseException,
*,
run_id: UUID,
**kwargs: Any,
) -> Run:
"""Handle an error for an LLM run."""
if not run_id:
raise TracerException("No run_id provided for on... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
9002bd82c018-6 | start_time = datetime.utcnow()
if metadata:
kwargs.update({"metadata": metadata})
chain_run = Run(
id=run_id,
parent_run_id=parent_run_id,
serialized=serialized,
inputs=inputs if isinstance(inputs, dict) else {"input": inputs},
extr... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
9002bd82c018-7 | self._end_trace(chain_run)
self._on_chain_end(chain_run)
return chain_run
[docs] def on_chain_error(
self,
error: BaseException,
*,
inputs: Optional[Dict[str, Any]] = None,
run_id: UUID,
**kwargs: Any,
) -> Run:
"""Handle an error for a chai... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
9002bd82c018-8 | start_time = datetime.utcnow()
if metadata:
kwargs.update({"metadata": metadata})
tool_run = Run(
id=run_id,
parent_run_id=parent_run_id,
serialized=serialized,
inputs={"input": input_str},
extra=kwargs,
events=[{"name":... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
9002bd82c018-9 | """Handle an error for a tool run."""
if not run_id:
raise TracerException("No run_id provided for on_tool_error callback.")
tool_run = self.run_map.get(str(run_id))
if tool_run is None or tool_run.run_type != "tool":
raise TracerException(f"No tool Run found to be traced... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
9002bd82c018-10 | start_time=start_time,
execution_order=execution_order,
child_execution_order=execution_order,
tags=tags,
child_runs=[],
run_type="retriever",
)
self._start_trace(retrieval_run)
self._on_retriever_start(retrieval_run)
return ret... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
9002bd82c018-11 | 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 = {"documents": documents}
retrieval_run.end_time = datetime.utcnow()
retrieval_run.events.append({"name": "end", "time"... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
9002bd82c018-12 | def _on_chain_end(self, run: Run) -> None:
"""Process the Chain Run."""
def _on_chain_error(self, run: Run) -> None:
"""Process the Chain Run upon error."""
def _on_tool_start(self, run: Run) -> None:
"""Process the Tool Run upon start."""
def _on_tool_end(self, run: Run) -> None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/base.html |
7087786c4bfa-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 |
7087786c4bfa-1 | """Converts a LangChain Run into a W&B Trace Span.
:param run: The LangChain Run to convert.
:return: The converted W&B Trace Span.
"""
try:
span = self._convert_lc_run_to_wb_span(run)
return span
except Exception as e:
if PRINT_WARNINGS:
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
7087786c4bfa-2 | """
base_span = self._convert_run_to_wb_span(run)
if base_span.attributes is None:
base_span.attributes = {}
base_span.attributes["llm_output"] = run.outputs.get("llm_output", {})
base_span.results = [
self.trace_tree.Result(
inputs={"prompt": prom... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
7087786c4bfa-3 | else self.trace_tree.SpanKind.CHAIN
)
return base_span
def _convert_tool_run_to_wb_span(self, run: Run) -> "Span":
"""Converts a LangChain Tool Run into a W&B Trace Span.
:param run: The LangChain Tool Run to convert.
:return: The converted W&B Trace Span.
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
7087786c4bfa-4 | :param run: The run to process.
:return: The convert model_dict to pass to WBTraceTree.
"""
try:
data = json.loads(run.json())
processed = self.flatten_run(data)
keep_keys = (
"id",
"name",
"serialized",
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
7087786c4bfa-5 | child_runs = item.pop("child_runs", [])
result.append(item)
result.extend(flatten(child_runs))
return result
return flatten([run])
[docs] def truncate_run_iterative(
self, runs: List[Dict[str, Any]], keep_keys: Tuple[str, ...] = ()
) -> List[Dict[str, A... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
7087786c4bfa-6 | visualize the run. promotes the "serialized" field to the top level.
:param runs: The list of runs to modify.
:param exact_keys: A tuple of keys to remove from the serialized field.
:param partial_keys: A tuple of partial keys to remove from the serialized
field.
:return: The... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
7087786c4bfa-7 | :return: The modified dictionary.
"""
if isinstance(obj, dict):
if ("id" in obj or "name" in obj) and not root:
_kind = obj.get("id")
if not _kind:
_kind = [obj.get("name")]
obj["_kind"] = _kind[-... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
7087786c4bfa-8 | _kind = transformed_dict.get("_kind", None)
name = transformed_dict.pop("name", None)
exec_ord = transformed_dict.pop("execution_order", None)
if not name:
name = _kind
output_dict = {
f"{exec_ord}_{name}": transformed_dict,
}
... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
7087786c4bfa-9 | """Arguments for the WandbTracer."""
job_type: Optional[str]
dir: Optional[StrPath]
config: Union[Dict, str, None]
project: Optional[str]
entity: Optional[str]
reinit: Optional[bool]
tags: Optional[Sequence]
group: Optional[str]
name: Optional[str]
notes: Optional[str]
magic:... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
7087786c4bfa-10 | provided, `wandb.init()` will be called with no arguments. Please
refer to the `wandb.init` for more details.
To use W&B to monitor all LangChain activity, add this tracer like any other
LangChain callback:
```
from wandb.integration.langchain import WandbTracer
t... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
7087786c4bfa-11 | root_span=root_span,
model_dict=model_dict,
)
if self._wandb.run is not None:
self._wandb.run.log({"langchain_trace": model_trace})
def _ensure_run(self, should_print_url: bool = False) -> None:
"""Ensures an active W&B run exists.
If not, will start a new run... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html |
3f702f98a8dc-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 |
3f702f98a8dc-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 |
3f702f98a8dc-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 |
db52869205d5-0 | Source code for langchain.callbacks.tracers.evaluation
"""A tracer that runs evaluators over completed runs."""
from __future__ import annotations
import logging
import weakref
from concurrent.futures import Future, wait
from typing import Any, Dict, List, Optional, Sequence, Union
from uuid import UUID
import langsmit... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/evaluation.html |
db52869205d5-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 |
db52869205d5-2 | self.logged_eval_results: Dict[str, List[EvaluationResult]] = {}
global _TRACERS
_TRACERS.add(self)
def _evaluate_in_project(self, run: Run, evaluator: langsmith.RunEvaluator) -> None:
"""Evaluate the run in the project.
Parameters
----------
run : Run
The... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/evaluation.html |
db52869205d5-3 | )
[docs] def wait_for_futures(self) -> None:
"""Wait for all futures to complete."""
wait(self.futures) | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/evaluation.html |
354527f2f4fd-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 |
74d53d205569-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 |
74d53d205569-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 |
74d53d205569-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 |
74d53d205569-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 |
189d51a4127e-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
from langchain.callbacks.base import BaseCallbackHandler
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
189d51a4127e-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 |
189d51a4127e-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 |
189d51a4127e-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 |
189d51a4127e-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(self, error... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
189d51a4127e-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 |
189d51a4127e-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 |
189d51a4127e-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 |
189d51a4127e-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 |
189d51a4127e-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 |
189d51a4127e-10 | [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()
)
self._curr... | https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html |
5928116024dc-0 | Source code for langchain.schema.prompt
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
from langchain.load.serializable import Serializable
from langchain.schema.messages import BaseMessage
[docs]class PromptValue(Serializable, ABC):
"""Base abstract class for inputs ... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt.html |
ea0d1f47896e-0 | Source code for langchain.schema.cache
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Optional, Sequence
from langchain.schema.output import Generation
RETURN_VAL_TYPE = Sequence[Generation]
[docs]class BaseCache(ABC):
"""Base interface for cache."""
[docs] @abstra... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/cache.html |
f8872a419741-0 | Source code for langchain.schema.embeddings
from abc import ABC, abstractmethod
from typing import List
[docs]class Embeddings(ABC):
"""Interface for embedding models."""
[docs] @abstractmethod
def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Embed search docs."""
[docs] @abstr... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/embeddings.html |
609d600d82a3-0 | Source code for langchain.schema.chat
from typing import Sequence, TypedDict
from langchain.schema import BaseMessage
[docs]class ChatSession(TypedDict):
"""Chat Session represents a single
conversation, channel, or other group of messages."""
messages: Sequence[BaseMessage]
"""The LangChain chat messag... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/chat.html |
c1b1d733bfb4-0 | Source code for langchain.schema.chat_history
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
from langchain.schema.messages import AIMessage, BaseMessage, HumanMessage
[docs]class BaseChatMessageHistory(ABC):
"""Abstract base class for storing chat message history.
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/chat_history.html |
c1b1d733bfb4-1 | Args:
message: The string contents of an AI message.
"""
self.add_message(AIMessage(content=message))
[docs] @abstractmethod
def add_message(self, message: BaseMessage) -> None:
"""Add a Message object to the store.
Args:
message: A BaseMessage object to st... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/chat_history.html |
7e8311619be5-0 | Source code for langchain.schema.prompt_template
from __future__ import annotations
import json
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Mapping, Optional, Union
import yaml
from langchain.load.serializable import Serializable
from langchain.pydantic_v1 ... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html |
7e8311619be5-1 | return create_model( # type: ignore[call-overload]
"PromptInput", **{k: (Any, None) for k in self.input_variables}
)
[docs] def invoke(self, input: Dict, config: RunnableConfig | None = None) -> PromptValue:
return self._call_with_config(
lambda inner_input: self.format_promp... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html |
7e8311619be5-2 | set(self.input_variables).difference(kwargs)
)
prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs}
return type(self)(**prompt_dict)
def _merge_partial_and_user_variables(self, **kwargs: Any) -> Dict[str, Any]:
# Get partial params:
partial_kwargs = {
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html |
7e8311619be5-3 | if isinstance(file_path, str):
save_path = Path(file_path)
else:
save_path = file_path
directory_path = save_path.parent
directory_path.mkdir(parents=True, exist_ok=True)
# Fetch dictionary to save
prompt_dict = self.dict()
if save_path.suffix == "... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html |
7e8311619be5-4 | from langchain.schema import Document
from langchain.prompts import PromptTemplate
doc = Document(page_content="This is a joke", metadata={"page": "1"})
prompt = PromptTemplate.from_template("Page {page}: {page_content}")
format_document(doc, prompt)
>>> "Page... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/prompt_template.html |
95dd03226160-0 | Source code for langchain.schema.retriever
from __future__ import annotations
import warnings
from abc import ABC, abstractmethod
from inspect import signature
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from langchain.load.dump import dumpd
from langchain.load.serializable import Serializable
from lang... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
95dd03226160-1 | """ # noqa: E501
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
_new_arg_supported: bool = False
_expects_other_args: bool = False
tags: Optional[List[str]] = None
"""Optional list of tags associated with the retriever. Defaults to None
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
95dd03226160-2 | if (
hasattr(cls, "aget_relevant_documents")
and cls.aget_relevant_documents != BaseRetriever.aget_relevant_documents
):
warnings.warn(
"Retrievers must implement abstract `_aget_relevant_documents` method"
" instead of `aget_relevant_documents... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
95dd03226160-3 | # If the retriever doesn't implement async, use default implementation
return await super().ainvoke(input, config)
config = config or {}
return await self.aget_relevant_documents(
input,
callbacks=config.get("callbacks"),
tags=config.get("tags"),
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
95dd03226160-4 | tags: Optional list of tags associated with the retriever. Defaults to None
These tags will be associated with each call to this retriever,
and passed as arguments to the handlers defined in `callbacks`.
metadata: Optional metadata associated with the retriever. Defaults to N... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
95dd03226160-5 | metadata: Optional[Dict[str, Any]] = None,
run_name: Optional[str] = None,
**kwargs: Any,
) -> List[Document]:
"""Asynchronously get documents relevant to a query.
Args:
query: string to find relevant documents for
callbacks: Callback manager or list of callba... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
95dd03226160-6 | await run_manager.on_retriever_error(e)
raise e
else:
await run_manager.on_retriever_end(
result,
**kwargs,
)
return result | https://api.python.langchain.com/en/latest/_modules/langchain/schema/retriever.html |
5a1d58cfcc76-0 | Source code for langchain.schema.document
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Sequence
from langchain.load.serializable import Serializable
from langchain.pydantic_v1 import Field
[docs]class Document(Serializable):
"""Class for storing a piece of text and ... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/document.html |
5a1d58cfcc76-1 | self, documents: Sequence[Document], **kwargs: Any
) -> Sequence[Document]:
raise NotImplementedError
""" # noqa: E501
[docs] @abstractmethod
def transform_documents(
self, documents: Sequence[Document], **kwargs: Any
) -> Sequence[Document]:
"""Transf... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/document.html |
ec56539ae4d7-0 | Source code for langchain.schema.vectorstore
from __future__ import annotations
import asyncio
import logging
import math
import warnings
from abc import ABC, abstractmethod
from functools import partial
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Collection,
Dict,
Iterable,... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-1 | """Access the query embedding object if available."""
logger.debug(
f"{Embeddings.__name__} is not implemented for {self.__class__.__name__}"
)
return None
[docs] def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]:
"""Delete by vector ID or ... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-2 | ) -> List[str]:
"""Run more documents through the embeddings and add to the vectorstore.
Args:
documents (List[Document]: Documents to add to the vectorstore.
Returns:
List[str]: List of IDs of the added texts.
"""
texts = [doc.page_content for doc in docu... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-3 | )
[docs] @abstractmethod
def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
"""Return docs most similar to query."""
@staticmethod
def _euclidean_relevance_score_fn(distance: float) -> float:
"""Return a similarity score on a scale [0, 1]."... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-4 | - the distance / similarity metric used by the VectorStore
- the scale of your embeddings (OpenAI's are unit normed. Many others are not!)
- embedding dimensionality
- etc.
Vectorstores should define their own selection based method of relevance.
"""
raise NotImplementedE... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-5 | k: int = 4,
**kwargs: Any,
) -> List[Tuple[Document, float]]:
"""Return docs and relevance scores in the range [0, 1].
0 is dissimilar, 1 is most similar.
Args:
query: input text
k: Number of Documents to return. Defaults to 4.
**kwargs: kwargs to ... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-6 | self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query."""
# This is a temporary workaround to make the similarity search
# asynchronous. The proper solution is to make the similarity search
# asynchronous in the vector sto... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-7 | ) -> List[Document]:
"""Return docs most similar to embedding vector."""
# This is a temporary workaround to make the similarity search
# asynchronous. The proper solution is to make the similarity search
# asynchronous in the vector store implementations.
func = partial(self.sim... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-8 | ) -> List[Document]:
"""Return docs selected using the maximal marginal relevance."""
# This is a temporary workaround to make the similarity search
# asynchronous. The proper solution is to make the similarity search
# asynchronous in the vector store implementations.
func = par... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-9 | k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> List[Document]:
"""Return docs selected using the maximal marginal relevance."""
raise NotImplementedError
[docs] @classmethod
def from_documents(
cls: Type[VST],
documents: Li... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-10 | cls: Type[VST],
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> VST:
"""Return VectorStore initialized from texts and embeddings."""
raise NotImplementedError
def _get_retriever_tags(self) -> List[str]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-11 | docsearch.as_retriever(
search_type="mmr",
search_kwargs={'k': 6, 'lambda_mult': 0.25}
)
# Fetch more documents for the MMR algorithm to consider
# But only return the top 5
docsearch.as_retriever(
search_type="mmr",
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-12 | "similarity",
"similarity_score_threshold",
"mmr",
)
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
@root_validator()
def validate_search_type(cls, values: Dict) -> Dict:
"""Validate search type."""
search_type =... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
ec56539ae4d7-13 | query, **self.search_kwargs
)
else:
raise ValueError(f"search_type of {self.search_type} not allowed.")
return docs
async def _aget_relevant_documents(
self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun
) -> List[Document]:
if self.searc... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/vectorstore.html |
b53d744c322d-0 | Source code for langchain.schema.language_model
from __future__ import annotations
from abc import ABC, abstractmethod
from functools import lru_cache
from typing import (
TYPE_CHECKING,
Any,
List,
Optional,
Sequence,
Set,
TypeVar,
Union,
)
from typing_extensions import TypeAlias
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
b53d744c322d-1 | Serializable, Runnable[LanguageModelInput, LanguageModelOutput], ABC
):
"""Abstract base class for interfacing with language models.
All language model wrappers inherit from BaseLanguageModel.
Exposes three main methods:
- generate_prompt: generate language model outputs for a sequence of prompt
... | https://api.python.langchain.com/en/latest/_modules/langchain/schema/language_model.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.