id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
f26a4f61091c-0 | Source code for langchain.agents.chat.output_parser
import json
import re
from typing import Union
from langchain.agents.agent import AgentOutputParser
from langchain.agents.chat.prompt import FORMAT_INSTRUCTIONS
from langchain.schema import AgentAction, AgentFinish, OutputParserException
FINAL_ANSWER_ACTION = "Final A... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/chat/output_parser.html |
f26a4f61091c-1 | @property
def _type(self) -> str:
return "chat" | https://api.python.langchain.com/en/latest/_modules/langchain/agents/chat/output_parser.html |
2e91e2eacc57-0 | Source code for langchain.agents.conversational_chat.base
"""An agent designed to hold a conversation in addition to using tools."""
from __future__ import annotations
from typing import Any, List, Optional, Sequence, Tuple
from pydantic import Field
from langchain.agents.agent import Agent, AgentOutputParser
from lang... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html |
2e91e2eacc57-1 | """Prefix to append the llm call with."""
return "Thought:"
@classmethod
def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
super()._validate_tools(tools)
validate_tools_single_input(cls.__name__, tools)
[docs] @classmethod
def create_prompt(
cls,
tools: ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html |
2e91e2eacc57-2 | """Construct the scratchpad that lets the agent continue its thought process."""
thoughts: List[BaseMessage] = []
for action, observation in intermediate_steps:
thoughts.append(AIMessage(content=action.log))
human_message = HumanMessage(
content=self.template_tool... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html |
0acadc827a52-0 | Source code for langchain.agents.conversational_chat.output_parser
from __future__ import annotations
from typing import Union
from langchain.agents import AgentOutputParser
from langchain.agents.conversational_chat.prompt import FORMAT_INSTRUCTIONS
from langchain.output_parsers.json import parse_json_markdown
from lan... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/output_parser.html |
0acadc827a52-1 | # exception
raise OutputParserException(
f"Missing 'action' or 'action_input' in LLM output: {text}"
)
except Exception as e:
# If any other exception is raised during parsing, also raise an
# OutputParserException
raise Out... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/output_parser.html |
c14a5cd6965c-0 | Source code for langchain.agents.mrkl.base
"""Attempt to implement MRKL systems as described in arxiv.org/pdf/2205.00445.pdf."""
from __future__ import annotations
from typing import Any, Callable, List, NamedTuple, Optional, Sequence
from pydantic import Field
from langchain.agents.agent import Agent, AgentExecutor, A... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
c14a5cd6965c-1 | @property
def observation_prefix(self) -> str:
"""Prefix to append the observation with."""
return "Observation: "
@property
def llm_prefix(self) -> str:
"""Prefix to append the llm call with."""
return "Thought:"
[docs] @classmethod
def create_prompt(
cls,
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
c14a5cd6965c-2 | llm: BaseLanguageModel,
tools: Sequence[BaseTool],
callback_manager: Optional[BaseCallbackManager] = None,
output_parser: Optional[AgentOutputParser] = None,
prefix: str = PREFIX,
suffix: str = SUFFIX,
format_instructions: str = FORMAT_INSTRUCTIONS,
input_variable... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
c14a5cd6965c-3 | f"a description must always be provided."
)
super()._validate_tools(tools)
[docs]class MRKLChain(AgentExecutor):
"""Chain that implements the MRKL system.
Example:
.. code-block:: python
from langchain import OpenAI, MRKLChain
from langchain.chains.mrkl.ba... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
c14a5cd6965c-4 | action_description="useful for searching"
),
ChainConfig(
action_name="Calculator",
action=llm_math_chain.run,
action_description="useful for doing math"
)
]
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
0507e559e3bd-0 | Source code for langchain.agents.mrkl.output_parser
import re
from typing import Union
from langchain.agents.agent import AgentOutputParser
from langchain.agents.mrkl.prompt import FORMAT_INSTRUCTIONS
from langchain.schema import AgentAction, AgentFinish, OutputParserException
FINAL_ANSWER_ACTION = "Final Answer:"
MISS... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/output_parser.html |
0507e559e3bd-1 | # ensure if its a well formed SQL query we don't remove any trailing " chars
if tool_input.startswith("SELECT ") is False:
tool_input = tool_input.strip('"')
return AgentAction(action, tool_input, text)
elif includes_answer:
return AgentFinish(
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/output_parser.html |
3ebaa66ac351-0 | Source code for langchain.retrievers.azure_cognitive_search
"""Retriever for the Azure Cognitive Search service."""
from __future__ import annotations
import json
from typing import Dict, List, Optional
import aiohttp
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import (
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html |
3ebaa66ac351-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 |
3ebaa66ac351-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 |
98c5d77008b7-0 | Source code for langchain.retrievers.zep
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema impor... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html |
98c5d77008b7-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 |
6f7604943254-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):
"""
Ret... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/arxiv.html |
b68dc0e387fb-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):
"""Ret... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pubmed.html |
ad34ef50c473-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 pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
ad34ef50c473-1 | 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,
query: str,
*,
run_manager: AsyncCallba... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
ad34ef50c473-2 | ) -> 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 reranked documents.
"""
# Get the results of all retri... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
ad34ef50c473-3 | # 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(doc_lists, self.weights):
for rank, doc in enumerate(doc_list, start=1):
rrf_score = weight... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/ensemble.html |
8d5c78dc4968-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 |
8d5c78dc4968-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 |
7e05c55af33f-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 |
7e05c55af33f-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 |
7e05c55af33f-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 |
d346995cab4d-0 | Source code for langchain.retrievers.zilliz
import warnings
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.embeddings.base import Embeddings
from langchain.schema import BaseRetriever, Document
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html |
d346995cab4d-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 |
ddbed6732285-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 |
ddbed6732285-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 |
e031e0c213f0-0 | Source code for langchain.retrievers.multi_query
import logging
from typing import List
from pydantic import BaseModel, Field
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.chains.llm import LLMChain
from langchain.llms.base import BaseLLM
from langchain.output_parsers.pydantic im... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
e031e0c213f0-1 | """Given a user query, use an LLM to write a set of queries.
Retrieve docs for each query. Rake the unique union of all retrieved docs."""
retriever: BaseRetriever
llm_chain: LLMChain
verbose: bool = True
parser_key: str = "lines"
[docs] @classmethod
def from_llm(
cls,
retriev... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
e031e0c213f0-2 | return unique_documents
[docs] def generate_queries(
self, question: str, run_manager: CallbackManagerForRetrieverRun
) -> List[str]:
"""Generate queries based upon user input.
Args:
question: user query
Returns:
List of LLM generated queries that are simil... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/multi_query.html |
3f7404a0233a-0 | Source code for langchain.retrievers.parent_document_retriever
import uuid
from typing import Any, Dict, List, Optional
from langchain.callbacks.base import Callbacks
from langchain.schema.document import Document
from langchain.schema.retriever import BaseRetriever
from langchain.schema.storage import BaseStore
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/parent_document_retriever.html |
3f7404a0233a-1 | # It should create documents smaller than the parent
child_splitter = RecursiveCharacterTextSplitter(chunk_size=400)
# The vectorstore to use to index the child chunks
vectorstore = Chroma(embedding_function=OpenAIEmbeddings())
# The storage layer for the parent documents
store =... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/parent_document_retriever.html |
3f7404a0233a-2 | ids = []
for d in sub_docs:
if d.metadata[self.id_key] not in ids:
ids.append(d.metadata[self.id_key])
docs = self.docstore.mget(ids)
return [d for d in docs if d is not None]
[docs] def add_documents(
self,
documents: List[Document],
ids: O... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/parent_document_retriever.html |
3f7404a0233a-3 | raise ValueError(
"Got uneven list of documents and ids. "
"If `ids` is provided, should be same length as `documents`."
)
doc_ids = ids
docs = []
full_docs = []
for i, doc in enumerate(documents):
_id = doc_ids[i]
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/parent_document_retriever.html |
86efacb4c53b-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 |
86efacb4c53b-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 |
8349a5bc03f7-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 |
8349a5bc03f7-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 |
4912be59d0b0-0 | Source code for langchain.retrievers.wikipedia
from typing import List
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
from langchain.utilities.wikipedia import WikipediaAPIWrapper
[docs]class WikipediaRetriever(BaseRetriever, WikipediaAPIWrapp... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/wikipedia.html |
a4b723bfd839-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 pydantic import Extra, Field, root_validator
from langchain.cal... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_enterprise_search.html |
a4b723bfd839-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 |
a4b723bfd839-2 | _serving_config: str
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
underscore_attrs_are_private = True
@root_validator(pre=True)
def validate_environment(cls, values: Dict) -> Dict:
"""Validates the env... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_enterprise_search.html |
a4b723bfd839-3 | for result in results:
document_dict = MessageToDict(
result.document._pb, preserving_proto_field_name=True
)
derived_struct_data = document_dict.get("derived_struct_data", None)
if not derived_struct_data:
continue
doc_metadata... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_enterprise_search.html |
a4b723bfd839-4 | max_extractive_segment_count=self.max_extractive_segment_count,
)
)
content_search_spec = SearchRequest.ContentSearchSpec(
extractive_content_spec=extractive_content_spec,
)
return SearchRequest(
query=query,
filter=self.filter,
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/google_cloud_enterprise_search.html |
347aa0556f1e-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 |
347aa0556f1e-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 |
347aa0556f1e-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 |
e165b9bcd978-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 |
e165b9bcd978-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 |
e165b9bcd978-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 |
6bf3e2b2ef1f-0 | Source code for langchain.retrievers.llama_index
from typing import Any, Dict, List, cast
from pydantic import Field
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
[docs]class LlamaIndexRetriever(BaseRetriever):
"""Retriever for the questi... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
6bf3e2b2ef1f-1 | 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: str, *, run_manager: CallbackManagerForRetrieverRun
) -> List[Document]:
"""Get docum... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html |
9c2c9b600ffd-0 | Source code for langchain.retrievers.kendra
import re
from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Union
from pydantic import BaseModel, Extra, root_validator, validator
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchai... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
9c2c9b600ffd-1 | """The zero-based location in the excerpt where the highlight starts."""
EndOffset: int
"""The zero-based location in the excerpt where the highlight ends."""
TopAnswer: Optional[bool]
"""Indicates whether the result is the best one."""
Type: Optional[str]
"""The highlight type: STANDARD or THES... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
9c2c9b600ffd-2 | """The only defined document attribute value or None.
According to Amazon Kendra, you can only provide one
value for a document attribute.
"""
if self.DateValue:
return self.DateValue
if self.LongValue:
return self.LongValue
if self.StringListValue... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
9c2c9b600ffd-3 | """Document attributes dict."""
return {attr.Key: attr.Value.value for attr in (self.DocumentAttributes or [])}
[docs] def to_doc(
self, page_content_formatter: Callable[["ResultItem"], str] = combined_text
) -> Document:
"""Converts this item to a Document."""
page_content = page... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
9c2c9b600ffd-4 | [docs] def get_attribute_value(self) -> str:
if not self.AdditionalAttributes:
return ""
if not self.AdditionalAttributes[0]:
return ""
else:
return self.AdditionalAttributes[0].get_value_text()
[docs] def get_excerpt(self) -> str:
if (
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
9c2c9b600ffd-5 | """
Represents an Amazon Kendra Retrieve API search result, which is composed of:
* relevant passages or text excerpts given an input query.
"""
QueryId: str
"""The ID of the query."""
ResultItems: List[RetrieveResultItem]
"""The result items."""
[docs]class AmazonKendraRetriever(BaseRet... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
9c2c9b600ffd-6 | """
index_id: str
region_name: Optional[str] = None
credentials_profile_name: Optional[str] = None
top_k: int = 3
attribute_filter: Optional[Dict] = None
page_content_formatter: Callable[[ResultItem], str] = combined_text
client: Any
user_context: Optional[Dict] = None
@validator("to... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
9c2c9b600ffd-7 | kendra_kwargs = {
"IndexId": self.index_id,
"QueryText": query.strip(),
"PageSize": self.top_k,
}
if self.attribute_filter is not None:
kendra_kwargs["AttributeFilter"] = self.attribute_filter
if self.user_context is not None:
kendra_kw... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html |
f7299f0de97e-0 | Source code for langchain.retrievers.bm25
"""
BM25 Retriever without elastic search
"""
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]de... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/bm25.html |
f7299f0de97e-1 | preprocess_func: A function to preprocess each text before vectorization.
**kwargs: Any other arguments to pass to the retriever.
Returns:
A BM25Retriever instance.
"""
try:
from rank_bm25 import BM25Okapi
except ImportError:
raise ImportEr... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/bm25.html |
f7299f0de97e-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 |
df0e4dc9a3ea-0 | Source code for langchain.retrievers.metal
from typing import Any, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
[docs]class MetalRetriever(BaseRetriever):
"""Retriever that uses the Meta... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html |
b82b5c37e7a2-0 | Source code for langchain.retrievers.milvus
"""Milvus Retriever"""
import warnings
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.embeddings.base import Embeddings
from langchain.schema import BaseRet... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html |
b82b5c37e7a2-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 |
13aa503ac350-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.embeddings.base import Embeddings
from langchain.schema import B... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
13aa503ac350-1 | ) -> SVMRetriever:
index = create_index(texts, embeddings)
return cls(embeddings=embeddings, index=index, texts=texts, **kwargs)
[docs] @classmethod
def from_documents(
cls,
documents: Iterable[Document],
embeddings: Embeddings,
**kwargs: Any,
) -> SVMRetriever... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
13aa503ac350-2 | # this performs a simple swap, this works because anything
# left of the 0 should be equivalent.
zero_index = np.where(sorted_ix == 0)[0][0]
if zero_index != 0:
sorted_ix[0], sorted_ix[zero_index] = sorted_ix[zero_index], sorted_ix[0]
denominator = np.max(similarities) - np.m... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html |
b79466f23987-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 Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.embedding... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
b79466f23987-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 |
b79466f23987-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."""
class Config:
"""Configura... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
b79466f23987-3 | sparse_vec = self.sparse_encoder.encode_queries(query)
# convert the question into a dense vector
dense_vec = self.embeddings.embed_query(query)
# scale alpha with hybrid_scale
dense_vec, sparse_vec = hybrid_convex_scale(dense_vec, sparse_vec, self.alpha)
sparse_vec["values"] = [... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html |
5e99289fe8e9-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.embeddings.base import Embeddings
from langchain.schema import BaseRetriever, Document
from lan... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html |
5e99289fe8e9-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 |
5e99289fe8e9-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 |
5e99289fe8e9-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 |
13bfd67e3c33-0 | Source code for langchain.retrievers.time_weighted_retriever
import datetime
from copy import deepcopy
from typing import Any, Dict, List, Optional, Tuple
from pydantic import Field
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.schema import BaseRetriever, Document
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
13bfd67e3c33-1 | """
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
def _get_combined_score(
self,
document: Document,
vector_relevance: Optional[float],
current_time: datetime.datetime,
) -> float:
"""Return the combined sco... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
13bfd67e3c33-2 | current_time = datetime.datetime.now()
docs_and_scores = {
doc.metadata["buffer_idx"]: (doc, self.default_salience)
for doc in self.memory_stream[-self.k :]
}
# If a doc is considered salient, update the salience score
docs_and_scores.update(self.get_salient_docs(... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
13bfd67e3c33-3 | self.memory_stream.extend(dup_docs)
return self.vectorstore.add_documents(dup_docs, **kwargs)
[docs] async def aadd_documents(
self, documents: List[Document], **kwargs: Any
) -> List[str]:
"""Add documents to vectorstore."""
current_time = kwargs.get("current_time")
if cu... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html |
216e490ba4e3-0 | Source code for langchain.retrievers.web_research
import logging
import re
from typing import List, Optional
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.chains import LLMChain
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html |
216e490ba4e3-1 | 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 mark at the end: {question}""",
)
[docs]class LineList(BaseModel):
"""List of ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html |
216e490ba4e3-2 | def from_llm(
cls,
vectorstore: VectorStore,
llm: BaseLLM,
search: GoogleSearchAPIWrapper,
prompt: Optional[BasePromptTemplate] = None,
num_search_results: int = 1,
text_splitter: RecursiveCharacterTextSplitter = RecursiveCharacterTextSplitter(
chunk_s... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html |
216e490ba4e3-3 | # 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 quote
first_quote_pos = query.find('"')
if... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html |
216e490ba4e3-4 | urls_to_look = []
for query in questions:
# Google search
search_results = self.search_tool(query, self.num_search_results)
logger.info("Searching for relevat urls ...")
logger.info(f"Search results: {search_results}")
for res in search_results:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/web_research.html |
2ea2141e04e1-0 | Source code for langchain.retrievers.merger_retriever
from typing import List
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
[docs]class MergerRetriever(BaseRetriever):
"""Retriever that me... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html |
2ea2141e04e1-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 |
2ea2141e04e1-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 |
848939bf8ec6-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 |
848939bf8ec6-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 |
102867fd5ece-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 |
102867fd5ece-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.