id stringlengths 14 16 | text stringlengths 31 3.14k | source stringlengths 58 124 |
|---|---|---|
81e43f2af96e-0 | Source code for langchain.vectorstores.deeplake
"""Wrapper around Activeloop Deep Lake."""
from __future__ import annotations
import logging
import uuid
from functools import partial
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
import numpy as np
from langchain.docstore.document imp... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-1 | """Naive search for nearest neighbors
args:
query_embedding: np.ndarray
data_vectors: np.ndarray
k (int): number of nearest neighbors
distance_metric: distance function 'L2' for Euclidean, 'L1' for Nuclear, 'Max'
l-infinity distnace, 'cos' for cosine similarity, 'dot' for... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-2 | We implement naive similarity search and filtering for fast prototyping,
but it can be extended with Tensor Query Language (TQL) for production use cases
over billion rows.
Why Deep Lake?
- Not only stores embeddings, but also the original data with version control.
- Serverless, doesn't require ano... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-3 | self.num_workers = num_workers
try:
import deeplake
from deeplake.constants import MB
except ImportError:
raise ValueError(
"Could not import deeplake python package. "
"Please install it with `pip install deeplake`."
)
... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-4 | "metadata",
htype="json",
create_id_tensor=False,
create_sample_info_tensor=False,
create_shape_tensor=False,
chunk_compression="lz4",
)
self.ds.create_tensor(
"embeddi... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-5 | """
if ids is None:
ids = [str(uuid.uuid1()) for _ in texts]
text_list = list(texts)
if metadatas is None:
metadatas = [{}] * len(text_list)
elements = list(zip(text_list, metadatas, ids))
@self._deeplake.compute
def ingest(sample_in: list, sample_... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-6 | **kwargs,
)
self.ds.commit(allow_empty=True)
self.ds.summary()
return ids
[docs] def search(
self,
query: Any[str, None] = None,
embedding: Any[float, None] = None,
k: int = 4,
distance_metric: str = "L2",
use_maximal_marginal_relevance:... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-7 | Defaults to None.
maximal_marginal_relevance: Whether to use maximal marginal relevance.
Defaults to False.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
Defaults to 20.
return_score: Whether to return the score. Defaults to False.
... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-8 | query_emb,
embeddings,
k=k_search,
distance_metric=distance_metric.lower(),
)
view = view[indices]
if use_maximal_marginal_relevance:
lambda_mult = kwargs.get("lambda_mult", 0.5)
indices = maximal_margina... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-9 | L-infinity distance, `cos` for cosine similarity, 'dot' for dot product
Defaults to `L2`.
filter: Attribute filter by metadata example {'key': 'value'}.
Defaults to None.
maximal_marginal_relevance: Whether to use maximal marginal relevance.
Defaul... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-10 | """Run similarity search with Deep Lake with distance returned.
Args:
query (str): Query text to search for.
distance_metric: `L2` for Euclidean, `L1` for Nuclear, `max` L-infinity
distance, `cos` for cosine similarity, 'dot' for dot product.
Defaults to `... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-11 | to maximum diversity and 1 to minimum diversity.
Defaults to 0.5.
Returns:
List of Documents selected by maximal marginal relevance.
"""
return self.search(
embedding=embedding,
k=k,
fetch_k=fetch_k,
use_maximal_... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-12 | lambda_mult=lambda_mult,
)
[docs] @classmethod
def from_texts(
cls,
texts: List[str],
embedding: Optional[Embeddings] = None,
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
dataset_path: str = _LANGCHAIN_DEFAULT_DEEPLAKE_PATH,
... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-13 | Should be used only for testing as it does not persist.
documents (List[Document]): List of documents to add.
embedding (Optional[Embeddings]): Embedding function. Defaults to None.
metadatas (Optional[List[dict]]): List of metadatas. Defaults to None.
ids (Optional[List[... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
81e43f2af96e-14 | return True
view = None
if ids:
view = self.ds.filter(lambda x: x["ids"].data()["value"] in ids)
ids = list(view.sample_indices)
if filter:
if view is None:
view = self.ds
view = view.filter(partial(dp_filter, filter=filter))
... | /content/https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html |
4d43f4e1ace6-0 | Source code for langchain.memory.buffer
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.memory.chat_memory import BaseChatMemory, BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema import get_buffer_string
[docs]class ConversationBuff... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
4d43f4e1ace6-1 | """Buffer for storing conversation memory."""
human_prefix: str = "Human"
ai_prefix: str = "AI"
"""Prefix to use for AI generated responses."""
buffer: str = ""
output_key: Optional[str] = None
input_key: Optional[str] = None
memory_key: str = "history" #: :meta private:
@root_validator... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
4d43f4e1ace6-2 | else:
prompt_input_key = self.input_key
if self.output_key is None:
if len(outputs) != 1:
raise ValueError(f"One output key expected, got {outputs.keys()}")
output_key = list(outputs.keys())[0]
else:
output_key = self.output_key
hum... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
84149b90113f-0 | Source code for langchain.memory.token_buffer
from typing import Any, Dict, List
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseLanguageModel, BaseMessage, get_buffer_string
[docs]class ConversationTokenBufferMemory(BaseChatMemory):
"""Buffer for storing conversation memory... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
84149b90113f-1 | )
return {self.memory_key: final_buffer}
[docs] def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:
"""Save context from this conversation to buffer. Pruned."""
super().save_context(inputs, outputs)
# Prune buffer if it exceeds max token limit
buff... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
c99c308f5ce9-0 | Source code for langchain.memory.readonly
from typing import Any, Dict, List
from langchain.schema import BaseMemory
[docs]class ReadOnlySharedMemory(BaseMemory):
"""A memory wrapper that is read-only and cannot be changed."""
memory: BaseMemory
@property
def memory_variables(self) -> List[str]:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/readonly.html |
a564d23cf71e-0 | Source code for langchain.memory.combined
from typing import Any, Dict, List
from langchain.schema import BaseMemory
[docs]class CombinedMemory(BaseMemory):
"""Class for combining multiple memories' data together."""
memories: List[BaseMemory]
"""For tracking all the memories that should be accessed."""
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
a564d23cf71e-1 | memory.save_context(inputs, outputs)
[docs] def clear(self) -> None:
"""Clear context from this session for every memory."""
for memory in self.memories:
memory.clear()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
d1f0e8687a2d-0 | Source code for langchain.memory.buffer_window
from typing import Any, Dict, List
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationBufferWindowMemory(BaseChatMemory):
"""Buffer for storing conversation memory."""
human_pr... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html |
43d7d5e7011a-0 | Source code for langchain.memory.simple
from typing import Any, Dict, List
from langchain.schema import BaseMemory
[docs]class SimpleMemory(BaseMemory):
"""Simple memory for storing context or other bits of information that shouldn't
ever change between prompts.
"""
memories: Dict[str, Any] = dict()
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/simple.html |
f87c77f88c46-0 | Source code for langchain.memory.entity
import logging
from abc import ABC, abstractmethod
from itertools import islice
from typing import Any, Dict, Iterable, List, Optional
from pydantic import Field
from langchain.chains.llm import LLMChain
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memor... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
f87c77f88c46-1 | """Delete all entities from store."""
pass
[docs]class InMemoryEntityStore(BaseEntityStore):
"""Basic in-memory entity store."""
store: Dict[str, Optional[str]] = {}
[docs] def get(self, key: str, default: Optional[str] = None) -> Optional[str]:
return self.store.get(key, default)
[docs] d... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
f87c77f88c46-2 | key_prefix: str = "memory_store",
ttl: Optional[int] = 60 * 60 * 24,
recall_ttl: Optional[int] = 60 * 60 * 24 * 3,
*args: Any,
**kwargs: Any,
):
try:
import redis
except ImportError:
raise ValueError(
"Could not import redis pyt... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
f87c77f88c46-3 | if not value:
return self.delete(key)
self.redis_client.set(f"{self.full_key_prefix}:{key}", value, ex=self.ttl)
logger.debug(
f"REDIS MEM set '{self.full_key_prefix}:{key}': '{value}' EX {self.ttl}"
)
[docs] def delete(self, key: str) -> None:
self.redis_clien... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
f87c77f88c46-4 | ai_prefix: str = "AI"
llm: BaseLanguageModel
entity_extraction_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT
entity_summarization_prompt: BasePromptTemplate = ENTITY_SUMMARIZATION_PROMPT
entity_cache: List[str] = []
k: int = 3
chat_history_key: str = "history"
entity_store: BaseEntit... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
f87c77f88c46-5 | human_prefix=self.human_prefix,
ai_prefix=self.ai_prefix,
)
output = chain.predict(
history=buffer_string,
input=inputs[prompt_input_key],
)
if output.strip() == "NONE":
entities = []
else:
entities = [w.strip() for w in... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
f87c77f88c46-6 | ai_prefix=self.ai_prefix,
)
input_data = inputs[prompt_input_key]
chain = LLMChain(llm=self.llm, prompt=self.entity_summarization_prompt)
for entity in self.entity_cache:
existing_summary = self.entity_store.get(entity, "")
output = chain.predict(
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
859b0ec856d1-0 | Source code for langchain.memory.summary_buffer
from typing import Any, Dict, List
from pydantic import root_validator
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.summary import SummarizerMixin
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationSummaryB... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
859b0ec856d1-1 | else:
final_buffer = get_buffer_string(
buffer, human_prefix=self.human_prefix, ai_prefix=self.ai_prefix
)
return {self.memory_key: final_buffer}
@root_validator()
def validate_prompt_input_variables(cls, values: Dict) -> Dict:
"""Validate that prompt inpu... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
859b0ec856d1-2 | pruned_memory.append(buffer.pop(0))
curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)
self.moving_summary_buffer = self.predict_new_summary(
pruned_memory, self.moving_summary_buffer
)
[docs] def clear(self) -> None:
"""Clear memory con... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
c1f551439656-0 | Source code for langchain.memory.kg
from typing import Any, Dict, List, Type, Union
from pydantic import Field
from langchain.chains.llm import LLMChain
from langchain.graphs import NetworkxEntityGraph
from langchain.graphs.networkx_graph import KnowledgeTriple, get_entities, parse_triples
from langchain.memory.chat_me... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
c1f551439656-1 | llm: BaseLanguageModel
summary_message_cls: Type[BaseMessage] = SystemMessage
"""Number of previous utterances to include in the context."""
memory_key: str = "history" #: :meta private:
[docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:
"""Return history buffer.""... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
c1f551439656-2 | if self.input_key is None:
return get_prompt_input_key(inputs, self.memory_variables)
return self.input_key
def _get_prompt_output_key(self, outputs: Dict[str, Any]) -> str:
"""Get the output key for the prompt."""
if self.output_key is None:
if len(outputs) != 1:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
c1f551439656-3 | [docs] def get_knowledge_triplets(self, input_string: str) -> List[KnowledgeTriple]:
chain = LLMChain(llm=self.llm, prompt=self.knowledge_extraction_prompt)
buffer_string = get_buffer_string(
self.chat_memory.messages[-self.k * 2 :],
human_prefix=self.human_prefix,
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
c1f551439656-4 | super().clear()
self.kg.clear()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
0d296d304f41-0 | Source code for langchain.memory.summary
from typing import Any, Dict, List, Type
from pydantic import BaseModel, root_validator
from langchain.chains.llm import LLMChain
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.prompt import SUMMARY_PROMPT
from langchain.prompts.base import BasePro... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
0d296d304f41-1 | memory_key: str = "history" #: :meta private:
@property
def memory_variables(self) -> List[str]:
"""Will always return list of memory variables.
:meta private:
"""
return [self.memory_key]
[docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
0d296d304f41-2 | self.buffer = self.predict_new_summary(
self.chat_memory.messages[-2:], self.buffer
)
[docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.buffer = ""
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 2... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
fcac1fa4871d-0 | Source code for langchain.memory.vectorstore
"""Class for a VectorStore-backed memory object."""
from typing import Any, Dict, List, Optional, Union
from pydantic import Field
from langchain.memory.chat_memory import BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema import Documen... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
fcac1fa4871d-1 | if self.input_key is None:
return get_prompt_input_key(inputs, self.memory_variables)
return self.input_key
[docs] def load_memory_variables(
self, inputs: Dict[str, Any]
) -> Dict[str, Union[List[Document], str]]:
"""Return history buffer."""
input_key = self._get_pro... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
fcac1fa4871d-2 | return [Document(page_content=page_content)]
[docs] def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:
"""Save context from this conversation to buffer."""
documents = self._form_documents(inputs, outputs)
self.retriever.add_documents(documents)
[docs] def cle... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
f10f3c29932c-0 | Source code for langchain.memory.chat_message_histories.in_memory
from typing import List
from pydantic import BaseModel
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
)
[docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel):
messages: List[Ba... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html |
e2aafddb3183-0 | Source code for langchain.memory.chat_message_histories.cosmos_db
"""Azure CosmosDB Memory History."""
from __future__ import annotations
import logging
from types import TracebackType
from typing import TYPE_CHECKING, Any, List, Optional, Type
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
e2aafddb3183-1 | :param user_id: The user ID to use, can be overwritten while loading.
:param ttl: The time to live (in seconds) to use for documents in the container.
"""
self.cosmos_endpoint = cosmos_endpoint
self.cosmos_database = cosmos_database
self.cosmos_container = cosmos_container
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
e2aafddb3183-2 | self.cosmos_container,
partition_key=PartitionKey("/user_id"),
default_ttl=self.ttl,
)
self.load_messages()
def __enter__(self) -> "CosmosDBChatMessageHistory":
"""Context manager entry point."""
if self._client:
self._client.__enter__()
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
e2aafddb3183-3 | item=self.session_id, partition_key=self.user_id
)
except CosmosHttpResponseError:
logger.info("no session found")
return
if (
"messages" in item
and len(item["messages"]) > 0
and isinstance(item["messages"][0], list)
):
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
e2aafddb3183-4 | self.messages = []
if self._container:
self._container.delete_item(
item=self.session_id, partition_key=self.user_id
)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
df00e23096d0-0 | Source code for langchain.memory.chat_message_histories.postgres
import json
import logging
from typing import List
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
DEFAULT_CO... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
df00e23096d0-1 | self.cursor.execute(create_table_query)
self.connection.commit()
@property
def messages(self) -> List[BaseMessage]: # type: ignore
"""Retrieve the messages from PostgreSQL"""
query = f"SELECT message FROM {self.table_name} WHERE session_id = %s;"
self.cursor.execute(query, (self... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
df00e23096d0-2 | """Clear session memory from PostgreSQL"""
query = f"DELETE FROM {self.table_name} WHERE session_id = %s;"
self.cursor.execute(query, (self.session_id,))
self.connection.commit()
def __del__(self) -> None:
if self.cursor:
self.cursor.close()
if self.connection:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
12dc64118beb-0 | Source code for langchain.memory.chat_message_histories.redis
import json
import logging
from typing import List, Optional
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
[do... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
12dc64118beb-1 | items = [json.loads(m.decode("utf-8")) for m in _items[::-1]]
messages = messages_from_dict(items)
return messages
[docs] def add_user_message(self, message: str) -> None:
self.append(HumanMessage(content=message))
[docs] def add_ai_message(self, message: str) -> None:
self.append(... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
6ce2f5ce4a8a-0 | Source code for langchain.memory.chat_message_histories.dynamodb
import logging
from typing import List
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,
messages_from_dict,
messages_to_dict,
)
logger = logging.getLogger(__name__)
... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
6ce2f5ce4a8a-1 | logger.warning("No record found with session id: %s", self.session_id)
else:
logger.error(error)
if response and "Item" in response:
items = response["Item"]["History"]
else:
items = []
messages = messages_from_dict(items)
return messag... | /content/https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
22f3f3df76b6-0 | Source code for langchain.retrievers.remote_retriever
from typing import List, Optional
import aiohttp
import requests
from pydantic import BaseModel
from langchain.schema import BaseRetriever, Document
[docs]class RemoteLangChainRetriever(BaseRetriever, BaseModel):
url: str
headers: Optional[dict] = None
i... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html |
22f3f3df76b6-1 | )
for r in result[self.response_key]
]
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html |
796010062aa3-0 | Source code for langchain.retrievers.weaviate_hybrid_search
"""Wrapper around weaviate vector database."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from uuid import uuid4
from pydantic import Extra
from langchain.docstore.document import Document
from langchain.schema import BaseR... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
796010062aa3-1 | arbitrary_types_allowed = True
# added text_key
[docs] def add_documents(self, docs: List[Document]) -> List[str]:
"""Upload documents to Weaviate."""
from weaviate.util import get_valid_uuid
with self._client.batch as batch:
ids = []
for i, doc in enumerate(docs):... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
796010062aa3-2 | text = res.pop(self._text_key)
docs.append(Document(page_content=text, metadata=res))
return docs
[docs] async def aget_relevant_documents(
self, query: str, where_filter: Optional[Dict[str, object]] = None
) -> List[Document]:
raise NotImplementedError
By Harrison Chase
... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
04671482a920-0 | Source code for langchain.retrievers.metal
from typing import Any, List, Optional
from langchain.schema import BaseRetriever, Document
[docs]class MetalRetriever(BaseRetriever):
def __init__(self, client: Any, params: Optional[dict] = None):
from metal_sdk.metal import Metal
if not isinstance(client... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html |
3bbb8c48d83a-0 | Source code for langchain.retrievers.chatgpt_plugin_retriever
from __future__ import annotations
from typing import List, Optional
import aiohttp
import requests
from pydantic import BaseModel
from langchain.schema import BaseRetriever, Document
[docs]class ChatGPTPluginRetriever(BaseRetriever, BaseModel):
url: str... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html |
3bbb8c48d83a-1 | async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=json) as response:
res = await response.json()
else:
async with self.aiosession.post(
url, headers=headers, json=json
) as response:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html |
62e3d14192b2-0 | Source code for langchain.retrievers.svm
"""SMV 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 pydantic import BaseModel
from langchain.embedding... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
62e3d14192b2-1 | [docs] def get_relevant_documents(self, query: str) -> List[Document]:
from sklearn import svm
query_embeds = np.array(self.embeddings.embed_query(query))
x = np.concatenate([query_embeds[None, ...], self.index])
y = np.zeros(x.shape[0])
y[0] = 1
clf = svm.LinearSVC(
... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
62e3d14192b2-2 | for row in sorted_ix[1 : self.k + 1]:
if (
self.relevancy_threshold is None
or normalized_similarities[row] >= self.relevancy_threshold
):
top_k_results.append(Document(page_content=self.texts[row - 1]))
return top_k_results
[docs] async... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
bea5e42c9f37-0 | Source code for langchain.retrievers.tfidf
"""TF-IDF Retriever.
Largely based on
https://github.com/asvskartheek/Text-Retrieval/blob/master/TF-IDF%20Search%20Engine%20(SKLEARN).ipynb"""
from typing import Any, Dict, List, Optional
from pydantic import BaseModel
from langchain.schema import BaseRetriever, Document
[docs... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
bea5e42c9f37-1 | [docs] def get_relevant_documents(self, query: str) -> List[Document]:
from sklearn.metrics.pairwise import cosine_similarity
query_vec = self.vectorizer.transform(
[query]
) # Ip -- (n_docs,x), Op -- (n_docs,n_Feats)
results = cosine_similarity(self.tfidf_array, query_ve... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html |
ea9dc459da01-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 pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.schema import BaseRe... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
ea9dc459da01-1 | # create dense vectors
dense_embeds = embeddings.embed_documents(context_batch)
# create sparse vectors
sparse_embeds = sparse_encoder.encode_documents(context_batch)
for s in sparse_embeds:
s["values"] = [float(s1) for s1 in s["values"]]
vectors = []
# loop t... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
ea9dc459da01-2 | def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
try:
from pinecone_text.hybrid import hybrid_convex_scale # noqa:F401
from pinecone_text.sparse.base_sparse_encoder import (
BaseSparseEncod... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
ea9dc459da01-3 | )
final_result = []
for res in result["matches"]:
final_result.append(Document(page_content=res["metadata"]["context"]))
# return search results as json
return final_result
[docs] async def aget_relevant_documents(self, query: str) -> List[Document]:
raise NotImple... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
2d46ce9a414c-0 | Source code for langchain.retrievers.time_weighted_retriever
"""Retriever that combines embedding similarity with recency in retrieving values."""
from copy import deepcopy
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from pydantic import BaseModel, Field
from langchain.schema impor... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
2d46ce9a414c-1 | """The maximum number of documents to retrieve in a given call."""
other_score_keys: List[str] = []
"""Other keys in the metadata to factor into the score, e.g. 'importance'."""
default_salience: Optional[float] = None
"""The salience to assign memories not retrieved from the vector store.
None assi... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
2d46ce9a414c-2 | docs_and_scores: List[Tuple[Document, float]]
docs_and_scores = self.vectorstore.similarity_search_with_relevance_scores(
query, **self.search_kwargs
)
results = {}
for fetched_doc, relevance in docs_and_scores:
buffer_idx = fetched_doc.metadata["buffer_idx"]
... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
2d46ce9a414c-3 | for doc, _ in rescored_docs[: self.k]:
# TODO: Update vector store doc once `update` method is exposed.
buffered_doc = self.memory_stream[doc.metadata["buffer_idx"]]
buffered_doc.metadata["last_accessed_at"] = current_time
result.append(buffered_doc)
return result... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
2d46ce9a414c-4 | [docs] async def aadd_documents(
self, documents: List[Document], **kwargs: Any
) -> List[str]:
"""Add documents to vectorstore."""
current_time = kwargs.get("current_time", datetime.now())
# Avoid mutating input documents
dup_docs = [deepcopy(d) for d in documents]
... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
efe582636de0-0 | Source code for langchain.retrievers.contextual_compression
"""Retriever that wraps a base retriever and filters the results."""
from typing import List
from pydantic import BaseModel, Extra
from langchain.retrievers.document_compressors.base import (
BaseDocumentCompressor,
)
from langchain.schema import BaseRetri... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html |
efe582636de0-1 | Args:
query: string to find relevant documents for
Returns:
List of relevant documents
"""
docs = await self.base_retriever.aget_relevant_documents(query)
compressed_docs = await self.base_compressor.acompress_documents(docs, query)
return list(compressed_... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html |
610beb3fd4da-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.docstore.document import Document
from langchain.schema import BaseRetriever
[docs]class ElasticSearchBM25Retr... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
610beb3fd4da-1 | def __init__(self, client: Any, index_name: str):
self.client = client
self.index_name = index_name
[docs] @classmethod
def create(
cls, elasticsearch_url: str, index_name: str, k1: float = 2.0, b: float = 0.75
) -> ElasticSearchBM25Retriever:
from elasticsearch import Elastic... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
610beb3fd4da-2 | refresh_indices: bool to refresh ElasticSearch indices
Returns:
List of ids from adding the texts into the retriever.
"""
try:
from elasticsearch.helpers import bulk
except ImportError:
raise ValueError(
"Could not import elasticsearch ... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html |
c185ba87a053-0 | Source code for langchain.retrievers.databerry
from typing import List, Optional
import aiohttp
import requests
from langchain.schema import BaseRetriever, Document
[docs]class DataberryRetriever(BaseRetriever):
datastore_url: str
top_k: Optional[int]
api_key: Optional[str]
def __init__(
self,
... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html |
c185ba87a053-1 | async with aiohttp.ClientSession() as session:
async with session.request(
"POST",
self.datastore_url,
json={
"query": query,
**({"topK": self.top_k} if self.top_k is not None else {}),
},
... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html |
61dcd301bfc2-0 | Source code for langchain.retrievers.document_compressors.embeddings_filter
"""Document compressor that uses embeddings to drop documents unrelated to the query."""
from typing import Callable, Dict, Optional, Sequence
import numpy as np
from pydantic import root_validator
from langchain.document_transformers import (
... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
61dcd301bfc2-1 | to None."""
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
@root_validator()
def validate_params(cls, values: Dict) -> Dict:
"""Validate similarity parameters."""
if values["k"] is None and values["similarity_threshold"] is None:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
61dcd301bfc2-2 | )
included_idxs = included_idxs[similar_enough]
return [stateful_documents[i] for i in included_idxs]
[docs] async def acompress_documents(
self, documents: Sequence[Document], query: str
) -> Sequence[Document]:
"""Filter down documents."""
raise NotImplementedError
B... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
896a92377a51-0 | Source code for langchain.retrievers.document_compressors.chain_extract
"""DocumentFilter that uses an LLM chain to extract the relevant parts of documents."""
from typing import Any, Callable, Dict, Optional, Sequence
from langchain import LLMChain, PromptTemplate
from langchain.retrievers.document_compressors.base im... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
896a92377a51-1 | return PromptTemplate(
template=template,
input_variables=["question", "context"],
output_parser=output_parser,
)
[docs]class LLMChainExtractor(BaseDocumentCompressor):
llm_chain: LLMChain
"""LLM wrapper to use for compressing documents."""
get_input: Callable[[str, Document], di... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
896a92377a51-2 | ) -> "LLMChainExtractor":
"""Initialize from LLM."""
_prompt = prompt if prompt is not None else _get_default_chain_prompt()
_get_input = get_input if get_input is not None else default_get_input
llm_chain = LLMChain(llm=llm, prompt=_prompt)
return cls(llm_chain=llm_chain, get_in... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
8a9e5353e1e9-0 | Source code for langchain.retrievers.document_compressors.chain_filter
"""Filter that uses an LLM to drop documents that aren't relevant to the query."""
from typing import Any, Callable, Dict, Optional, Sequence
from langchain import BasePromptTemplate, LLMChain, PromptTemplate
from langchain.output_parsers.boolean im... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html |
8a9e5353e1e9-1 | The chain prompt is expected to have a BooleanOutputParser."""
get_input: Callable[[str, Document], dict] = default_get_input
"""Callable for constructing the chain input from the query and a Document."""
[docs] def compress_documents(
self, documents: Sequence[Document], query: str
) -> Sequence... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html |
63e0b4b6eb56-0 | Source code for langchain.retrievers.document_compressors.base
"""Interface for retrieved document compressors."""
from abc import ABC, abstractmethod
from typing import List, Sequence, Union
from pydantic import BaseModel
from langchain.schema import BaseDocumentTransformer, Document
class BaseDocumentCompressor(BaseM... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html |
63e0b4b6eb56-1 | if isinstance(_transformer, BaseDocumentCompressor):
documents = _transformer.compress_documents(documents, query)
elif isinstance(_transformer, BaseDocumentTransformer):
documents = _transformer.transform_documents(documents)
else:
raise ValueErro... | /content/https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html |
f233ee6cac97-0 | Source code for langchain.tools.ifttt
"""From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services.
# Creating a webhook
- Go to https://ifttt.com/create
# Configuring the "If This"
- Click on the "If This" button in the IFTTT interface.
- Search for "Webhooks" in the search bar.
- Choose the first... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html |
f233ee6cac97-1 | - Congratulations! You have successfully connected the Webhook to the desired
service, and you're ready to start receiving data and triggering actions 🎉
# Finishing up
- To get your webhook URL go to https://ifttt.com/maker_webhooks/settings
- Copy the IFTTT key value from there. The URL is of the form
https://maker.i... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.