id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
fa2ab740c896-0 | Source code for langchain.chat_loaders.telegram
import json
import logging
import os
import tempfile
import zipfile
from pathlib import Path
from typing import Iterator, List, Union
from langchain.chat_loaders.base import BaseChatLoader
from langchain.schema import AIMessage, BaseMessage, HumanMessage
from langchain.sc... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/telegram.html |
fa2ab740c896-1 | " Telegram HTML files. You can do this by running"
"'pip install beautifulsoup4' in your terminal."
)
with open(file_path, "r", encoding="utf-8") as file:
soup = BeautifulSoup(file, "html.parser")
results: List[Union[HumanMessage, AIMessage]] = []
previous... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/telegram.html |
fa2ab740c896-2 | for message in messages:
text = message.get("text", "")
timestamp = message.get("date", "")
from_name = message.get("from", "")
results.append(
HumanMessage(
content=text,
additional_kwargs={
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/telegram.html |
fa2ab740c896-3 | yield self._load_single_chat_session_html(file_path)
elif file_path.endswith(".json"):
yield self._load_single_chat_session_json(file_path) | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/telegram.html |
2cf6ce46baeb-0 | Source code for langchain.chat_loaders.base
from abc import ABC, abstractmethod
from typing import Iterator, List
from langchain.schema.chat import ChatSession
[docs]class BaseChatLoader(ABC):
"""Base class for chat loaders."""
[docs] @abstractmethod
def lazy_load(self) -> Iterator[ChatSession]:
"""L... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/base.html |
4b98164d6f8b-0 | Source code for langchain.chat_loaders.facebook_messenger
import json
import logging
from pathlib import Path
from typing import Iterator, Union
from langchain.chat_loaders.base import BaseChatLoader
from langchain.schema.chat import ChatSession
from langchain.schema.messages import HumanMessage
logger = logging.getLog... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/facebook_messenger.html |
4b98164d6f8b-1 | Attributes:
path (Path): The path to the directory containing the chat files.
"""
[docs] def __init__(self, path: Union[str, Path]) -> None:
super().__init__()
self.directory_path = Path(path) if isinstance(path, str) else path
[docs] def lazy_load(self) -> Iterator[ChatSession]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/facebook_messenger.html |
fb0d34b1a877-0 | Source code for langchain.chat_loaders.slack
import json
import logging
import re
import zipfile
from pathlib import Path
from typing import Dict, Iterator, List, Union
from langchain.chat_loaders.base import BaseChatLoader
from langchain.schema import AIMessage, HumanMessage
from langchain.schema.chat import ChatSessi... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/slack.html |
fb0d34b1a877-1 | {"message_time": timestamp}
)
else:
results.append(
HumanMessage(
role=sender,
content=text,
additional_kwargs={
"sender": sender,
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/slack.html |
5c30a5834c8c-0 | Source code for langchain.chat_loaders.imessage
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING, Iterator, List, Optional, Union
from langchain.chat_loaders.base import BaseChatLoader
from langchain.schema import HumanMessage
from langchain.schema.chat import ChatSession
if ... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/imessage.html |
5c30a5834c8c-1 | except ImportError as e:
raise ImportError(
"The sqlite3 module is required to load iMessage chats.\n"
"Please install it with `pip install pysqlite3`"
) from e
def _load_single_chat_session(
self, cursor: "sqlite3.Cursor", chat_id: int
) -> ChatSe... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/imessage.html |
5c30a5834c8c-2 | import sqlite3
try:
conn = sqlite3.connect(self.db_path)
except sqlite3.OperationalError as e:
raise ValueError(
f"Could not open iMessage DB file {self.db_path}.\n"
"Make sure your terminal emulator has disk access to this file.\n"
... | https://api.python.langchain.com/en/latest/_modules/langchain/chat_loaders/imessage.html |
85883c5ce151-0 | Source code for langchain.retrievers.azure_cognitive_search
from __future__ import annotations
import json
from typing import Dict, List, Optional
import aiohttp
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.pydant... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
85883c5ce151-1 | values["service_name"] = get_from_dict_or_env(
values, "service_name", "AZURE_COGNITIVE_SEARCH_SERVICE_NAME"
)
values["index_name"] = get_from_dict_or_env(
values, "index_name", "AZURE_COGNITIVE_SEARCH_INDEX_NAME"
)
values["api_key"] = get_from_dict_or_env(
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
85883c5ce151-2 | async with session.get(search_url, headers=self._headers) as response:
response_json = await response.json()
else:
async with self.aiosession.get(
search_url, headers=self._headers
) as response:
response_json = await response.json()
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
caa05e2a5678-0 | Source code for langchain.retrievers.tfidf
from __future__ import annotations
import pickle
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
[docs]class TFIDFRetriev... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
caa05e2a5678-1 | tfidf_array = vectorizer.fit_transform(texts)
metadatas = metadatas or ({} for _ in texts)
docs = [Document(page_content=t, metadata=m) for t, m in zip(texts, metadatas)]
return cls(vectorizer=vectorizer, docs=docs, tfidf_array=tfidf_array, **kwargs)
[docs] @classmethod
def from_documents... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
caa05e2a5678-2 | ) -> None:
try:
import joblib
except ImportError:
raise ImportError(
"Could not import joblib, please install with `pip install joblib`."
)
path = Path(folder_path)
path.mkdir(exist_ok=True, parents=True)
# Save vectorizer with ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
98448f5e376f-0 | Source code for langchain.retrievers.multi_vector
from typing import List
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.pydantic_v1 import Field
from langchain.schema import BaseRetriever, BaseStore, Document
from langchain.vectorstores import VectorStore
[docs]class MultiVectorR... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_vector.html |
ab9ce90364e6-0 | Source code for langchain.retrievers.bm25
from __future__ import annotations
from typing import Any, Callable, Dict, Iterable, List, Optional
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
[docs]def default_preprocessing_func(text: str) -> Lis... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/bm25.html |
ab9ce90364e6-1 | **kwargs: Any other arguments to pass to the retriever.
Returns:
A BM25Retriever instance.
"""
try:
from rank_bm25 import BM25Okapi
except ImportError:
raise ImportError(
"Could not import rank_bm25, please install with `pip install "
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/bm25.html |
ab9ce90364e6-2 | Returns:
A BM25Retriever instance.
"""
texts, metadatas = zip(*((d.page_content, d.metadata) for d in documents))
return cls.from_texts(
texts=texts,
bm25_params=bm25_params,
metadatas=metadatas,
preprocess_func=preprocess_func,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/bm25.html |
e11f015acb5c-0 | Source code for langchain.retrievers.merger_retriever
import asyncio
from typing import List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
[docs]class MergerRetriever(BaseRetriever):
"""Re... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
e11f015acb5c-1 | """
Merge the results of the retrievers.
Args:
query: The query to search for.
Returns:
A list of merged documents.
"""
# Get the results of all retrievers.
retriever_docs = [
retriever.get_relevant_documents(
query, cal... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
e11f015acb5c-2 | for i in range(max_docs):
for retriever, doc in zip(self.retrievers, retriever_docs):
if i < len(doc):
merged_documents.append(doc[i])
return merged_documents | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
926d7c948c61-0 | Source code for langchain.retrievers.zilliz
import warnings
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.pydantic_v1 import root_validator
from langchain.schema import BaseRetriever, Document
from langchain.schema.embeddings import Em... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html |
926d7c948c61-1 | )
return values
[docs] def add_texts(
self, texts: List[str], metadatas: Optional[List[dict]] = None
) -> None:
"""Add text to the Zilliz store
Args:
texts (List[str]): The text
metadatas (List[dict]): Metadata dicts, must line up with existing store
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html |
509c92b97c3b-0 | Source code for langchain.retrievers.svm
from __future__ import annotations
import concurrent.futures
from typing import Any, Iterable, List, Optional
import numpy as np
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
from langchain.schema.embe... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
509c92b97c3b-1 | cls,
texts: List[str],
embeddings: Embeddings,
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> SVMRetriever:
index = create_index(texts, embeddings)
return cls(
embeddings=embeddings,
index=index,
texts=texts,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
509c92b97c3b-2 | clf.fit(x, y)
similarities = clf.decision_function(x)
sorted_ix = np.argsort(-similarities)
# svm.LinearSVC in scikit-learn is non-deterministic.
# if a text is the same as a query, there is no guarantee
# the query will be in the first index.
# this performs a simple swa... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
15788f6d9752-0 | Source code for langchain.retrievers.remote_retriever
from typing import List, Optional
import aiohttp
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
[docs]class RemoteLangChain... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html |
15788f6d9752-1 | async with aiohttp.ClientSession() as session:
async with session.request(
"POST", self.url, headers=self.headers, json={self.input_key: query}
) as response:
result = await response.json()
return [
Document(
page_content=r[self... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html |
ca6f12a37f55-0 | Source code for langchain.retrievers.re_phraser
import logging
from typing import List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.chains.llm import LLMChain
from langchain.llms.base import BaseLLM
from langchain.prompts.prompt ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/re_phraser.html |
ca6f12a37f55-1 | Returns:
RePhraseQueryRetriever
"""
llm_chain = LLMChain(llm=llm, prompt=prompt)
return cls(
retriever=retriever,
llm_chain=llm_chain,
)
def _get_relevant_documents(
self,
query: str,
*,
run_manager: CallbackManagerF... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/re_phraser.html |
c99a4a4cd1c9-0 | Source code for langchain.retrievers.multi_query
import asyncio
import logging
from typing import List, Sequence
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.chains.llm import LLMChain
from langchain.llms.base import BaseLLM
from... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
c99a4a4cd1c9-1 | )
def _unique_documents(documents: Sequence[Document]) -> List[Document]:
return [doc for i, doc in enumerate(documents) if doc not in documents[:i]]
[docs]class MultiQueryRetriever(BaseRetriever):
"""Given a query, use an LLM to write a set of queries.
Retrieve docs for each query. Return the unique union ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
c99a4a4cd1c9-2 | Args:
question: user query
Returns:
Unique union of relevant documents from all generated queries
"""
queries = await self.agenerate_queries(query, run_manager)
documents = await self.aretrieve_documents(queries, run_manager)
return self.unique_union(docum... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
c99a4a4cd1c9-3 | ) -> List[Document]:
"""Get relevant documents given a user query.
Args:
question: user query
Returns:
Unique union of relevant documents from all generated queries
"""
queries = self.generate_queries(query, run_manager)
documents = self.retrieve_d... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
5e8a0e6b47b8-0 | Source code for langchain.retrievers.pubmed
from typing import List
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
from langchain.utilities.pubmed import PubMedAPIWrapper
[docs]class PubMedRetriever(BaseRetriever, PubMedAPIWrapper):
"""`Pu... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pubmed.html |
513918dbe0d7-0 | Source code for langchain.retrievers.llama_index
from typing import Any, Dict, List, cast
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.pydantic_v1 import Field
from langchain.schema import BaseRetriever, Document
[docs]class LlamaIndexRetriever(BaseRetriever):
"""`LlamaIndex... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
513918dbe0d7-1 | It is used for question-answering with sources over an LlamaIndex
graph data structure."""
graph: Any
"""LlamaIndex graph to query."""
query_configs: List[Dict] = Field(default_factory=list)
"""List of query configs to pass to the query method."""
def _get_relevant_documents(
self, query... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
c20c4b9b9341-0 | Source code for langchain.retrievers.elastic_search_bm25
"""Wrapper around Elasticsearch vector database."""
from __future__ import annotations
import uuid
from typing import Any, Iterable, List
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.docstore.document import Document
from ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
c20c4b9b9341-1 | [docs] @classmethod
def create(
cls, elasticsearch_url: str, index_name: str, k1: float = 2.0, b: float = 0.75
) -> ElasticSearchBM25Retriever:
"""
Create a ElasticSearchBM25Retriever from a list of texts.
Args:
elasticsearch_url: URL of the Elasticsearch instance ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
c20c4b9b9341-2 | """Run more texts through the embeddings and add to the retriever.
Args:
texts: Iterable of strings to add to the retriever.
refresh_indices: bool to refresh ElasticSearch indices
Returns:
List of ids from adding the texts into the retriever.
"""
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
365a07189e94-0 | Source code for langchain.retrievers.parent_document_retriever
import uuid
from typing import List, Optional
from langchain.retrievers import MultiVectorRetriever
from langchain.schema.document import Document
from langchain.text_splitter import TextSplitter
[docs]class ParentDocumentRetriever(MultiVectorRetriever):
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/parent_document_retriever.html |
365a07189e94-1 | # The vectorstore to use to index the child chunks
vectorstore = Chroma(embedding_function=OpenAIEmbeddings())
# The storage layer for the parent documents
store = InMemoryStore()
# Initialize the retriever
retriever = ParentDocumentRetriever(
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/parent_document_retriever.html |
365a07189e94-2 | to set this to False if the documents are already in the docstore
and you don't want to re-add them.
"""
if self.parent_splitter is not None:
documents = self.parent_splitter.split_documents(documents)
if ids is None:
doc_ids = [str(uuid.uuid4()) for _ in ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/parent_document_retriever.html |
a4f2b9b98d3d-0 | Source code for langchain.retrievers.zep
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.pydantic_v1 import root_validator
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html |
a4f2b9b98d3d-1 | values["zep_client"] = values.get(
"zep_client",
ZepClient(base_url=values["url"], api_key=values.get("api_key")),
)
return values
def _search_result_to_doc(
self, results: List[MemorySearchResult]
) -> List[Document]:
return [
Document(
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html |
2e5cf6e429c1-0 | Source code for langchain.retrievers.google_cloud_enterprise_search
"""Retriever wrapper for Google Cloud Enterprise Search on Gen App Builder."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence
from langchain.callbacks.manager import CallbackManagerForRetrieverR... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_enterprise_search.html |
2e5cf6e429c1-1 | """The maximum number of extractive answers returned in each search result.
At most 5 answers will be returned for each SearchResult.
"""
max_extractive_segment_count: int = Field(default=1, ge=1, le=1)
"""The maximum number of extractive segments returned in each search result.
Currently one segmen... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_enterprise_search.html |
2e5cf6e429c1-2 | the environment."""
# TODO: Add extra data type handling for type website
engine_data_type: int = Field(default=0, ge=0, le=1)
""" Defines the enterprise search data type
0 - Unstructured data
1 - Structured data
"""
_client: SearchServiceClient
_serving_config: str
class Config:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_enterprise_search.html |
2e5cf6e429c1-3 | except ImportError:
raise ImportError(
"google.cloud.discoveryengine is not installed."
"Please install it with pip install google-cloud-discoveryengine"
)
super().__init__(**data)
self._client = SearchServiceClient(credentials=self.credentials)
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_enterprise_search.html |
2e5cf6e429c1-4 | )
)
return documents
def _convert_structured_search_response(
self, results: Sequence[SearchResult]
) -> List[Document]:
"""Converts a sequence of search results to a list of LangChain documents."""
import json
from google.protobuf.json_format import Messa... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_enterprise_search.html |
2e5cf6e429c1-5 | )
elif self.engine_data_type == 1:
content_search_spec = None
else:
# TODO: Add extra data type handling for type website
raise NotImplementedError(
"Only engine data type 0 (Unstructured) or 1 (Structured)"
+ " are supported currently.... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_enterprise_search.html |
dce1203786d8-0 | Source code for langchain.retrievers.web_research
import logging
import re
from typing import List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.chains import LLMChain
from langchain.chains.prompt_selector import Conditi... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html |
dce1203786d8-1 | )
DEFAULT_SEARCH_PROMPT = PromptTemplate(
input_variables=["question"],
template="""You are an assistant tasked with improving Google search \
results. Generate THREE Google search queries that are similar to \
this question. The output should be a numbered list of questions and each \
should have a question ma... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html |
dce1203786d8-2 | )
[docs] @classmethod
def from_llm(
cls,
vectorstore: VectorStore,
llm: BaseLLM,
search: GoogleSearchAPIWrapper,
prompt: Optional[BasePromptTemplate] = None,
num_search_results: int = 1,
text_splitter: RecursiveCharacterTextSplitter = RecursiveCharacterText... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html |
dce1203786d8-3 | [docs] def clean_search_query(self, query: str) -> str:
# Some search tools (e.g., Google) will
# fail to return results if query has a
# leading digit: 1. "LangCh..."
# Check if the first character is a digit
if query[0].isdigit():
# Find the position of the first... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html |
dce1203786d8-4 | # Get urls
logger.info("Searching for relevant urls...")
urls_to_look = []
for query in questions:
# Google search
search_results = self.search_tool(query, self.num_search_results)
logger.info("Searching for relevant urls...")
logger.info(f"Search ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html |
dce1203786d8-5 | *,
run_manager: AsyncCallbackManagerForRetrieverRun,
) -> List[Document]:
raise NotImplementedError | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html |
10cd4bdccd54-0 | Source code for langchain.retrievers.knn
"""KNN Retriever.
Largely based on
https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb"""
from __future__ import annotations
import concurrent.futures
from typing import Any, List, Optional
import numpy as np
from langchain.callbacks.manager import CallbackManager... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html |
10cd4bdccd54-1 | index = create_index(texts, embeddings)
return cls(embeddings=embeddings, index=index, texts=texts, **kwargs)
def _get_relevant_documents(
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
) -> List[Document]:
query_embeds = np.array(self.embeddings.embed_query(query))
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html |
07e2581fa710-0 | Source code for langchain.retrievers.time_weighted_retriever
import datetime
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.pydantic_v1 import Field
from langchain.schema import BaseRetriever, Document
f... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
07e2581fa710-1 | """
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
def _document_get_date(self, field: str, document: Document) -> datetime.datetime:
"""Return the value of the date field of a document."""
if field in document.metadata:
if ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
07e2581fa710-2 | results[buffer_idx] = (doc, relevance)
return results
def _get_relevant_documents(
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
) -> List[Document]:
"""Return documents that are relevant to the query."""
current_time = datetime.datetime.now()
docs_and_... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
07e2581fa710-3 | if "last_accessed_at" not in doc.metadata:
doc.metadata["last_accessed_at"] = current_time
if "created_at" not in doc.metadata:
doc.metadata["created_at"] = current_time
doc.metadata["buffer_idx"] = len(self.memory_stream) + i
self.memory_stream.extend(dup... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
4b40f1df67dc-0 | Source code for langchain.retrievers.milvus
"""Milvus Retriever"""
import warnings
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.pydantic_v1 import root_validator
from langchain.schema import BaseRetriever, Document
from langchain.sche... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html |
4b40f1df67dc-1 | Args:
texts (List[str]): The text
metadatas (List[dict]): Metadata dicts, must line up with existing store
"""
self.store.add_texts(texts, metadatas)
def _get_relevant_documents(
self,
query: str,
*,
run_manager: CallbackManagerForRetrieverRun,... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html |
f64f3b51b7f9-0 | Source code for langchain.retrievers.contextual_compression
from typing import Any, List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.retrievers.document_compressors.base import (
BaseDocumentCompressor,
)
from langchain.sche... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html |
f64f3b51b7f9-1 | run_manager: AsyncCallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
"""Get documents relevant for a query.
Args:
query: string to find relevant documents for
Returns:
List of relevant documents
"""
docs = await self.base_retri... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html |
1536ac7f4a46-0 | Source code for langchain.retrievers.docarray
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import numpy as np
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
from langchain.schema.embeddings import Embeddings
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
1536ac7f4a46-1 | """Configuration for this pydantic object."""
arbitrary_types_allowed = True
def _get_relevant_documents(
self,
query: str,
*,
run_manager: CallbackManagerForRetrieverRun,
) -> List[Document]:
"""Get documents relevant for a query.
Args:
query:... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
1536ac7f4a46-2 | else:
filter_args["filter_query"] = self.filters
if self.filters:
query = (
self.index.build_query() # get empty query object
.find(
query=query_emb, search_field=search_field
) # add vector similarity search
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
1536ac7f4a46-3 | [
doc[self.search_field]
if isinstance(doc, dict)
else getattr(doc, self.search_field)
for doc in docs
],
k=self.top_k,
)
results = [self._docarray_to_langchain_doc(docs[idx]) for idx in mmr_selected]
return ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
2fd6f5423d7e-0 | Source code for langchain.retrievers.vespa_retriever
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Sequence, Union
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
if TYPE_CH... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
2fd6f5423d7e-1 | return docs
def _get_relevant_documents(
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
) -> List[Document]:
body = self.body.copy()
body["query"] = query
return self._query(body)
[docs] def get_relevant_documents_with_filter(
self, query: str, *, _fi... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
2fd6f5423d7e-2 | _filter (Optional[str]): Document filter condition expressed in YQL.
Defaults to None.
yql (Optional[str]): Full YQL query to be used. Should not be specified
if _filter or sources are specified. Defaults to None.
kwargs (Any): Keyword arguments added to query bod... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html |
715850000d75-0 | Source code for langchain.retrievers.chatgpt_plugin_retriever
from __future__ import annotations
from typing import List, Optional
import aiohttp
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetr... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html |
715850000d75-1 | return docs
async def _aget_relevant_documents(
self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun
) -> List[Document]:
url, json, headers = self._create_request(query)
if not self.aiosession:
async with aiohttp.ClientSession() as session:
a... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html |
d19c0701c922-0 | Source code for langchain.retrievers.databerry
from typing import List, Optional
import aiohttp
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
[docs]class DataberryRetriever(Bas... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html |
d19c0701c922-1 | self.datastore_url,
json={
"query": query,
**({"topK": self.top_k} if self.top_k is not None else {}),
},
headers={
"Content-Type": "application/json",
**(
{"Authorizat... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html |
345493eb23a8-0 | Source code for langchain.retrievers.weaviate_hybrid_search
from __future__ import annotations
from typing import Any, Dict, List, Optional, cast
from uuid import uuid4
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.docstore.document import Document
from langchain.pydantic_v1 impo... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
345493eb23a8-1 | client = values["client"]
raise ValueError(
f"client should be an instance of weaviate.Client, got {type(client)}"
)
if values.get("attributes") is None:
values["attributes"] = []
cast(List, values["attributes"]).append(values["text_key"])
if v... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
345493eb23a8-2 | return ids
def _get_relevant_documents(
self,
query: str,
*,
run_manager: CallbackManagerForRetrieverRun,
where_filter: Optional[Dict[str, object]] = None,
score: bool = False,
hybrid_search_kwargs: Optional[Dict[str, object]] = None,
) -> List[Document]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
345493eb23a8-3 | to be used during the hybrid search portion.
Example - hybrid_search_kwargs={"vector": [0.1, 0.2, 0.3, ...]}
https://weaviate.io/developers/weaviate/search/hybrid#with-a-custom-vector
4) Use Fusion ranking method
Example - from weaviate.gql.get import HybridFusion... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
7e8c66571dd0-0 | Source code for langchain.retrievers.kay
from __future__ import annotations
from typing import Any, List
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
[docs]class KayAiRetriever(BaseRetriever):
"""
Retriever for Kay.ai datasets.
T... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kay.html |
7e8c66571dd0-1 | def _get_relevant_documents(
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
) -> List[Document]:
ctxs = self.client.query(query=query, num_context=self.num_contexts)
docs = []
for ctx in ctxs:
page_content = ctx.pop("chunk_embed_text", None)
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kay.html |
7a282aeddfa5-0 | Source code for langchain.retrievers.pinecone_hybrid_search
"""Taken from: https://docs.pinecone.io/docs/hybrid-search"""
import hashlib
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.pydantic_v1 import Extra, root_validator
from langch... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
7a282aeddfa5-1 | if ids is None:
# create unique ids using hash of the text
ids = [hash_text(context) for context in contexts]
for i in _iterator:
# find end of batch
i_end = min(i + batch_size, len(contexts))
# extract batch
context_batch = contexts[i:i_end]
batch_ids = ids[i... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
7a282aeddfa5-2 | """Embeddings model to use."""
"""description"""
sparse_encoder: Any
"""Sparse encoder to use."""
index: Any
"""Pinecone index to use."""
top_k: int = 4
"""Number of documents to return."""
alpha: float = 0.5
"""Alpha value for hybrid search."""
namespace: Optional[str] = None
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
7a282aeddfa5-3 | self, query: str, *, run_manager: CallbackManagerForRetrieverRun
) -> List[Document]:
from pinecone_text.hybrid import hybrid_convex_scale
sparse_vec = self.sparse_encoder.encode_queries(query)
# convert the question into a dense vector
dense_vec = self.embeddings.embed_query(query)
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
c15c9ed4c47f-0 | Source code for langchain.retrievers.chaindesk
from typing import Any, List, Optional
import aiohttp
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
[docs]class ChaindeskRetrieve... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chaindesk.html |
c15c9ed4c47f-1 | )
for r in data["results"]
]
async def _aget_relevant_documents(
self,
query: str,
*,
run_manager: AsyncCallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
async with aiohttp.ClientSession() as session:
async with se... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chaindesk.html |
ac389678b51d-0 | Source code for langchain.retrievers.arxiv
from typing import List
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
from langchain.utilities.arxiv import ArxivAPIWrapper
[docs]class ArxivRetriever(BaseRetriever, ArxivAPIWrapper):
"""`Arxiv` ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/arxiv.html |
555ff3d3dc9d-0 | Source code for langchain.retrievers.ensemble
"""
Ensemble retriever that ensemble the results of
multiple retrievers by using weighted Reciprocal Rank Fusion
"""
from typing import Any, Dict, List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
555ff3d3dc9d-1 | Args:
query: The query to search for.
Returns:
A list of reranked documents.
"""
# Get fused result of the retrievers.
fused_documents = self.rank_fusion(query, run_manager)
return fused_documents
async def _aget_relevant_documents(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
555ff3d3dc9d-2 | self, query: str, run_manager: AsyncCallbackManagerForRetrieverRun
) -> List[Document]:
"""
Asynchronously retrieve the results of the retrievers
and use rank_fusion_func to get the final result.
Args:
query: The query to search for.
Returns:
A list of... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
555ff3d3dc9d-3 | for doc_list in doc_lists:
for doc in doc_list:
all_documents.add(doc.page_content)
# Initialize the RRF score dictionary for each document
rrf_score_dic = {doc: 0.0 for doc in all_documents}
# Calculate RRF scores for each document
for doc_list, weight in zip... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
51a579f23e95-0 | Source code for langchain.retrievers.metal
from typing import Any, List, Optional
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.pydantic_v1 import root_validator
from langchain.schema import BaseRetriever, Document
[docs]class MetalRetriever(BaseRetriever):
"""`Metal API` ret... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.