id
stringlengths
14
16
text
stringlengths
13
2.7k
source
stringlengths
57
178
53ee3b064a1c-1
llm_ends (int): The number of times the llm end method has been called. llm_streams (int): The number of times the text method has been called. tool_starts (int): The number of times the tool start method has been called. tool_ends (int): The number of times the tool end method has been called. ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
53ee3b064a1c-2
"""Whether to ignore agent callbacks.""" return self.ignore_agent_ @property def ignore_retriever(self) -> bool: """Whether to ignore retriever callbacks.""" return self.ignore_retriever_ [docs] def get_custom_callback_meta(self) -> Dict[str, Any]: return { "step":...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
53ee3b064a1c-3
"""Callback Handler that logs to Aim. Parameters: repo (:obj:`str`, optional): Aim repository path or Repo object to which Run object is bound. If skipped, default Repo is used. experiment_name (:obj:`str`, optional): Sets Run's `experiment` property. 'default' if not specifi...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
53ee3b064a1c-4
self._run_hash = self._run.hash self.action_records: list = [] [docs] def setup(self, **kwargs: Any) -> None: aim = import_aim() if not self._run: if self._run_hash: self._run = aim.Run( self._run_hash, repo=self.repo, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
53ee3b064a1c-5
self.llm_ends += 1 self.ends += 1 resp = {"action": "on_llm_end"} resp.update(self.get_custom_callback_meta()) response_res = deepcopy(response) generated = [ aim.Text(generation.text) for generations in response_res.generations for generation ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
53ee3b064a1c-6
aim = import_aim() self.step += 1 self.chain_ends += 1 self.ends += 1 resp = {"action": "on_chain_end"} resp.update(self.get_custom_callback_meta()) outputs_res = deepcopy(outputs) self._run.track( aim.Text(outputs_res["output"]), name="on_chain_end", ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
53ee3b064a1c-7
"""Run when tool errors.""" self.step += 1 self.errors += 1 [docs] def on_text(self, text: str, **kwargs: Any) -> None: """ Run when agent is ending. """ self.step += 1 self.text_ctr += 1 [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
53ee3b064a1c-8
[docs] def flush_tracker( self, repo: Optional[str] = None, experiment_name: Optional[str] = None, system_tracking_interval: Optional[int] = 10, log_system_params: bool = True, langchain_asset: Any = None, reset: bool = True, finish: bool = False, )...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
53ee3b064a1c-9
repo=repo if repo else self.repo, experiment_name=experiment_name if experiment_name else self.experiment_name, system_tracking_interval=system_tracking_interval if system_tracking_interval else self.system_tracking_interval...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/aim_callback.html
b9dd31a821f5-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html
b9dd31a821f5-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html
b9dd31a821f5-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html
b9dd31a821f5-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}") ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/promptlayer_callback.html
db9948796294-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html
db9948796294-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html
db9948796294-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_...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html
db9948796294-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/mutable_expander.html
d770c79a4540-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
d770c79a4540-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:...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
d770c79a4540-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, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
d770c79a4540-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
d770c79a4540-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
d770c79a4540-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
d770c79a4540-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 ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
d770c79a4540-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 ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
d770c79a4540-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
d770c79a4540-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
d770c79a4540-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
44f36e397620-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-1
[docs] def process_span(self, run: Run) -> Optional["Span"]: """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 ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-2
"""Converts a LangChain LLM Run into a W&B Trace Span. :param run: The LangChain LLM Run to convert. :return: The converted W&B Trace Span. """ base_span = self._convert_run_to_wb_span(run) if base_span.attributes is None: base_span.attributes = {} base_span.a...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-3
] base_span.span_kind = ( self.trace_tree.SpanKind.AGENT if "agent" in run.name.lower() 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 T...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-4
else: return self._convert_run_to_wb_span(run) [docs] def process_model(self, run: Run) -> Optional[Dict[str, Any]]: """Utility to process a run for wandb model_dict serialization. :param run: The run to process. :return: The convert model_dict to pass to WBTraceTree. """ ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-5
:param child_runs: The list of child runs to flatten. :return: The flattened list of runs. """ if child_runs is None: return [] result = [] for item in child_runs: child_runs = item.pop("child_runs", []) result.a...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-6
"""Utility to modify the serialized field of a list of runs dictionaries. removes any keys that match the exact_keys and any keys that contain any of the partial_keys. recursively moves the dictionaries under the kwargs key to the top level. changes the "id" field to a string "_kind" fie...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-7
changes the id field to a string "_kind" field that tells WBTraceTree how to visualize the run. recursively moves the dictionaries under the kwargs key to the top level. :param obj: a run dictionary with id and kwargs fields. :param root: whether this is the root dictiona...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-8
"""Transforms a run dictionary to be compatible with WBTraceTree. :param run: The run dictionary to transform. :return: The transformed run dictionary. """ transformed_dict = transform_serialized(run) serialized = transformed_dict.pop("serialized") ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-9
parent_dict[next(iter(parent_dict))][ next(iter(id_to_data[child_id])) ] = id_to_data[child_id][next(iter(id_to_data[child_id]))] root_dict = next( data for id_val, data in id_to_data.items() if id_val not in child_to_parent ) return root_dict [docs]class ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-10
""" _run: Optional[WBRun] = None _run_args: Optional[WandbRunArgs] = None [docs] def __init__(self, run_args: Optional[WandbRunArgs] = None, **kwargs: Any) -> None: """Initializes the WandbTracer. Parameters: run_args: (dict, optional) Arguments to pass to `wandb.init()`. If not ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-11
""" self._wandb.finish() def _log_trace_from_run(self, run: Run) -> None: """Logs a LangChain Run to W*B as a W&B Trace.""" self._ensure_run() root_span = self.run_processor.process_span(run) model_dict = self.run_processor.process_model(run) if root_span is None: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
44f36e397620-12
"`langchain`." ) self._wandb.run._label(repo="langchain") def _persist_run(self, run: "Run") -> None: """Persist a run.""" self._log_trace_from_run(run)
lang/api.python.langchain.com/en/latest/_modules/langchain/callbacks/tracers/wandb.html
8fb1c6a656ef-0
Source code for langchain.docstore.base """Interface to access to place that stores documents.""" from abc import ABC, abstractmethod from typing import Dict, List, Union from langchain.docstore.document import Document [docs]class Docstore(ABC): """Interface to access to place that stores documents.""" [docs] @...
lang/api.python.langchain.com/en/latest/_modules/langchain/docstore/base.html
99a87cd34bba-0
Source code for langchain.docstore.wikipedia """Wrapper around wikipedia API.""" from typing import Union from langchain.docstore.base import Docstore from langchain.docstore.document import Document [docs]class Wikipedia(Docstore): """Wrapper around wikipedia API.""" [docs] def __init__(self) -> None: "...
lang/api.python.langchain.com/en/latest/_modules/langchain/docstore/wikipedia.html
4ef954a81e65-0
Source code for langchain.docstore.arbitrary_fn from typing import Callable, Union from langchain.docstore.base import Docstore from langchain.schema import Document [docs]class DocstoreFn(Docstore): """Langchain Docstore via arbitrary lookup function. This is useful when: * it's expensive to construct an ...
lang/api.python.langchain.com/en/latest/_modules/langchain/docstore/arbitrary_fn.html
54cf80ba11d3-0
Source code for langchain.docstore.in_memory """Simple in memory docstore in the form of a dict.""" from typing import Dict, List, Optional, Union from langchain.docstore.base import AddableMixin, Docstore from langchain.docstore.document import Document [docs]class InMemoryDocstore(Docstore, AddableMixin): """Simp...
lang/api.python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html
54cf80ba11d3-1
""" if search not in self._dict: return f"ID {search} not found." else: return self._dict[search]
lang/api.python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html
9767901d2013-0
Source code for langchain.smith.evaluation.string_run_evaluator """Run evaluator wrapper for string evaluators.""" from __future__ import annotations from abc import abstractmethod from typing import Any, Dict, List, Optional from langsmith import EvaluationResult, RunEvaluator from langsmith.schemas import DataType, E...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html
9767901d2013-1
return self.map(run) [docs]class LLMStringRunMapper(StringRunMapper): """Extract items to evaluate from the run object.""" [docs] def serialize_chat_messages(self, messages: List[Dict]) -> str: """Extract the input messages from the run.""" if isinstance(messages, list) and messages: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html
9767901d2013-2
first_generation: Dict = generations[0] if isinstance(first_generation, list): # Runs from Tracer have generations as a list of lists of dicts # Whereas Runs from the API have a list of dicts first_generation = first_generation[0] if "message" in first_generation: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html
9767901d2013-3
"""The key from the model Run's inputs to use as the eval input. If not provided, will use the only input key or raise an error if there are multiple.""" prediction_key: Optional[str] = None """The key from the model Run's outputs to use as the eval prediction. If not provided, will use the only out...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html
9767901d2013-4
available_keys = ", ".join(run.outputs.keys()) raise ValueError( f"Run with ID {run.id} doesn't have the expected prediction key" f" '{self.prediction_key}'. Available prediction keys in this Run are:" f" {available_keys}. Adjust the evaluator's prediction_key...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html
9767901d2013-5
"""Maps the Example, or dataset row to a dictionary.""" if not example.outputs: raise ValueError( f"Example {example.id} has no outputs to use as a reference." ) if self.reference_key is None: if len(example.outputs) > 1: raise ValueErr...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html
9767901d2013-6
"""The name of the evaluation metric.""" string_evaluator: StringEvaluator """The evaluation chain.""" @property def input_keys(self) -> List[str]: return ["run", "example"] @property def output_keys(self) -> List[str]: return ["feedback"] def _prepare_input(self, inputs: Dic...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html
9767901d2013-7
"""Call the evaluation chain.""" evaluate_strings_inputs = self._prepare_input(inputs) _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() callbacks = _run_manager.get_child() chain_output = self.string_evaluator.evaluate_strings( **evaluate_strings_in...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html
9767901d2013-8
return EvaluationResult( key=self.string_evaluator.evaluation_name, comment=f"Error evaluating run {run.id}: {e}", # TODO: Add run ID once we can declare it via callbacks ) [docs] async def aevaluate_run( self, run: Run, example: Optional[Example] =...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html
9767901d2013-9
data_type (DataType): The type of dataset used in the run. input_key (str, optional): The key used to map the input from the run. prediction_key (str, optional): The key used to map the prediction from the run. reference_key (str, optional): The key used to map the reference from the...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html
9767901d2013-10
) else: example_mapper = None return cls( name=evaluator.evaluation_name, run_mapper=run_mapper, example_mapper=example_mapper, string_evaluator=evaluator, tags=tags, )
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html
c128777ea886-0
Source code for langchain.smith.evaluation.name_generation import random adjectives = [ "abandoned", "aching", "advanced", "ample", "artistic", "back", "best", "bold", "brief", "clear", "cold", "complicated", "cooked", "crazy", "crushing", "damp", "dea...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html
c128777ea886-1
"sunny", "tart", "terrific", "timely", "unique", "upbeat", "vacant", "virtual", "warm", "weary", "whispered", "worthwhile", "yellow", ] nouns = [ "account", "acknowledgment", "address", "advertising", "airplane", "animal", "appointment", "a...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html
c128777ea886-2
"cheek", "cheese", "chef", "cherry", "chicken", "child", "church", "circle", "class", "clay", "click", "clock", "cloth", "cloud", "clove", "club", "coach", "coal", "coast", "coat", "cod", "coffee", "collar", "color", "comb",...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html
c128777ea886-3
"discussion", "disease", "disgust", "distance", "distribution", "division", "doctor", "dog", "door", "drain", "drawer", "dress", "drink", "driving", "dust", "ear", "earth", "edge", "education", "effect", "egg", "end", "energy", ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html
c128777ea886-4
"group", "growth", "guide", "guitar", "hair", "hall", "hand", "harbor", "harmony", "hat", "head", "health", "heart", "heat", "hill", "history", "hobbies", "hole", "hope", "horn", "horse", "hospital", "hour", "house", "humor"...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html
c128777ea886-5
"list", "look", "loss", "love", "lunch", "machine", "man", "manager", "map", "marble", "mark", "market", "mass", "match", "meal", "measure", "meat", "meeting", "memory", "metal", "middle", "milk", "mind", "mine", "minute", ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html
c128777ea886-6
"pear", "pen", "pencil", "person", "pest", "pet", "picture", "pie", "pin", "pipe", "pizza", "place", "plane", "plant", "plastic", "plate", "play", "pleasure", "plot", "plough", "pocket", "point", "poison", "police", "polluti...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html
c128777ea886-7
"rice", "river", "road", "roll", "room", "root", "rose", "route", "rub", "rule", "run", "sack", "sail", "salt", "sand", "scale", "scarecrow", "scarf", "scene", "scent", "school", "science", "scissors", "screw", "sea", "s...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html
c128777ea886-8
"sound", "soup", "space", "spark", "speed", "sponge", "spoon", "spray", "spring", "spy", "square", "stamp", "star", "start", "statement", "station", "steam", "steel", "stem", "step", "stew", "stick", "stitch", "stocking", "s...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html
c128777ea886-9
"toad", "toe", "tooth", "toothpaste", "touch", "town", "toy", "trade", "train", "transport", "tray", "treatment", "tree", "trick", "trip", "trouble", "trousers", "truck", "tub", "turkey", "turn", "twist", "umbrella", "uncle", ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html
c128777ea886-10
"wrist", "writer", "yard", "yoke", "zebra", "zinc", "zipper", "zone", ] [docs]def random_name(prefix: str = "test") -> str: """Generate a random name.""" adjective = random.choice(adjectives) noun = random.choice(nouns) number = random.randint(1, 100) return f"{prefix}-{a...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html
4c966120638b-0
Source code for langchain.smith.evaluation.progress """A simple progress bar for the console.""" import threading from typing import Any, Dict, Optional, Sequence from uuid import UUID from langchain.callbacks import base as base_callbacks from langchain.schema.document import Document from langchain.schema.output impo...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/progress.html
4c966120638b-1
) -> Any: if parent_run_id is None: self.increment() [docs] def on_chain_end( self, outputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any, ) -> Any: if parent_run_id is None: self.incre...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/progress.html
4c966120638b-2
self.increment() [docs] def on_tool_error( self, error: BaseException, *, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any, ) -> Any: if parent_run_id is None: self.increment() [docs] def on_tool_end( self, ou...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/progress.html
2dfea7e2b96b-0
Source code for langchain.smith.evaluation.config """Configuration for run evaluators.""" from typing import Any, Dict, List, Optional, Union from langsmith import RunEvaluator from langchain.evaluation.criteria.eval_chain import CRITERIA_TYPE from langchain.evaluation.embedding_distance.base import ( EmbeddingDist...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html
2dfea7e2b96b-1
If not provided, we will attempt to infer automatically.""" prediction_key: Optional[str] = None """The key from the traced run's outputs dictionary to use to represent the prediction. If not provided, it will be inferred automatically.""" input_key: Optional[str] = None """The key from the trac...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html
2dfea7e2b96b-2
The key from the traced run's outputs dictionary to use to represent the prediction. If not provided, it will be inferred automatically. input_key : Optional[str] The key from the traced run's inputs dictionary to use to represent the input. If not provided, it will be inferred autom...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html
2dfea7e2b96b-3
"""The key from the traced run's inputs dictionary to use to represent the input. If not provided, it will be inferred automatically.""" eval_llm: Optional[BaseLanguageModel] = None """The language model to pass to any evaluators that require one.""" class Config: arbitrary_types_allowed = True ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html
2dfea7e2b96b-4
) -> None: super().__init__(criteria=criteria, **kwargs) [docs] class EmbeddingDistance(SingleKeyEvalConfig): """Configuration for an embedding distance evaluator. Parameters ---------- embeddings : Optional[Embeddings] The embeddings to use for computing the d...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html
2dfea7e2b96b-5
The prompt template to use for generating the question. llm : Optional[BaseLanguageModel] The language model to use for the evaluation chain. """ evaluator_type: EvaluatorType = EvaluatorType.QA llm: Optional[BaseLanguageModel] = None prompt: Optional[BasePromptTempla...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html
2dfea7e2b96b-6
"""Configuration for a json equality evaluator. Parameters ---------- """ evaluator_type: EvaluatorType = EvaluatorType.JSON_EQUALITY [docs] class ExactMatch(SingleKeyEvalConfig): """Configuration for an exact match string evaluator. Parameters ---------- ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html
2dfea7e2b96b-7
If not provided, the score will be between 1 and 10 (by default). prompt : Optional[BasePromptTemplate] """ evaluator_type: EvaluatorType = EvaluatorType.SCORE_STRING criteria: Optional[CRITERIA_TYPE] = None llm: Optional[BaseLanguageModel] = None normalize_by: Optional[f...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/config.html
94b373b81797-0
Source code for langchain.smith.evaluation.runner_utils """Utilities for running language models or Chains over datasets.""" from __future__ import annotations import functools import inspect import logging import uuid from enum import Enum from typing import ( TYPE_CHECKING, Any, Callable, Dict, Li...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-1
if TYPE_CHECKING: import pandas as pd logger = logging.getLogger(__name__) MODEL_OR_CHAIN_FACTORY = Union[ Callable[[], Union[Chain, Runnable]], BaseLanguageModel, Callable[[dict], Any], Runnable, Chain, ] MCF = Union[Callable[[], Union[Chain, Runnable]], BaseLanguageModel] [docs]class InputForm...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-2
raise ImportError( "Pandas is required to convert the results to a dataframe." " to install pandas, run `pip install pandas`." ) from e indices = [] records = [] for example_id, result in self["results"].items(): feedback = result["feedback...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-3
f" new_memory = {memory_class}(...)\n" f" return {chain_class}" "(memory=new_memory, ...)\n\n" f'run_on_dataset("{dataset_name}", chain_constructor, ...)' ) return lambda: chain elif isinstance(llm_or_chain_factory, BaseLanguageModel): ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-4
return lambda: runnable_ elif not isinstance(_model, Runnable): # This is unlikely to happen - a constructor for a model function return lambda: RunnableLambda(constructor) else: # Typical correct case return constructor # noqa return llm_or_chain_fac...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-5
raise InputFormatError(f"LLM Run expects string prompt input. Got {inputs}") else: raise InputFormatError( f"LLM Run expects 'prompt' or 'prompts' in inputs. Got {inputs}" ) if len(prompts) == 1: return prompts[0] else: raise InputFormatError( f"LLM Ru...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-6
f" 'messages' key input. Got {inputs}" ) if len(raw_messages) == 1: return messages_from_dict(raw_messages[0]) else: raise InputFormatError( f"Chat Run expects single List[dict] or List[List[dict]] 'messages'" f" input. Got {len(raw_messages)} messages from inputs...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-7
" for the llm or chat model you wish to evaluate." ) def _validate_example_inputs_for_chain( first_example: Example, chain: Chain, input_mapper: Optional[Callable[[Dict], Any]], ) -> None: """Validate that the example inputs match the chain input keys.""" if input_mapper: fir...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-8
example: Example, llm_or_chain_factory: MCF, input_mapper: Optional[Callable[[Dict], Any]], ) -> None: """Validate that the example inputs are valid for the model.""" if isinstance(llm_or_chain_factory, BaseLanguageModel): _validate_example_inputs_for_language_model(example, input_mapper) el...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-9
run_outputs = chain.output_keys if isinstance(chain, Chain) else None run_evaluators = _load_run_evaluators( evaluation, run_type, data_type, list(examples[0].outputs) if examples[0].outputs else None, run_inputs, run_outputs, ) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-10
if run_outputs and prediction_key not in run_outputs: logger.warning( f"Prediction key {prediction_key} not in chain's specified" f" output keys {run_outputs}. Evaluation behavior may be undefined." ) elif run_outputs and len(run_outputs) == 1: predict...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-11
if not isinstance(eval_config, EvaluatorType): eval_config = EvaluatorType(eval_config) evaluator_ = load_evaluator(eval_config, llm=eval_llm) eval_type_tag = eval_config.value else: kwargs = {"llm": eval_llm, **eval_config.get_kwargs()} evaluator_ = load_evaluator(eval_c...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-12
" Did you mean to use a StringEvaluator instead?" "\nSee: https://python.langchain.com/docs/guides/evaluation/string/" ) else: raise NotImplementedError( f"Run evaluator for {eval_type_tag} is not implemented" ) return run_evaluator def _get_keys( config: smit...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-13
) ): input_key, prediction_key, reference_key = _get_keys( config, run_inputs, run_outputs, example_outputs ) for eval_config in config.evaluators: run_evaluator = _construct_run_evaluator( eval_config, config.eval_llm, run_type, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-14
llm: The language model to run. inputs: The input dictionary. tags: Optional tags to add to the run. callbacks: Optional callbacks to use during the run. input_mapper: Optional function to map inputs to the expected format. Returns: The LLMResult or ChatResult. Raises: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-15
inputs: Dict[str, Any], callbacks: Callbacks, *, tags: Optional[List[str]] = None, input_mapper: Optional[Callable[[Dict], Any]] = None, ) -> Union[dict, str]: """Run a chain asynchronously on inputs.""" inputs_ = inputs if input_mapper is None else input_mapper(inputs) if ( isinstan...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-16
) result = None try: if isinstance(llm_or_chain_factory, BaseLanguageModel): output: Any = await _arun_llm( llm_or_chain_factory, example.inputs, tags=config["tags"], callbacks=config["callbacks"], input_mapper=i...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-17
InputFormatError: If the input format is invalid. """ if input_mapper is not None: prompt_or_messages = input_mapper(inputs) if isinstance(prompt_or_messages, str): llm_output: Union[str, BaseMessage] = llm.predict( prompt_or_messages, callbacks=callbacks, tags=tags ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-18
and len(inputs_) == 1 and chain.input_keys ): val = next(iter(inputs_.values())) output = chain(val, callbacks=callbacks, tags=tags) else: runnable_config = RunnableConfig(tags=tags or [], callbacks=callbacks) output = chain.invoke(inputs_, config=runnable_config) ret...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-19
chain, example.inputs, config["callbacks"], tags=config["tags"], input_mapper=input_mapper, ) result = output except Exception as e: error_type = type(e).__name__ logger.warning( f"{chain_or_llm} failed f...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html
94b373b81797-20
f"\n\n{example_msg}" ) print( f"View the evaluation results for project '{project_name}'" f" at:\n{project.url}?eval=true\n\n" f"View all tests for Dataset {dataset_name} at:\n{dataset.url}", flush=True, ) examples = list(client.list_examples(dataset_id=dataset.id)) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/runner_utils.html