id stringlengths 6 6 | text stringlengths 20 17.2k | title stringclasses 1
value |
|---|---|---|
152852 | "TextLoader": {"How to retrieve using multiple vectors per document": "https://python.langchain.com/docs/how_to/multi_vector/", "How to do retrieval with contextual compression": "https://python.langchain.com/docs/how_to/contextual_compression/", "How to load documents from a directory": "https://python.langchain.com/d... | |
152854 | "EmbeddingsFilter": {"How to do retrieval with contextual compression": "https://python.langchain.com/docs/how_to/contextual_compression/", "How to get a RAG application to add citations": "https://python.langchain.com/docs/how_to/qa_citations/"}, "DocumentCompressorPipeline": {"How to do retrieval with contextual comp... | |
152858 | "LaserEmbeddings": {"LASER Language-Agnostic SEntence Representations Embeddings by Meta AI": "https://python.langchain.com/docs/integrations/text_embedding/laser/", "Facebook - Meta": "https://python.langchain.com/docs/integrations/providers/facebook/"}, "OpenCLIPEmbeddings": {"OpenClip": "https://python.langchain.com... | |
152873 | "DistanceStrategy": {"Kinetica Vectorstore API": "https://python.langchain.com/docs/integrations/vectorstores/kinetica/", "SAP HANA Cloud Vector Engine": "https://python.langchain.com/docs/integrations/vectorstores/sap_hanavector/", "SingleStoreDB": "https://python.langchain.com/docs/integrations/vectorstores/singlesto... | |
153211 | "/docs/modules/data_connection/document_loaders/html/": {
"canonical": "/docs/how_to/document_loader_html/",
"alternative": [
"/v0.1/docs/modules/data_connection/document_loaders/html/"
]
},
"/docs/modules/data_connection/document_loaders/json/": {
"canonical": "/docs/how_to/document_loader_js... | |
153217 | "/docs/use_cases/sql/csv/": {
"canonical": "/docs/tutorials/sql_qa/",
"alternative": [
"/v0.1/docs/use_cases/sql/csv/"
]
},
"/docs/use_cases/sql/large_db/": {
"canonical": "/docs/tutorials/sql_qa/",
"alternative": [
"/v0.1/docs/use_cases/sql/large_db/"
]
},
"/docs/use_cases/s... | |
153229 | This package has moved!
https://github.com/langchain-ai/langchain-experimental/tree/main/libs/experimental | |
153319 | """Test text splitting functionality."""
import random
import re
import string
from pathlib import Path
from typing import Any, List
import pytest
from langchain_core.documents import Document
from langchain_text_splitters import (
Language,
RecursiveCharacterTextSplitter,
TextSplitter,
Tokenizer,
)
... | |
153320 | @pytest.mark.parametrize(
"splitter, text, expected_docs",
[
(
CharacterTextSplitter(
separator=" ", chunk_size=7, chunk_overlap=3, add_start_index=True
),
"foo bar baz 123",
[
Document(page_content="foo bar", metadata={"sta... | |
153322 | def test_rust_code_splitter() -> None:
splitter = RecursiveCharacterTextSplitter.from_language(
Language.RUST, chunk_size=CHUNK_SIZE, chunk_overlap=0
)
code = """
fn main() {
println!("Hello, World!");
}
"""
chunks = splitter.split_text(code)
assert chunks == ["fn main() {", 'println... | |
153324 | def test_experimental_markdown_syntax_text_splitter_with_headers() -> None:
"""Test experimental markdown syntax splitter."""
markdown_splitter = ExperimentalMarkdownSyntaxTextSplitter(strip_headers=False)
output = markdown_splitter.split_text(EXPERIMENTAL_MARKDOWN_DOCUMENT)
expected_output = [
... | |
153326 | @pytest.mark.requires("lxml")
@pytest.mark.requires("bs4")
def test_happy_path_splitting_with_duplicate_header_tag() -> None:
# arrange
html_string = """<!DOCTYPE html>
<html>
<body>
<div>
<h1>Foo</h1>
<p>Some intro text about Foo.</p>
... | |
153331 | from __future__ import annotations
import copy
import pathlib
from io import BytesIO, StringIO
from typing import Any, Dict, Iterable, List, Optional, Tuple, TypedDict, cast
import requests
from langchain_core.documents import Document
from langchain_text_splitters.character import RecursiveCharacterTextSplitter
c... | |
153332 | class HTMLSectionSplitter:
"""
Splitting HTML files based on specified tag and font sizes.
Requires lxml package.
"""
def __init__(
self,
headers_to_split_on: List[Tuple[str, str]],
xslt_path: Optional[str] = None,
**kwargs: Any,
) -> None:
"""Create a ne... | |
153335 | from __future__ import annotations
import re
from typing import Any, Dict, List, Tuple, TypedDict, Union
from langchain_core.documents import Document
from langchain_text_splitters.base import Language
from langchain_text_splitters.character import RecursiveCharacterTextSplitter
class MarkdownTextSplitter(Recursiv... | |
153338 | from __future__ import annotations
import re
from typing import Any, List, Literal, Optional, Union
from langchain_text_splitters.base import Language, TextSplitter
class CharacterTextSplitter(TextSplitter):
"""Splitting text that looks at characters."""
def __init__(
self, separator: str = "\n\n",... | |
153341 | from __future__ import annotations
from typing import Any, List, Optional, cast
from langchain_text_splitters.base import TextSplitter, Tokenizer, split_text_on_tokens
class SentenceTransformersTokenTextSplitter(TextSplitter):
"""Splitting text to tokens using sentence model tokenizer."""
def __init__(
... | |
153345 | from __future__ import annotations
import copy
import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import (
AbstractSet,
Any,
Callable,
Collection,
Iterable,
List,
Literal,
Optional,
Sequence,
Type,
TypeVar,
... | |
153426 | """Test the base tool implementation."""
import inspect
import json
import sys
import textwrap
import threading
from datetime import datetime
from enum import Enum
from functools import partial
from typing import (
Annotated,
Any,
Callable,
Generic,
Literal,
Optional,
TypeVar,
Union,
)
... | |
153427 | def test_structured_args_decorator_no_infer_schema() -> None:
"""Test functionality with structured arguments parsed as a decorator."""
@tool(infer_schema=False)
def structured_tool_input(
arg1: int, arg2: Union[float, datetime], opt_arg: Optional[dict] = None
) -> str:
"""Return the ar... | |
153434 | @pytest.mark.skipif(PYDANTIC_MAJOR_VERSION != 1, reason="Testing pydantic v1.")
def test__get_all_basemodel_annotations_v1() -> None:
A = TypeVar("A")
class ModelA(BaseModel, Generic[A], extra="allow"):
a: A
class ModelB(ModelA[str]):
b: Annotated[ModelA[dict[str, Any]], "foo"]
class ... | |
153477 | """Test for some custom pydantic decorators."""
from typing import Any, Optional
import pytest
from pydantic import ConfigDict
from langchain_core.utils.pydantic import (
PYDANTIC_MAJOR_VERSION,
_create_subset_model_v2,
create_model_v2,
get_fields,
is_basemodel_instance,
is_basemodel_subclass... | |
153506 | # Add a test for schema of runnable assign
def foo(x: int) -> int:
return x
foo_ = RunnableLambda(foo)
assert foo_.assign(bar=lambda x: "foo").get_output_schema().model_json_schema() == {
"properties": {"bar": {"title": "Bar"}, "root": {"title": "Root"}},
"required": ["root", "bar"... | |
153548 | from typing import Any, Callable, NamedTuple, Union
import pytest
from langchain_core.beta.runnables.context import Context
from langchain_core.language_models import FakeListLLM, FakeStreamingListLLM
from langchain_core.output_parsers.string import StrOutputParser
from langchain_core.prompt_values import StringPromp... | |
153561 | "langchain_core",
"language_models",
"fake",
"FakeStreamingListLLM"
],
"repr": "FakeStreamingListLLM(responses=['first item, second item, third item'])",
"name": "FakeStreamingListLLM"
},
{
"lc": 1,
"type": "constructo... | |
153565 | "kwargs": {
"first": {
"lc": 1,
"type": "constructor",
"id": [
"langchain",
"prompts",
"chat",
"ChatPromptTemplate"
],
"kwargs": {
"input_variables": [
"question"
],
"messages": [
... | |
153613 | """Set of tests that complement the standard tests for vectorstore.
These tests verify that the base abstraction does appropriate delegation to
the relevant methods.
"""
from __future__ import annotations
import uuid
from collections.abc import Iterable, Sequence
from typing import Any, Optional
import pytest
from... | |
153619 | from langchain_core.output_parsers import __all__
EXPECTED_ALL = [
"BaseLLMOutputParser",
"BaseGenerationOutputParser",
"BaseOutputParser",
"ListOutputParser",
"CommaSeparatedListOutputParser",
"NumberedListOutputParser",
"MarkdownListOutputParser",
"StrOutputParser",
"BaseTransform... | |
153626 | """Test PydanticOutputParser"""
from enum import Enum
from typing import Literal, Optional
import pydantic
import pytest
from pydantic import BaseModel, Field
from pydantic.v1 import BaseModel as V1BaseModel
from langchain_core.exceptions import OutputParserException
from langchain_core.language_models import Parrot... | |
153630 | import json
from typing import Any
import pytest
from pydantic import BaseModel
from langchain_core.exceptions import OutputParserException
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
from langchain_core.output_parsers.openai_functions import (
JsonOutputFunctionsParser,
PydanticO... | |
153648 | """Test few shot prompt template."""
from collections.abc import Sequence
from typing import Any
import pytest
from langchain_core.example_selectors import BaseExampleSelector
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langchain_core.prompts import (
AIMessagePromptTemplate,
... | |
153654 | f test_mustache_prompt_from_template(snapshot: SnapshotAssertion) -> None:
"""Test prompts can be constructed from a template."""
# Single input variable.
template = "This is a {{foo}} test."
prompt = PromptTemplate.from_template(template, template_format="mustache")
assert prompt.format(foo="bar") ... | |
153658 | """Test few shot prompt template."""
import pytest
from langchain_core.prompts.few_shot_with_templates import FewShotPromptWithTemplates
from langchain_core.prompts.prompt import PromptTemplate
EXAMPLE_PROMPT = PromptTemplate(
input_variables=["question", "answer"], template="{question}: {answer}"
)
async def ... | |
153664 | import base64
import tempfile
from pathlib import Path
from typing import Any, Union, cast
import pytest
from pydantic import ValidationError
from syrupy import SnapshotAssertion
from langchain_core._api.deprecation import (
LangChainPendingDeprecationWarning,
)
from langchain_core.load import dumpd, load
from la... | |
153682 | from langchain_core.documents import Document
def test_str() -> None:
assert str(Document(page_content="Hello, World!")) == "page_content='Hello, World!'"
assert (
str(Document(page_content="Hello, World!", metadata={"a": 3}))
== "page_content='Hello, World!' metadata={'a': 3}"
)
def tes... | |
153683 | from langchain_core.documents import Document
def test_init() -> None:
for doc in [
Document(page_content="foo"),
Document(page_content="foo", metadata={"a": 1}),
Document(page_content="foo", id=None),
Document(page_content="foo", id="1"),
Document(page_content="foo", id=1)... | |
153723 | # flake8: noqa
"""Global values and configuration that apply to all of LangChain."""
import warnings
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from langchain_core.caches import BaseCache
# DO NOT USE THESE VALUES DIRECTLY!
# Use them only via `get_<X>()` and `set_<X>()` below,
# or else your ... | |
153725 | """Abstract base class for a Document retrieval system.
A retrieval system is defined as something that can take string queries and return
the most 'relevant' Documents from some source.
Usage:
A retriever follows the standard Runnable interface, and should be used
via the standard Runnable metho... | |
153736 | """Custom **exceptions** for LangChain."""
from enum import Enum
from typing import Any, Optional
class LangChainException(Exception): # noqa: N818
"""General LangChain exception."""
class TracerException(LangChainException):
"""Base class for exceptions in tracers module."""
class OutputParserException... | |
153743 | class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
"""Base class for chat models.
Key imperative methods:
Methods that actually call the underlying model.
+---------------------------+----------------------------------------------------------------+--------------------------------------... | |
153765 | import inspect
from typing import Any, Callable, Literal, Optional, Union, get_type_hints
from pydantic import BaseModel, Field, create_model
from langchain_core.callbacks import Callbacks
from langchain_core.runnables import Runnable
from langchain_core.tools.base import BaseTool
from langchain_core.tools.simple imp... | |
153767 | from __future__ import annotations
from functools import partial
from typing import Optional
from pydantic import BaseModel, Field
from langchain_core.callbacks import Callbacks
from langchain_core.prompts import (
BasePromptTemplate,
PromptTemplate,
aformat_document,
format_document,
)
from langchai... | |
153769 | from __future__ import annotations
import textwrap
from collections.abc import Awaitable
from inspect import signature
from typing import (
Annotated,
Any,
Callable,
Literal,
Optional,
Union,
)
from pydantic import BaseModel, Field, SkipValidation
from langchain_core.callbacks import (
As... | |
153771 | from __future__ import annotations
import asyncio
import functools
import inspect
import json
import uuid
import warnings
from abc import ABC, abstractmethod
from collections.abc import Sequence
from contextvars import copy_context
from inspect import signature
from typing import (
Annotated,
Any,
Callable... | |
153773 | class BaseTool(RunnableSerializable[Union[str, dict, ToolCall], Any]):
"""Interface LangChain tools must implement."""
def __init_subclass__(cls, **kwargs: Any) -> None:
"""Create the definition of the new tool class."""
super().__init_subclass__(**kwargs)
args_schema_type = cls.__anno... | |
153798 | """**Embeddings** interface."""
from abc import ABC, abstractmethod
from langchain_core.runnables.config import run_in_executor
class Embeddings(ABC):
"""Interface for embedding models.
This is an interface meant for implementing text embedding models.
Text embedding models are used to map text to a v... | |
153810 | class RunManager(BaseRunManager):
"""Sync Run Manager."""
def on_text(
self,
text: str,
**kwargs: Any,
) -> Any:
"""Run when a text is received.
Args:
text (str): The received text.
**kwargs (Any): Additional keyword arguments.
Retur... | |
153821 | class AsyncCallbackHandler(BaseCallbackHandler):
"""Async callback handler for LangChain."""
async def on_llm_start(
self,
serialized: dict[str, Any],
prompts: list[str],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,
tags: Optional[list[str]] = N... | |
153826 | """Helper functions for deprecating parts of the LangChain API.
This module was adapted from matplotlibs _api/deprecation.py module:
https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py
.. warning::
This module is for internal use only. Do not use it in your own code.
We ma... | |
153828 | def warn_deprecated(
since: str,
*,
message: str = "",
name: str = "",
alternative: str = "",
alternative_import: str = "",
pending: bool = False,
obj_type: str = "",
addendum: str = "",
removal: str = "",
package: str = "",
) -> None:
"""Display a standardized deprecatio... | |
153837 | """Utilities for tests."""
from __future__ import annotations
import inspect
import textwrap
import warnings
from contextlib import nullcontext
from functools import lru_cache, wraps
from types import GenericAlias
from typing import (
Any,
Callable,
Optional,
TypeVar,
Union,
cast,
overload... | |
153838 | def _create_subset_model_v2(
name: str,
model: type[pydantic.BaseModel],
field_names: list[str],
*,
descriptions: Optional[dict] = None,
fn_description: Optional[str] = None,
) -> type[pydantic.BaseModel]:
"""Create a pydantic model with a subset of the model fields."""
from pydantic imp... | |
153891 | class Runnable(Generic[Input, Output], ABC):
"""A unit of work that can be invoked, batched, streamed, transformed and composed.
Key Methods
===========
- **invoke/ainvoke**: Transforms a single input into an output.
- **batch/abatch**: Efficiently transforms multiple inputs into outputs.
- **... | |
153908 | def invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> dict[str, Any]:
from langchain_core.callbacks.manager import CallbackManager
# setup callbacks
config = ensure_config(config)
callback_manager = CallbackManager.configure(
... | |
153909 | class RunnableGenerator(Runnable[Input, Output]):
"""Runnable that runs a generator function.
RunnableGenerators can be instantiated directly or by using a generator within
a sequence.
RunnableGenerators can be used to implement custom behavior, such as custom output
parsers, while preserving stre... | |
153920 | from __future__ import annotations
import inspect
from collections.abc import Sequence
from types import GenericAlias
from typing import (
TYPE_CHECKING,
Any,
Callable,
Optional,
Union,
)
from pydantic import BaseModel
from typing_extensions import override
from langchain_core.chat_history import... | |
153926 | class VectorStore(ABC):
"""Interface for vector store."""
def add_texts(
self,
texts: Iterable[str],
metadatas: Optional[list[dict]] = None,
*,
ids: Optional[list[str]] = None,
**kwargs: Any,
) -> list[str]:
"""Run more texts through the embeddings an... | |
153927 | async def aadd_documents(
self, documents: list[Document], **kwargs: Any
) -> list[str]:
"""Async run more documents through the embeddings and add to
the vectorstore.
Args:
documents: Documents to add to the vectorstore.
kwargs: Additional keyword arguments.... | |
153929 | async def amax_marginal_relevance_search_by_vector(
self,
embedding: list[float],
k: int = 4,
fetch_k: int = 20,
lambda_mult: float = 0.5,
**kwargs: Any,
) -> list[Document]:
"""Async return docs selected using the maximal marginal relevance.
Maximal ... | |
153930 | class VectorStoreRetriever(BaseRetriever):
"""Base Retriever class for VectorStore."""
vectorstore: VectorStore
"""VectorStore to use for retrieval."""
search_type: str = "similarity"
"""Type of search to perform. Defaults to "similarity"."""
search_kwargs: dict = Field(default_factory=dict)
... | |
153951 | """**OutputParser** classes parse the output of an LLM call.
**Class hierarchy:**
.. code-block::
BaseLLMOutputParser --> BaseOutputParser --> <name>OutputParser # ListOutputParser, PydanticOutputParser
**Main helpers:**
.. code-block::
Serializable, Generation, PromptValue
""" # noqa: E501
from langch... | |
153952 | import json
from typing import Annotated, Generic, Optional
import pydantic
from pydantic import SkipValidation
from typing_extensions import override
from langchain_core.exceptions import OutputParserException
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.outputs import Generation
fr... | |
153953 | # flake8: noqa
JSON_FORMAT_INSTRUCTIONS = """The output should be formatted as a JSON instance that conforms to the JSON schema below.
As an example, for the schema {{"properties": {{"foo": {{"title": "Foo", "description": "a list of strings", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
... | |
153956 | from __future__ import annotations
import json
from json import JSONDecodeError
from typing import Annotated, Any, Optional, TypeVar, Union
import jsonpatch # type: ignore[import]
import pydantic
from pydantic import SkipValidation
from langchain_core.exceptions import OutputParserException
from langchain_core.outp... | |
153958 | class BaseOutputParser(
BaseLLMOutputParser, RunnableSerializable[LanguageModelOutput, T]
):
"""Base class to parse the output of an LLM call.
Output parsers help structure language model responses.
Example:
.. code-block:: python
class BooleanOutputParser(BaseOutputParser[bool]):... | |
153963 | class FewShotChatMessagePromptTemplate(
BaseChatPromptTemplate, _FewShotPromptTemplateMixin
):
"""Chat prompt template that supports few-shot examples.
The high level structure of produced by this prompt template is a list of messages
consisting of prefix message(s), example message(s), and suffix mess... | |
153968 | class ChatPromptTemplate(BaseChatPromptTemplate):
"""Prompt template for chat models.
Use to create flexible templated prompts for chat models.
Examples:
.. versionchanged:: 0.2.24
You can pass any Message-like formats supported by
``ChatPromptTemplate.from_messages()`` d... | |
153969 | @model_validator(mode="before")
@classmethod
def validate_input_variables(cls, values: dict) -> Any:
"""Validate input variables.
If input_variables is not set, it will be set to the union of
all input variables in the messages.
Args:
values: values to validate.
... | |
153973 | """Prompt schema definition."""
from __future__ import annotations
import warnings
from pathlib import Path
from typing import Any, Literal, Optional, Union
from pydantic import BaseModel, model_validator
from langchain_core.prompts.string import (
DEFAULT_FORMATTER_MAPPING,
StringPromptTemplate,
check_... | |
153974 | @classmethod
def from_template(
cls,
template: str,
*,
template_format: str = "f-string",
partial_variables: Optional[dict[str, Any]] = None,
**kwargs: Any,
) -> PromptTemplate:
"""Load a prompt template from a template.
*Security warning*:
... | |
153979 | """Base class for all prompt templates, returning a prompt."""
input_variables: list[str]
"""A list of the names of the variables whose values are required as inputs to the
prompt."""
optional_variables: list[str] = Field(default=[])
"""optional_variables: A list of the names of the variables for p... | |
153980 | @property
def _prompt_type(self) -> str:
"""Return the prompt type key."""
raise NotImplementedError
def dict(self, **kwargs: Any) -> dict:
"""Return dictionary representation of prompt.
Args:
kwargs: Any additional arguments to pass to the dictionary.
Retu... | |
153989 | class Document(BaseMedia):
"""Class for storing a piece of text and associated metadata.
Example:
.. code-block:: python
from langchain_core.documents import Document
document = Document(
page_content="Hello, world!",
metadata={"source": "https... | |
153991 | """Module contains logic for indexing documents into vector stores."""
from __future__ import annotations
import hashlib
import json
import uuid
from collections.abc import AsyncIterable, AsyncIterator, Iterable, Iterator, Sequence
from itertools import islice
from typing import (
Any,
Callable,
Literal,
... | |
154000 | from importlib import metadata
from langchain_core._api.deprecation import warn_deprecated
## Create namespaces for pydantic v1 and v2.
# This code must stay at the top of the file before other modules may
# attempt to import pydantic since it adds pydantic_v1 and pydantic_v2 to sys.modules.
#
# This hack is done for... | |
154001 | from langchain_core._api import warn_deprecated
try:
from pydantic.v1.dataclasses import * # noqa: F403
except ImportError:
from pydantic.dataclasses import * # type: ignore # noqa: F403
warn_deprecated(
"0.3.0",
removal="1.0.0",
alternative="pydantic.v1 or pydantic",
message=(
"As o... | |
154002 | from langchain_core._api import warn_deprecated
try:
from pydantic.v1.main import * # noqa: F403
except ImportError:
from pydantic.main import * # type: ignore # noqa: F403
warn_deprecated(
"0.3.0",
removal="1.0.0",
alternative="pydantic.v1 or pydantic",
message=(
"As of langchain-co... | |
154043 | # 🦜️🔗 LangChain
⚡ Building applications with LLMs through composability ⚡
[](https://github.com/langchain-ai/langchain/releases)
[](https://github.com/... | |
154050 | """Global values and configuration that apply to all of LangChain."""
import warnings
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from langchain_core.caches import BaseCache
# DO NOT USE THESE VALUES DIRECTLY!
# Use them only via `get_<X>()` and `set_<X>()` below,
# or else your code may behave... | |
154053 | def __getattr__(name: str) -> Any:
if name == "MRKLChain":
from langchain.agents import MRKLChain
_warn_on_import(name, replacement="langchain.agents.MRKLChain")
return MRKLChain
elif name == "ReActChain":
from langchain.agents import ReActChain
_warn_on_import(name, r... | |
154054 | elif name == "WikipediaAPIWrapper":
from langchain_community.utilities import WikipediaAPIWrapper
_warn_on_import(
name, replacement="langchain_community.utilities.WikipediaAPIWrapper"
)
return WikipediaAPIWrapper
elif name == "WolframAlphaAPIWrapper":
from lang... | |
154081 | from typing import Any, List
from langchain_core.callbacks import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever, RetrieverLike
from pydantic import ConfigDict
from langchain.retrievers.... | |
154101 | class EnsembleRetriever(BaseRetriever):
"""Retriever that ensembles the multiple retrievers.
It uses a rank fusion.
Args:
retrievers: A list of retrievers to ensemble.
weights: A list of weights corresponding to the retrievers. Defaults to equal
weighting for all retrievers.
... | |
154106 | import datetime
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from langchain_core.callbacks import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
from lang... | |
154109 | import asyncio
import logging
from typing import List, Optional, Sequence
from langchain_core.callbacks import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain_core.documents import Document
from langchain_core.language_models import BaseLanguageModel
from langchain_core.... | |
154126 | from typing import Callable, Dict, Optional, Sequence
import numpy as np
from langchain_core.callbacks.manager import Callbacks
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.utils import pre_init
from pydantic import ConfigDict, Field
from langchain... | |
154155 | """**Tools** are classes that an Agent uses to interact with the world.
Each tool has a **description**. Agent uses the description to choose the right
tool for the job.
**Class hierarchy:**
.. code-block::
ToolMetaclass --> BaseTool --> <name>Tool # Examples: AIPluginTool, BaseGraphQLTool
... | |
154185 | from typing import Any
def __getattr__(name: str = "") -> Any:
raise AttributeError(
"This tool has been moved to langchain experiment. "
"This tool has access to a python REPL. "
"For best practices make sure to sandbox this tool. "
"Read https://github.com/langchain-ai/langchain/... | |
154344 | """**Embedding models** are wrappers around embedding models
from different APIs and services.
**Embedding models** can be LLMs or not.
**Class hierarchy:**
.. code-block::
Embeddings --> <name>Embeddings # Examples: OpenAIEmbeddings, HuggingFaceEmbeddings
"""
import logging
from typing import TYPE_CHECKING,... | |
154387 | from __future__ import annotations
from typing import Any, Dict, List, Type
from langchain_core._api import deprecated
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.language_models import BaseLanguageModel
from langchain_core.messages import BaseMessage, SystemMessage, get_buffer_... | |
154462 | from langchain_core.tracers.stdout import (
ConsoleCallbackHandler,
FunctionCallbackHandler,
)
__all__ = ["FunctionCallbackHandler", "ConsoleCallbackHandler"] | |
154477 | """LangSmith evaluation utilities.
This module provides utilities for evaluating Chains and other language model
applications using LangChain evaluators and LangSmith.
For more information on the LangSmith API, see the `LangSmith API documentation <https://docs.smith.langchain.com/docs/>`_.
**Example**
.. code-bloc... | |
154496 | """**Chat Models** are a variation on language models.
While Chat Models use language models under the hood, the interface they expose
is a bit different. Rather than expose a "text in, text out" API, they expose
an interface where "chat messages" are the inputs and outputs.
**Class hierarchy:**
.. code-block::
... | |
154500 | from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.chat_models.openai import ChatOpenAI
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
... | |
154539 | class AgentExecutor(Chain):
"""Agent that is using tools."""
agent: Union[BaseSingleActionAgent, BaseMultiActionAgent, Runnable]
"""The agent to run for creating a plan and determining actions
to take at each step of the execution loop."""
tools: Sequence[BaseTool]
"""The valid tools the agent ... | |
154540 | def _take_next_step(
self,
name_to_tool_map: Dict[str, BaseTool],
color_mapping: Dict[str, str],
inputs: Dict[str, str],
intermediate_steps: List[Tuple[AgentAction, str]],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Union[AgentFinish, List[Tuple[Age... | |
154541 | async def _aperform_agent_action(
self,
name_to_tool_map: Dict[str, BaseTool],
color_mapping: Dict[str, str],
agent_action: AgentAction,
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> AgentStep:
if run_manager:
await run_manager.on_age... | |
154544 | """Module definitions of agent types together with corresponding agents."""
from enum import Enum
from langchain_core._api import deprecated
@deprecated(
"0.1.0",
message=(
"Use new agent constructor methods like create_react_agent, create_json_agent, "
"create_structured_chat_agent, etc."
... | |
154550 | """Chain that does self-ask with search."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Sequence, Union
from langchain_core._api import deprecated
from langchain_core.language_models import BaseLanguageModel
from langchain_core.prompts import BasePromptTemplate
from langchain_core.runna... | |
154575 | from typing import List, Sequence, Union
from langchain_core.language_models import BaseLanguageModel
from langchain_core.prompts.chat import ChatPromptTemplate
from langchain_core.runnables import Runnable, RunnablePassthrough
from langchain_core.tools import BaseTool
from langchain_core.tools.render import ToolsRend... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.