id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
28,330
import re from abc import ABC, abstractmethod from typing import ( Any, Callable, Dict, List, Literal, Optional, Sequence, Union, ) from langchain_core.callbacks import CallbackManagerForRetrieverRun from langchain_core.documents import Document from langchain_core.pydantic_v1 import ( ...
Combine a ResultItem title and excerpt into a single string. Args: item: the ResultItem of a Kendra search. Returns: A combined text of the title and excerpt of the given item.
28,331
import warnings from typing import Any, Dict, List, Optional from langchain_core.callbacks import CallbackManagerForRetrieverRun from langchain_core.documents import Document from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import root_validator from langchain_core.retrievers import Base...
Deprecated ZillizRetreiver. Please use ZillizRetriever ('i' before 'e') instead. Args: *args: **kwargs: Returns: ZillizRetriever
28,332
from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, List from langchain_core.callbacks import ( AsyncCallbackManagerForRetrieverRun, CallbackManagerForRetrieverRun, ) from langchain_core.documents import Document from langchain_core.language_models.chat_models import BaseChatModel fr...
null
28,333
from __future__ import annotations import concurrent.futures from typing import Any, Iterable, List, Optional import numpy as np from langchain_core.callbacks import CallbackManagerForRetrieverRun from langchain_core.documents import Document from langchain_core.embeddings import Embeddings from langchain_core.retrieve...
Create an index of embeddings for a list of contexts. Args: contexts: List of contexts to embed. embeddings: Embeddings model to use. Returns: Index of embeddings.
28,334
import warnings from typing import Any, Dict, List, Optional from langchain_core.callbacks import CallbackManagerForRetrieverRun from langchain_core.documents import Document from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import root_validator from langchain_core.retrievers import Base...
Deprecated MilvusRetreiver. Please use MilvusRetriever ('i' before 'e') instead. Args: *args: **kwargs: Returns: MilvusRetriever
28,335
from __future__ import annotations import concurrent.futures from typing import Any, List, Optional import numpy as np from langchain_core.callbacks import CallbackManagerForRetrieverRun from langchain_core.documents import Document from langchain_core.embeddings import Embeddings from langchain_core.retrievers import ...
Create an index of embeddings for a list of contexts. Args: contexts: List of contexts to embed. embeddings: Embeddings model to use. Returns: Index of embeddings.
28,336
import hashlib from typing import Any, Dict, List, Optional from langchain_core.callbacks import CallbackManagerForRetrieverRun from langchain_core.documents import Document from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import Extra, root_validator from langchain_core.retrievers impor...
Create an index from a list of contexts. It modifies the index argument in-place! Args: contexts: List of contexts to embed. index: Index to use. embeddings: Embeddings model to use. sparse_encoder: Sparse encoder to use. ids: List of ids to use for the documents. metadatas: List of metadata to use for the documents.
28,337
from __future__ import annotations from typing import Any, Callable, Dict, Iterable, List, Optional from langchain_core.callbacks import CallbackManagerForRetrieverRun from langchain_core.documents import Document from langchain_core.pydantic_v1 import Field from langchain_core.retrievers import BaseRetriever def defa...
null
28,338
import asyncio import logging import warnings from concurrent.futures import ThreadPoolExecutor from typing import Any, Dict, Iterator, List, Optional, Union, cast import aiohttp import requests from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader The provided ...
Build metadata from BeautifulSoup output.
28,339
import concurrent import logging import random from pathlib import Path from typing import Any, List, Optional, Sequence, Type, Union from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader from langchain_community.document_loaders.html_bs import BSHTMLLoader from ...
null
28,340
from __future__ import annotations import os from typing import ( TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, Optional, Sequence, ) from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader def _dependable_mastodon_import() ->...
null
28,341
import json from pathlib import Path from typing import Any, List from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader The provided code snippet includes necessary dependencies for implementing the `concatenate_cells` function. Write a Python function `def conc...
Combine cells information in a readable format ready to be used. Args: cell: A dictionary include_outputs: Whether to include the outputs of the cell. max_output_length: Maximum length of the output to be displayed. traceback: Whether to return a traceback of the error. Returns: A string with the cell information.
28,342
import json from pathlib import Path from typing import Any, List from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader The provided code snippet includes necessary dependencies for implementing the `remove_newlines` function. Write a Python function `def remove...
Recursively remove newlines, no matter the data structure they are stored in.
28,343
import re from pathlib import Path from typing import Iterator from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader The provided code snippet includes necessary dependencies for implementing the `concatenate_rows` function. Write a Python function `def concaten...
Combine message information in a readable format ready to be used.
28,344
from __future__ import annotations import asyncio import json from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Union from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader The provided code snippet includes necessary dependencies f...
Combine message information in a readable format ready to be used.
28,345
from __future__ import annotations import asyncio import json from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Union from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader The provided code snippet includes necessary dependencies f...
Convert a string or list of strings to a list of Documents with metadata.
28,346
from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader def _dependable_tweepy_import() -> tweepy: try: import tweepy except I...
null
28,347
from __future__ import annotations import logging import os import tempfile from abc import abstractmethod from enum import Enum from pathlib import Path from typing import TYPE_CHECKING, Dict, Iterable, List, Sequence, Union from langchain_core.pydantic_v1 import ( BaseModel, BaseSettings, Field, FileP...
Fetch the mime types for the specified file types.
28,348
from __future__ import annotations import asyncio import logging import re from typing import ( TYPE_CHECKING, Callable, Iterator, List, Optional, Sequence, Set, Union, ) import requests from langchain_core.documents import Document from langchain_core.utils.html import extract_sub_links...
Extract metadata from raw html using BeautifulSoup.
28,349
from __future__ import annotations import warnings from typing import ( TYPE_CHECKING, Any, Iterable, Iterator, Mapping, Optional, Sequence, Union, ) from urllib.parse import urlparse import numpy as np from langchain_core.documents import Document from langchain_community.document_loade...
Extract text from images with RapidOCR. Args: images: Images to extract text from. Returns: Text extracted from images. Raises: ImportError: If `rapidocr-onnxruntime` package is not installed.
28,350
from langchain_community.document_loaders.base import BaseBlobParser from langchain_community.document_loaders.parsers.generic import MimeTypeBasedParser from langchain_community.document_loaders.parsers.msword import MsWordParser from langchain_community.document_loaders.parsers.pdf import PyMuPDFParser from langchain...
Get default mime-type based parser.
28,351
from langchain_community.document_loaders.base import BaseBlobParser from langchain_community.document_loaders.parsers.generic import MimeTypeBasedParser from langchain_community.document_loaders.parsers.msword import MsWordParser from langchain_community.document_loaders.parsers.pdf import PyMuPDFParser from langchain...
Get a parser by parser name.
28,352
from typing import Any, Callable, Iterator, List, Optional, Tuple from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader The provided code snippet includes necessary dependencies for implementing the `default_joiner` function. Write a Python function `def default...
Default joiner for content columns.
28,353
from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING, Any, Iterator, List, Optional, Sequence, Tuple, Union from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader def _process_element( element: Union[Tag, NavigableString...
Returns cleaned text with newlines preserved and irrelevant elements removed.
28,354
from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING, Any, Iterator, List, Optional, Sequence, Tuple, Union from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader def _get_link_ratio(section: Tag) -> float: links = sect...
null
28,355
from __future__ import annotations import logging from enum import Enum from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union from urllib.parse import parse_qs, urlparse from langchain_core.documents import Document from langchain_core.pydantic_v1 import root_validator from langchain_co...
Parse a youtube url and return the video id if valid, otherwise None.
28,356
from pathlib import Path from typing import Callable, Iterable, Iterator, Optional, Sequence, TypeVar, Union from langchain_community.document_loaders.blob_loaders.schema import Blob, BlobLoader T = TypeVar("T") The provided code snippet includes necessary dependencies for implementing the `_make_iterator` function. W...
Create a function that optionally wraps an iterable in tqdm.
28,357
import concurrent.futures from typing import List, NamedTuple, Optional, cast class FileEncoding(NamedTuple): """File encoding as the NamedTuple.""" encoding: Optional[str] """The encoding of the file.""" confidence: float """The confidence of the encoding.""" language: Optional[str] """The ...
Try to detect the file encoding. Returns a list of `FileEncoding` tuples with the detected encodings ordered by confidence. Args: file_path: The path to the file to detect the encoding for. timeout: The timeout in seconds for the encoding detection.
28,358
import datetime import json from typing import List from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader The provided code snippet includes necessary dependencies for implementing the `concatenate_rows` function. Write a Python function `def concatenate_rows(me...
Combine message information in a readable format ready to be used. Args: message: Message to be concatenated title: Title of the conversation Returns: Concatenated message
28,359
import collections from abc import ABC, abstractmethod from typing import IO, Any, Callable, Dict, Iterator, List, Optional, Sequence, Union from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader def satisfies_min_unstructured_version(min_version: str) -> bool: ...
Raise an error if the `Unstructured` version does not exceed the specified minimum.
28,360
import collections from abc import ABC, abstractmethod from typing import IO, Any, Callable, Dict, Iterator, List, Optional, Sequence, Union from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader The provided code snippet includes necessary dependencies for imple...
Retrieve a list of elements from the `Unstructured API`.
28,361
import asyncio import logging import warnings from typing import Any, Dict, Iterator, List, Optional, Sequence, Union import aiohttp import requests from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader The provided code snippet includes necessary dependencies f...
Build metadata from BeautifulSoup output.
28,362
import itertools import re from typing import Any, Callable, Generator, Iterable, Iterator, List, Optional, Tuple from urllib.parse import urlparse from langchain_core.documents import Document from langchain_community.document_loaders.web_base import WebBaseLoader def _default_parsing_function(content: Any) -> str: ...
null
28,363
import itertools import re from typing import Any, Callable, Generator, Iterable, Iterator, List, Optional, Tuple from urllib.parse import urlparse from langchain_core.documents import Document from langchain_community.document_loaders.web_base import WebBaseLoader def _default_meta_function(meta: dict, _content: Any)...
null
28,364
import itertools import re from typing import Any, Callable, Generator, Iterable, Iterator, List, Optional, Tuple from urllib.parse import urlparse from langchain_core.documents import Document from langchain_community.document_loaders.web_base import WebBaseLoader def _batch_block(iterable: Iterable, size: int) -> Ge...
null
28,365
import itertools import re from typing import Any, Callable, Generator, Iterable, Iterator, List, Optional, Tuple from urllib.parse import urlparse from langchain_core.documents import Document from langchain_community.document_loaders.web_base import WebBaseLoader The provided code snippet includes necessary dependen...
Extract the scheme + domain from a given URL. Args: url (str): The input URL. Returns: return a 2-tuple of scheme and domain
28,366
import datetime import json from pathlib import Path from typing import Iterator from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader The provided code snippet includes necessary dependencies for implementing the `concatenate_rows` function. Write a Python func...
Combine message information in a readable format ready to be used. Args: row: dictionary containing message information.
28,367
from __future__ import annotations from typing import TYPE_CHECKING, Iterable, List, Optional, Sequence from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader def _dependable_praw_import() -> praw: try: import praw except ImportError: rais...
null
28,368
import os from typing import Any, Dict, List, Optional from uuid import UUID from langchain_core.callbacks import BaseCallbackHandler from langchain_core.messages import ( AIMessage, BaseMessage, ChatMessage, FunctionMessage, HumanMessage, SystemMessage, ) from langchain_core.outputs import LLMR...
null
28,369
from __future__ import annotations import logging from copy import deepcopy from typing import TYPE_CHECKING, Any, Dict, List, Tuple from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import LLMResult from langchain_community.c...
Import flytekit and flytekitplugins-deck-standard.
28,370
from __future__ import annotations import logging from copy import deepcopy from typing import TYPE_CHECKING, Any, Dict, List, Tuple from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import LLMResult from langchain_community.c...
Analyze text using textstat and spacy. Parameters: text (str): The text to analyze. nlp (spacy.lang): The spacy language model to use for visualization. Returns: (dict): A dictionary containing the complexity metrics and visualization files serialized to HTML string.
28,371
import json import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import LLMResult from langchain_com...
Load json file to a dictionary. Parameters: json_path (str): The path to the json file. Returns: (dict): The dictionary representation of the json file.
28,372
import json import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import LLMResult from langchain_com...
Analyze text using textstat and spacy. Parameters: text (str): The text to analyze. complexity_metrics (bool): Whether to compute complexity metrics. visualize (bool): Whether to visualize the text. nlp (spacy.lang): The spacy language model to use for visualization. output_dir (str): The directory to save the visualiz...
28,373
import json import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import LLMResult from langchain_com...
Construct an html element from a prompt and a generation. Parameters: prompt (str): The prompt. generation (str): The generation. Returns: (wandb.Html): The html element.
28,374
import hashlib from pathlib import Path from typing import Any, Dict, Iterable, Tuple, Union def _flatten_dict( nested_dict: Dict[str, Any], parent_key: str = "", sep: str = "_" ) -> Iterable[Tuple[str, Any]]: """ Generator that yields flattened items from a nested dictionary for a flat dict. Parameters...
Flattens a nested dictionary into a flat dictionary. Parameters: nested_dict (dict): The nested dictionary to flatten. 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. Returns: (dict): A flat dictio...
28,375
import hashlib from pathlib import Path from typing import Any, Dict, Iterable, Tuple, Union The provided code snippet includes necessary dependencies for implementing the `load_json` function. Write a Python function `def load_json(json_path: Union[str, Path]) -> str` to solve the following problem: Load json file to...
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.
28,376
from __future__ import annotations import tempfile from copy import deepcopy from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.out...
Import the clearml python package and raise an error if it is not installed.
28,377
import importlib.metadata import logging import os import traceback import warnings from contextvars import ContextVar from typing import Any, Dict, List, Union, cast from uuid import UUID import requests from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler...
Builds an LLMonitor UserContextManager Parameters: - `user_id`: The user id. - `user_props`: The user properties. Returns: A context manager that sets the user context.
28,378
import importlib.metadata import logging import os import traceback import warnings from contextvars import ContextVar from typing import Any, Dict, List, Union, cast from uuid import UUID import requests from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler...
null
28,379
import importlib.metadata import logging import os import traceback import warnings from contextvars import ContextVar from typing import Any, Dict, List, Union, cast from uuid import UUID import requests from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler...
null
28,380
import importlib.metadata import logging import os import traceback import warnings from contextvars import ContextVar from typing import Any, Dict, List, Union, cast from uuid import UUID import requests from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler...
null
28,381
import importlib.metadata import logging import os import traceback import warnings from contextvars import ContextVar from typing import Any, Dict, List, Union, cast from uuid import UUID import requests from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler...
null
28,382
import importlib.metadata import logging import os import traceback import warnings from contextvars import ContextVar from typing import Any, Dict, List, Union, cast from uuid import UUID import requests from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler...
null
28,383
import logging import os import random import string import tempfile import traceback from copy import deepcopy from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from ...
Import the mlflow python package and raise an error if it is not installed.
28,384
import logging import os import random import string import tempfile import traceback from copy import deepcopy from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from ...
Get the metrics to log to MLFlow.
28,385
import logging import os import random import string import tempfile import traceback from copy import deepcopy from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from ...
Analyze text using textstat and spacy. Parameters: text (str): The text to analyze. nlp (spacy.lang): The spacy language model to use for visualization. textstat: The textstat library to use for complexity metrics calculation. Returns: (dict): A dictionary containing the complexity metrics and visualization files seria...
28,386
import logging import os import random import string import tempfile import traceback from copy import deepcopy from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from ...
Construct an html element from a prompt and a generation. Parameters: prompt (str): The prompt. generation (str): The generation. Returns: (str): The html string.
28,387
import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Sequence from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import Generation, LLMResult import langchai...
null
28,388
import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Sequence from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import Generation, LLMResult import langchai...
null
28,389
import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Sequence from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import Generation, LLMResult import langchai...
null
28,390
from __future__ import annotations import os import uuid from collections import defaultdict from datetime import datetime from time import time from typing import TYPE_CHECKING, Any, DefaultDict, Dict, List, Optional import numpy as np from langchain_core.agents import AgentAction, AgentFinish from langchain_core.call...
Lazy load Arthur.
28,391
from __future__ import annotations import json from typing import ( TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, TypedDict, Union, ) from langchain_core.tracers.base import BaseTracer from langchain_core.tracers.schemas import Run def _serialize_io(run_inputs: Optional...
null
28,392
from types import ModuleType, SimpleNamespace from typing import TYPE_CHECKING, Any, Callable, Dict from langchain_core.tracers import BaseTracer def _get_run_type(run: "Run") -> str: if isinstance(run.run_type, str): return run.run_type elif hasattr(run.run_type, "value"): return run.run_type....
null
28,393
from types import ModuleType, SimpleNamespace from typing import TYPE_CHECKING, Any, Callable, Dict from langchain_core.tracers import BaseTracer The provided code snippet includes necessary dependencies for implementing the `import_comet_llm_api` function. Write a Python function `def import_comet_llm_api() -> Simple...
Import comet_llm api and raise an error if it is not installed.
28,394
import os import warnings from datetime import datetime from enum import Enum from typing import Any, Dict, List, Optional, Tuple, Union from uuid import UUID from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.messages import BaseMessa...
Get default Label Studio configs for the given mode. Parameters: mode: Label Studio mode ("prompt" or "chat") Returns: Tuple of Label Studio config and mode
28,395
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Optional from langchain_core.callbacks import BaseCallbackHandler from langchain_core.utils import get_from_env The provided code snippet includes necessary dependencies for implementing the `import_langkit` function. Write a Pyth...
Import the langkit python package and raise an error if it is not installed. Args: sentiment: Whether to import the langkit.sentiment module. Defaults to False. toxicity: Whether to import the langkit.toxicity module. Defaults to False. themes: Whether to import the langkit.themes module. Defaults to False. Returns: Th...
28,396
from __future__ import annotations from enum import Enum from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import LLMResult from langchain_community.callb...
Convert newline characters to markdown newline sequences (space, space, newline).
28,397
from __future__ import annotations import logging from contextlib import contextmanager from contextvars import ContextVar from typing import ( Generator, Optional, ) from langchain_core.tracers.context import register_configure_hook from langchain_community.callbacks.openai_info import OpenAICallbackHandler fr...
Get the OpenAI callback handler in a context manager. which conveniently exposes token and cost information. Returns: OpenAICallbackHandler: The OpenAI callback handler. Example: >>> with get_openai_callback() as cb: ... # Use the OpenAI callback handler
28,398
from __future__ import annotations import logging from contextlib import contextmanager from contextvars import ContextVar from typing import ( Generator, Optional, ) from langchain_core.tracers.context import register_configure_hook from langchain_community.callbacks.openai_info import OpenAICallbackHandler fr...
Get the WandbTracer in a context manager. Args: session_name (str, optional): The name of the session. Defaults to "default". Returns: None Example: >>> with wandb_tracing_enabled() as session: ... # Use the WandbTracer session
28,399
from __future__ import annotations import datetime from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple from uuid import UUID from langchain_core.callbacks import BaseCallbackHandler from langchain_core.messages import ( AIMessage, BaseMessage, ChatMessage, HumanMessage, Syst...
Lazy import promptlayer to avoid circular imports.
28,400
import json import os import shutil import tempfile from copy import deepcopy from typing import Any, Dict, List, Optional from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import LLMResult from langchain_community.callbacks.u...
Save dict to local file path. Parameters: data (dict): The dictionary to be saved. file_path (str): Local file path.
28,401
from typing import Any, Awaitable, Callable, Dict, Optional from uuid import UUID from langchain_core.callbacks import AsyncCallbackHandler, BaseCallbackHandler def _default_approve(_input: str) -> bool: msg = ( "Do you approve of the following input? " "Anything except 'Y'/'Yes' (case-insensitive)...
null
28,402
from typing import Any, Awaitable, Callable, Dict, Optional from uuid import UUID from langchain_core.callbacks import AsyncCallbackHandler, BaseCallbackHandler async def _adefault_approve(_input: str) -> bool: msg = ( "Do you approve of the following input? " "Anything except 'Y'/'Yes' (case-insen...
null
28,403
from typing import Any, Awaitable, Callable, Dict, Optional from uuid import UUID from langchain_core.callbacks import AsyncCallbackHandler, BaseCallbackHandler def _default_true(_: Dict[str, Any]) -> bool: return True
null
28,404
import os from typing import Any, Dict, List from uuid import UUID from langchain_core.callbacks import BaseCallbackHandler from langchain_core.messages import BaseMessage from langchain_core.outputs import LLMResult The provided code snippet includes necessary dependencies for implementing the `import_context` functi...
Import the `getcontext` package.
28,405
import threading from typing import Any, Dict, List from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import LLMResult MODEL_COST_PER_1K_TOKENS = { # GPT-4 input "gpt-4": 0.03, "gpt-4-0314": 0.03, "gpt-4-0613": 0.03, "gpt-4-32k": 0.06, "gpt-4-32k-0314": 0.06, ...
Get the cost in USD for a given model and number of tokens. Args: model_name: Name of the model num_tokens: Number of tokens. is_completion: Whether the model is used for completion or not. Defaults to False. Returns: Cost in USD.
28,406
from copy import deepcopy from typing import Any, Dict, List, Optional from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import LLMResult The provided code snippet includes necessary dependencies for implementing the `import_...
Import the aim python package and raise an error if it is not installed.
28,407
import time from typing import Any, Dict, List, Optional from uuid import UUID from langchain_core.callbacks import BaseCallbackHandler from langchain_core.outputs import LLMResult from langchain_community.callbacks.utils import import_pandas The provided code snippet includes necessary dependencies for implementing t...
Import the fiddler python package and raise an error if it is not installed.
28,408
import time from typing import Any, Dict, List, Optional, cast from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.messages import BaseMessage from langchain_core.outputs import ChatGeneration, LLMResult The provided code snippet inclu...
Import the infino client.
28,409
import time from typing import Any, Dict, List, Optional, cast from langchain_core.agents import AgentAction, AgentFinish from langchain_core.callbacks import BaseCallbackHandler from langchain_core.messages import BaseMessage from langchain_core.outputs import ChatGeneration, LLMResult def import_tiktoken() -> Any: ...
Calculate num tokens for OpenAI with tiktoken package. Official documentation: https://github.com/openai/openai-cookbook/blob/main /examples/How_to_count_tokens_with_tiktoken.ipynb
28,410
from typing import Any, Dict, Optional, Sequence, Type, Union from langchain_core.documents import BaseDocumentTransformer, Document from langchain_core.language_models import BaseLanguageModel from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel class OpenAIMetadataTag...
Create a DocumentTransformer that uses an OpenAI function chain to automatically tag documents with metadata based on their content and an input schema. Args: metadata_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary is passed in, it's assumed to already be a valid JsonSchema. For best results, ...
28,411
from typing import Any, Iterator, List, Sequence, cast from langchain_core.documents import BaseDocumentTransformer, Document The provided code snippet includes necessary dependencies for implementing the `get_navigable_strings` function. Write a Python function `def get_navigable_strings(element: Any) -> Iterator[str...
Get all navigable strings from a BeautifulSoup element. Args: element: A BeautifulSoup element. Returns: A generator of strings.
28,412
from typing import Any, List, Sequence from langchain_core.documents import BaseDocumentTransformer, Document from langchain_core.pydantic_v1 import BaseModel The provided code snippet includes necessary dependencies for implementing the `_litm_reordering` function. Write a Python function `def _litm_reordering(docume...
Lost in the middle reorder: the less relevant documents will be at the middle of the list and more relevant elements at beginning / end. See: https://arxiv.org/abs//2307.03172
28,413
from typing import Any, Callable, List, Sequence import numpy as np from langchain_core.documents import BaseDocumentTransformer, Document from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, Field from langchain_community.utils.math import cosine_similarity class _Document...
Convert a list of documents to a list of documents with state. Args: documents: The documents to convert. Returns: A list of documents with state.
28,414
from typing import Any, Callable, List, Sequence import numpy as np from langchain_core.documents import BaseDocumentTransformer, Document from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, Field from langchain_community.utils.math import cosine_similarity The provided c...
Filter redundant documents based on the similarity of their embeddings.
28,415
from typing import Any, Callable, List, Sequence import numpy as np from langchain_core.documents import BaseDocumentTransformer, Document from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, Field from langchain_community.utils.math import cosine_similarity class _Document...
null
28,416
from typing import Any, Callable, List, Sequence import numpy as np from langchain_core.documents import BaseDocumentTransformer, Document from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, Field from langchain_community.utils.math import cosine_similarity The provided c...
Filter documents based on proximity of their embeddings to clusters.
28,417
import importlib import logging from typing import Any, Callable, List, Optional from langchain_community.embeddings.self_hosted import SelfHostedEmbeddings The provided code snippet includes necessary dependencies for implementing the `_embed_documents` function. Write a Python function `def _embed_documents(client: ...
Inference function to send to the remote hardware. Accepts a sentence_transformer model_id and returns a list of embeddings for each document in the batch.
28,418
import importlib import logging from typing import Any, Callable, List, Optional from langchain_community.embeddings.self_hosted import SelfHostedEmbeddings logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `load_embedding_model` function. Write a Pytho...
Load the embedding model.
28,419
from __future__ import annotations import asyncio import json from typing import Any, Dict, List, Optional import aiohttp import requests from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, root_validator The provided code snippet includes necessary dependencies for imple...
Check if an endpoint is live by sending a GET request to the specified URL. Args: url (str): The URL of the endpoint to check. Returns: bool: True if the endpoint is live (status code 200), False otherwise. Raises: Exception: If the endpoint returns a non-successful status code or if there is an error querying the endp...
28,420
from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional import requests from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, Extra, SecretStr, root_validator from langchain_core.utils import convert_to_secret_str, get_from_di...
Use tenacity to retry the completion call.
28,421
from __future__ import annotations import logging import warnings from typing import ( Any, Callable, Dict, List, Literal, Optional, Sequence, Set, Tuple, Union, ) from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, Extra, Field, roo...
Use tenacity to retry the embedding call.
28,422
from __future__ import annotations import logging import warnings from typing import ( Any, Callable, Dict, List, Literal, Optional, Sequence, Set, Tuple, Union, ) from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, Extra, Field, roo...
Use tenacity to retry the embedding call.
28,423
from __future__ import annotations import json import logging from typing import ( Any, Callable, Dict, List, Optional, Tuple, Union, cast, ) import requests from langchain_core._api.deprecation import deprecated from langchain_core.embeddings import Embeddings from langchain_core.pydant...
Use tenacity to retry the embedding call.
28,424
from __future__ import annotations import logging import time from typing import Any, Callable, Dict, List from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, SecretStr, root_validator from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env from tenaci...
Use tenacity to retry the embedding call.
28,425
from __future__ import annotations from typing import Any, Iterator, List, Optional from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel def _chunk(texts: List[str], size: int) -> Iterator[List[str]]: for i in range(0, len(texts), size): yield texts[i : i + size...
null
28,426
from __future__ import annotations from typing import Any, Dict, Iterator, List from urllib.parse import urlparse from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, PrivateAttr def _chunk(texts: List[str], size: int) -> Iterator[List[str]]: for i in range(0, len(text...
null
28,427
from __future__ import annotations from typing import Iterator, List from urllib.parse import urlparse from langchain_community.embeddings.mlflow import MlflowEmbeddings def _chunk(texts: List[str], size: int) -> Iterator[List[str]]: for i in range(0, len(texts), size): yield texts[i : i + size]
null
28,428
from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel, root_validator from langchain_core.utils import get_from_dict_or_env from tenacity import ( before_sleep_log, ...
Use tenacity to retry the completion call.
28,429
from __future__ import annotations import warnings from typing import Any, Iterator, List, Optional from langchain_core.embeddings import Embeddings from langchain_core.pydantic_v1 import BaseModel def _chunk(texts: List[str], size: int) -> Iterator[List[str]]: for i in range(0, len(texts), size): yield te...
null