id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
117
307df7ddda7e-87
(langchain.document_loaders.GoogleDriveLoader attribute) tokenizer (langchain.llms.Petals attribute) tokens (langchain.llms.AlephAlpha attribute) tokens_path (langchain.llms.RWKV attribute) TokenTextSplitter (class in langchain.text_splitter) ToMarkdownLoader (class in langchain.document_loaders) TomlLoader (class in l...
https://python.langchain.com/en/latest/genindex.html
307df7ddda7e-88
(langchain.utilities.GooglePlacesAPIWrapper attribute) (langchain.utilities.WikipediaAPIWrapper attribute) top_n (langchain.retrievers.document_compressors.CohereRerank attribute) top_p (langchain.chat_models.ChatGooglePalm attribute) (langchain.llms.AlephAlpha attribute) (langchain.llms.Anthropic attribute) (langchain...
https://python.langchain.com/en/latest/genindex.html
307df7ddda7e-89
type (langchain.utilities.GoogleSerperAPIWrapper attribute) Typesense (class in langchain.vectorstores) U unsecure (langchain.utilities.searx_search.SearxSearchWrapper attribute) (langchain.utilities.SearxSearchWrapper attribute) UnstructuredAPIFileIOLoader (class in langchain.document_loaders) UnstructuredAPIFileLoade...
https://python.langchain.com/en/latest/genindex.html
307df7ddda7e-90
(langchain.llms.Cohere class method) (langchain.llms.CTransformers class method) (langchain.llms.Databricks class method) (langchain.llms.DeepInfra class method) (langchain.llms.FakeListLLM class method) (langchain.llms.ForefrontAI class method) (langchain.llms.GooglePalm class method) (langchain.llms.GooseAI class met...
https://python.langchain.com/en/latest/genindex.html
307df7ddda7e-91
(langchain.llms.VertexAI class method) (langchain.llms.Writer class method) upsert_messages() (langchain.memory.CosmosDBChatMessageHistory method) url (langchain.document_loaders.MathpixPDFLoader property) (langchain.llms.Beam attribute) (langchain.retrievers.ChatGPTPluginRetriever attribute) (langchain.retrievers.Remo...
https://python.langchain.com/en/latest/genindex.html
307df7ddda7e-92
(langchain.chains.VectorDBQAWithSourcesChain attribute) (langchain.prompts.example_selector.SemanticSimilarityExampleSelector attribute) (langchain.retrievers.SelfQueryRetriever attribute) (langchain.retrievers.TimeWeightedVectorStoreRetriever attribute) vectorstore_info (langchain.agents.agent_toolkits.VectorStoreTool...
https://python.langchain.com/en/latest/genindex.html
307df7ddda7e-93
(langchain.llms.OpenAIChat attribute) (langchain.llms.OpenLM attribute) (langchain.llms.Petals attribute) (langchain.llms.PipelineAI attribute) (langchain.llms.PredictionGuard attribute) (langchain.llms.Replicate attribute) (langchain.llms.RWKV attribute) (langchain.llms.SagemakerEndpoint attribute) (langchain.llms.Sel...
https://python.langchain.com/en/latest/genindex.html
307df7ddda7e-94
Wikipedia (class in langchain.docstore) WikipediaLoader (class in langchain.document_loaders) wolfram_alpha_appid (langchain.utilities.WolframAlphaAPIWrapper attribute) writer_api_key (langchain.llms.Writer attribute) writer_org_id (langchain.llms.Writer attribute) Y YoutubeLoader (class in langchain.document_loaders) ...
https://python.langchain.com/en/latest/genindex.html
1f25b99c001c-0
Search Error Please activate JavaScript to enable the search functionality. Ctrl+K By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, 2023.
https://python.langchain.com/en/latest/search.html
1cf15912e997-0
.md .pdf Deployments Contents Streamlit Gradio (on Hugging Face) Chainlit Beam Vercel FastAPI + Vercel Kinsta Fly.io Digitalocean App Platform Google Cloud Run SteamShip Langchain-serve BentoML Databutton Deployments# So, you’ve created a really cool chain - now what? How do you deploy it and make it easily shareable...
https://python.langchain.com/en/latest/ecosystem/deployments.html
1cf15912e997-1
Chainlit doc on the integration with LangChain Beam# This repo serves as a template for how deploy a LangChain with Beam. It implements a Question Answering app and contains instructions for deploying the app as a serverless REST API. Vercel# A minimal example on how to run LangChain on Vercel using Flask. FastAPI + Ve...
https://python.langchain.com/en/latest/ecosystem/deployments.html
1cf15912e997-2
Databutton# These templates serve as examples of how to build, deploy, and share LangChain applications using Databutton. You can create user interfaces with Streamlit, automate tasks by scheduling Python code, and store files and data in the built-in store. Examples include a Chatbot interface with conversational memo...
https://python.langchain.com/en/latest/ecosystem/deployments.html
e29953d4035a-0
.md .pdf Locally Hosted Setup Contents Installation Environment Setup Locally Hosted Setup# This page contains instructions for installing and then setting up the environment to use the locally hosted version of tracing. Installation# Ensure you have Docker installed (see Get Docker) and that it’s running. Install th...
https://python.langchain.com/en/latest/tracing/local_installation.html
e29953d4035a-1
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, 2023.
https://python.langchain.com/en/latest/tracing/local_installation.html
b974dda93ebd-0
.md .pdf Cloud Hosted Setup Contents Installation Environment Setup Cloud Hosted Setup# We offer a hosted version of tracing at langchainplus.vercel.app. You can use this to view traces from your run without having to run the server locally. Note: we are currently only offering this to a limited number of users. The ...
https://python.langchain.com/en/latest/tracing/hosted_installation.html
b974dda93ebd-1
os.environ["LANGCHAIN_API_KEY"] = "my_api_key" # Don't commit this to your repo! Better to set it in your terminal. Contents Installation Environment Setup By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, 2023.
https://python.langchain.com/en/latest/tracing/hosted_installation.html
c90931d38bad-0
.ipynb .pdf Tracing Walkthrough Contents [Beta] Tracing V2 Tracing Walkthrough# There are two recommended ways to trace your LangChains: Setting the LANGCHAIN_TRACING environment variable to “true”. Using a context manager with tracing_enabled() to trace a particular block of code. Note if the environment variable is...
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
c90931d38bad-1
> Entering new AgentExecutor chain... I need to use a calculator to solve this. Action: Calculator Action Input: 2^.123243 Observation: Answer: 1.0891804557407723 Thought: I now know the final answer. Final Answer: 1.0891804557407723 > Finished chain. '1.0891804557407723' # Agent run with tracing using a chat model ag...
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
c90931d38bad-2
I need to use a calculator to solve this. Action: Calculator Action Input: 5 ^ .123243 Observation: Answer: 1.2193914912400514 Thought:I now know the answer to the question. Final Answer: 1.2193914912400514 > Finished chain. # Now, we unset the environment variable and use a context manager. if "LANGCHAIN_TRACING" in ...
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
c90931d38bad-3
del os.environ["LANGCHAIN_TRACING"] questions = [f"What is {i} raised to .123 power?" for i in range(1,4)] # start a background task task = asyncio.create_task(agent.arun(questions[0])) # this should not be traced with tracing_enabled() as session: assert session tasks = [agent.arun(q) for q in questions[...
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
c90931d38bad-4
pip install --upgrade langchain langchain plus start Option 2 (Hosted): After making an account an grabbing a LangChainPlus API Key, set the LANGCHAIN_ENDPOINT and LANGCHAIN_API_KEY environment variables import os os.environ["LANGCHAIN_TRACING_V2"] = "true" # os.environ["LANGCHAIN_ENDPOINT"] = "https://langchainpro-api...
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
c90931d38bad-5
Contents [Beta] Tracing V2 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, 2023.
https://python.langchain.com/en/latest/tracing/agent_with_tracing.html
add7ed7a6800-0
Source code for langchain.text_splitter """Functionality for splitting text.""" from __future__ import annotations import copy import logging import re from abc import ABC, abstractmethod from typing import ( AbstractSet, Any, Callable, Collection, Iterable, List, Literal, Optional, ...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
add7ed7a6800-1
keep_separator: bool = False, ): """Create a new TextSplitter. Args: chunk_size: Maximum size of chunks to return chunk_overlap: Overlap in characters between chunks length_function: Function that measures the length of given chunks keep_separator: Whe...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
add7ed7a6800-2
return self.create_documents(texts, metadatas=metadatas) def _join_docs(self, docs: List[str], separator: str) -> Optional[str]: text = separator.join(docs) text = text.strip() if text == "": return None else: return text def _merge_splits(self, splits: It...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
add7ed7a6800-3
): total -= self._length_function(current_doc[0]) + ( separator_len if len(current_doc) > 1 else 0 ) current_doc = current_doc[1:] current_doc.append(d) total += _len + (separator_len if len(curre...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
add7ed7a6800-4
"""Text splitter that uses tiktoken encoder to count length.""" try: import tiktoken except ImportError: raise ImportError( "Could not import tiktoken python package. " "This is needed in order to calculate max_tokens_for_prompt. " ...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
add7ed7a6800-5
"""Implementation of splitting text that looks at characters.""" def __init__(self, separator: str = "\n\n", **kwargs: Any): """Create a new TextSplitter.""" super().__init__(**kwargs) self._separator = separator [docs] def split_text(self, text: str) -> List[str]: """Split incomi...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
add7ed7a6800-6
self._tokenizer = enc self._allowed_special = allowed_special self._disallowed_special = disallowed_special [docs] def split_text(self, text: str) -> List[str]: """Split incoming text and return chunks.""" splits = [] input_ids = self._tokenizer.encode( text, ...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
add7ed7a6800-7
separator = separators[-1] new_separators = None for i, _s in enumerate(separators): if _s == "": separator = _s break if _s in text: separator = _s new_separators = separators[i + 1 :] break ...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
add7ed7a6800-8
try: from nltk.tokenize import sent_tokenize self._tokenizer = sent_tokenize except ImportError: raise ImportError( "NLTK is not installed, please install it with `pip install nltk`." ) self._separator = separator [docs] def split_text(s...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
add7ed7a6800-9
"""Initialize a MarkdownTextSplitter.""" separators = [ # First, try to split along Markdown headings (starting with level 2) "\n## ", "\n### ", "\n#### ", "\n##### ", "\n###### ", # Note the alternative syntax for headings (bel...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
add7ed7a6800-10
"\n\\begin{quotation}", "\n\\begin{verse}", "\n\\begin{verbatim}", ## Now split by math environments "\n\\begin{align}", "$$", "$", # Now split by the normal type of lines " ", "", ] super().__ini...
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
a091925fb243-0
Source code for langchain.requests """Lightweight wrapper around requests library, with async support.""" from contextlib import asynccontextmanager from typing import Any, AsyncGenerator, Dict, Optional import aiohttp import requests from pydantic import BaseModel, Extra class Requests(BaseModel): """Wrapper aroun...
https://python.langchain.com/en/latest/_modules/langchain/requests.html
a091925fb243-1
def delete(self, url: str, **kwargs: Any) -> requests.Response: """DELETE the URL and return the text.""" return requests.delete(url, headers=self.headers, **kwargs) @asynccontextmanager async def _arequest( self, method: str, url: str, **kwargs: Any ) -> AsyncGenerator[aiohttp.Clien...
https://python.langchain.com/en/latest/_modules/langchain/requests.html
a091925fb243-2
"""PATCH the URL and return the text asynchronously.""" async with self._arequest("PATCH", url, **kwargs) as response: yield response @asynccontextmanager async def aput( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: ...
https://python.langchain.com/en/latest/_modules/langchain/requests.html
a091925fb243-3
"""POST to the URL and return the text.""" return self.requests.post(url, data, **kwargs).text [docs] def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PATCH the URL and return the text.""" return self.requests.patch(url, data, **kwargs).text [docs] def put(self, ur...
https://python.langchain.com/en/latest/_modules/langchain/requests.html
a091925fb243-4
"""PUT the URL and return the text asynchronously.""" async with self.requests.aput(url, **kwargs) as response: return await response.text() [docs] async def adelete(self, url: str, **kwargs: Any) -> str: """DELETE the URL and return the text asynchronously.""" async with self.req...
https://python.langchain.com/en/latest/_modules/langchain/requests.html
b7ed90f7f811-0
Source code for langchain.document_transformers """Transform documents""" from typing import Any, Callable, List, Sequence import numpy as np from pydantic import BaseModel, Field from langchain.embeddings.base import Embeddings from langchain.math_utils import cosine_similarity from langchain.schema import BaseDocumen...
https://python.langchain.com/en/latest/_modules/langchain/document_transformers.html
b7ed90f7f811-1
for first_idx, second_idx in redundant_stacked[redundant_sorted]: if first_idx in included_idxs and second_idx in included_idxs: # Default to dropping the second document of any highly similar pair. included_idxs.remove(second_idx) return list(sorted(included_idxs)) def _get_embeddin...
https://python.langchain.com/en/latest/_modules/langchain/document_transformers.html
b7ed90f7f811-2
"""Filter down documents.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embeddings_from_stateful_docs( self.embeddings, stateful_documents ) included_idxs = _filter_similar_embeddings( embedded_documents, self.similarity_fn, s...
https://python.langchain.com/en/latest/_modules/langchain/document_transformers.html
21f112892a2f-0
Source code for langchain.experimental.autonomous_agents.baby_agi.baby_agi """BabyAGI agent.""" from collections import deque from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import CallbackManagerFo...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
21f112892a2f-1
print(str(t["task_id"]) + ": " + t["task_name"]) def print_next_task(self, task: Dict) -> None: print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m") print(str(task["task_id"]) + ": " + task["task_name"]) def print_task_result(self, result: str) -> None: print("\033[93m...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
21f112892a2f-2
next_task_id = int(this_task_id) + 1 response = self.task_prioritization_chain.run( task_names=", ".join(task_names), next_task_id=str(next_task_id), objective=objective, ) new_tasks = response.split("\n") prioritized_task_list = [] for task_st...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
21f112892a2f-3
"""Run the agent.""" objective = inputs["objective"] first_task = inputs.get("first_task", "Make a todo list") self.add_task({"task_id": 1, "task_name": first_task}) num_iters = 0 while True: if self.task_list: self.print_task_list() # ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
21f112892a2f-4
break return {} [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, vectorstore: VectorStore, verbose: bool = False, task_execution_chain: Optional[Chain] = None, **kwargs: Dict[str, Any], ) -> "BabyAGI": """Initialize the BabyAGI Con...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
7d4201e1c1e8-0
Source code for langchain.experimental.autonomous_agents.autogpt.agent from __future__ import annotations from typing import List, Optional from pydantic import ValidationError from langchain.chains.llm import LLMChain from langchain.chat_models.base import BaseChatModel from langchain.experimental.autonomous_agents.au...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
7d4201e1c1e8-1
ai_role: str, memory: VectorStoreRetriever, tools: List[BaseTool], llm: BaseChatModel, human_in_the_loop: bool = False, output_parser: Optional[BaseAutoGPTOutputParser] = None, ) -> AutoGPT: prompt = AutoGPTPrompt( ai_name=ai_name, ai_role=ai_r...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
7d4201e1c1e8-2
# Get command name and arguments action = self.output_parser.parse(assistant_reply) tools = {t.name: t for t in self.tools} if action.name == FINISH_NAME: return action.args["response"] if action.name in tools: tool = tools[action.name] ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
a68fd5f8a0e7-0
Source code for langchain.experimental.generative_agents.generative_agent import re from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from pydantic import BaseModel, Field from langchain import LLMChain from langchain.base_language import BaseLanguageModel from langchain.experimental.gen...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
a68fd5f8a0e7-1
arbitrary_types_allowed = True # LLM-related methods @staticmethod def _parse_list(text: str) -> List[str]: """Parse a newline-separated string into a list of strings.""" lines = re.split(r"\n", text.strip()) return [re.sub(r"^\s*\d+\.\s*", "", line).strip() for line in lines] de...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
a68fd5f8a0e7-2
entity_action = self._get_entity_action(observation, entity_name) q1 = f"What is the relationship between {self.name} and {entity_name}" q2 = f"{entity_name} is {entity_action}" return self.chain(prompt=prompt).run(q1=q1, queries=[q1, q2]).strip() def _generate_reaction( self, observ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
a68fd5f8a0e7-3
) consumed_tokens = self.llm.get_num_tokens( prompt.format(most_recent_memories="", **kwargs) ) kwargs[self.memory.most_recent_memories_token_key] = consumed_tokens return self.chain(prompt=prompt).run(**kwargs).strip() def _clean_response(self, text: str) -> str: ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
a68fd5f8a0e7-4
if "SAY:" in result: said_value = self._clean_response(result.split("SAY:")[-1]) return True, f"{self.name} said {said_value}" else: return False, result [docs] def generate_dialogue_response( self, observation: str, now: Optional[datetime] = None ) -> Tuple[bo...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
a68fd5f8a0e7-5
}, ) return True, f"{self.name} said {response_text}" else: return False, result ###################################################### # Agent stateful' summary methods. # # Each dialog or response prompt includes a header # # summarizing ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
a68fd5f8a0e7-6
+ f"\nInnate traits: {self.traits}" + f"\n{self.summary}" ) [docs] def get_full_header( self, force_refresh: bool = False, now: Optional[datetime] = None ) -> str: """Return a full header of the agent's status, summary, and current time.""" now = datetime.now() if now ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
f9f1a6970d21-0
Source code for langchain.experimental.generative_agents.memory import logging import re from datetime import datetime from typing import Any, Dict, List, Optional from langchain import LLMChain from langchain.base_language import BaseLanguageModel from langchain.prompts import PromptTemplate from langchain.retrievers ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
f9f1a6970d21-1
# output keys relevant_memories_key: str = "relevant_memories" relevant_memories_simple_key: str = "relevant_memories_simple" most_recent_memories_key: str = "most_recent_memories" now_key: str = "now" reflecting: bool = False def chain(self, prompt: PromptTemplate) -> LLMChain: return L...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
f9f1a6970d21-2
) -> List[str]: """Generate 'insights' on a topic of reflection, based on pertinent memories.""" prompt = PromptTemplate.from_template( "Statements about {topic}\n" + "{related_statements}\n\n" + "What 5 high-level insights can you infer from the above statements?" ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
f9f1a6970d21-3
"On the scale of 1 to 10, where 1 is purely mundane" + " (e.g., brushing teeth, making bed) and 10 is" + " extremely poignant (e.g., a break up, college" + " acceptance), rate the likely poignancy of the" + " following piece of memory. Respond with a single integer." ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
f9f1a6970d21-4
and not self.reflecting ): self.reflecting = True self.pause_to_reflect(now=now) # Hack to clear the importance from reflection self.aggregate_importance = 0.0 self.reflecting = False return result [docs] def fetch_memories( self, ob...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
f9f1a6970d21-5
break consumed_tokens += self.llm.get_num_tokens(doc.page_content) if consumed_tokens < self.max_tokens_limit: result.append(doc) return self.format_memories_simple(result) @property def memory_variables(self) -> List[str]: """Input keys this memory class ...
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
f9f1a6970d21-6
[docs] def clear(self) -> None: """Clear memory contents.""" # TODO By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, 2023.
https://python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
50d1b2fb2c48-0
Source code for langchain.retrievers.time_weighted_retriever """Retriever that combines embedding similarity with recency in retrieving values.""" import datetime from copy import deepcopy from typing import Any, Dict, List, Optional, Tuple from pydantic import BaseModel, Field from langchain.schema import BaseRetrieve...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
50d1b2fb2c48-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://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
50d1b2fb2c48-2
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(query)) rescored_docs = [ (doc, self._get_combined_score(doc, relevance, current_time)) for doc, relevance in docs_a...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
50d1b2fb2c48-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://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
8f87664f674d-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
8f87664f674d-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 = [] ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
8f87664f674d-2
"""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 ( BaseSparseEncoder, # noqa:F401 ) except ImportError: ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
d0615fb22631-0
Source code for langchain.retrievers.vespa_retriever """Wrapper for retrieving documents from Vespa.""" from __future__ import annotations import json from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Sequence, Union from langchain.schema import BaseRetriever, Document if TYPE_CHECKING: from ves...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html
d0615fb22631-1
docs.append(Document(page_content=page_content, metadata=metadata)) return docs [docs] def get_relevant_documents(self, query: str) -> List[Document]: body = self._query_body.copy() body["query"] = query return self._query(body) [docs] async def aget_relevant_documents(self, query:...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html
d0615fb22631-2
document metadata. Defaults to empty tuple (). sources (Sequence[str] or "*" or None): Sources to retrieve from. Defaults to None. _filter (Optional[str]): Document filter condition expressed in YQL. Defaults to None. yql (Optional[str]): Full YQL quer...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html
c3ba74937347-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 __future__ import annotations from typing import Any, Dict, Iterable, List, Optional from pydantic import BaseModel from langchai...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
c3ba74937347-1
return cls(vectorizer=vectorizer, docs=docs, tfidf_array=tfidf_array, **kwargs) [docs] @classmethod def from_documents( cls, documents: Iterable[Document], *, tfidf_params: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> TFIDFRetriever: texts, metadatas = ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
0e77ade5bea3-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html
0e77ade5bea3-1
y[0] = 1 clf = svm.LinearSVC( class_weight="balanced", verbose=False, max_iter=10000, tol=1e-6, C=0.1 ) clf.fit(x, y) similarities = clf.decision_function(x) sorted_ix = np.argsort(-similarities) # svm.LinearSVC in scikit-learn is non-deterministic. # ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html
19159140704d-0
Source code for langchain.retrievers.wikipedia from typing import List from langchain.schema import BaseRetriever, Document from langchain.utilities.wikipedia import WikipediaAPIWrapper [docs]class WikipediaRetriever(BaseRetriever, WikipediaAPIWrapper): """ It is effectively a wrapper for WikipediaAPIWrapper. ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/wikipedia.html
71366c4575f1-0
Source code for langchain.retrievers.azure_cognitive_search """Retriever wrapper for Azure Cognitive Search.""" from __future__ import annotations import json from typing import Dict, List, Optional import aiohttp import requests from pydantic import BaseModel, Extra, root_validator from langchain.schema import BaseRet...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html
71366c4575f1-1
) values["api_key"] = get_from_dict_or_env( values, "api_key", "AZURE_COGNITIVE_SEARCH_API_KEY" ) return values def _build_search_url(self, query: str) -> str: base_url = f"https://{self.service_name}.search.windows.net/" endpoint_path = f"indexes/{self.index_name...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html
71366c4575f1-2
search_results = self._search(query) return [ Document(page_content=result.pop(self.content_key), metadata=result) for result in search_results ] [docs] async def aget_relevant_documents(self, query: str) -> List[Document]: search_results = await self._asearch(query) ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html
a722b5ae3d09-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
a722b5ae3d09-1
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 Elasticsearch # Create an Elasticsearch client instance es = Elasticsearch(ela...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
a722b5ae3d09-2
raise ValueError( "Could not import elasticsearch python package. " "Please install it with `pip install elasticsearch`." ) requests = [] ids = [] for i, text in enumerate(texts): _id = str(uuid.uuid4()) request = { ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
3073c6efe973-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 pydantic import BaseModel from langchain.embedding...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html
3073c6efe973-1
similarities = index_embeds.dot(query_embeds) sorted_ix = np.argsort(-similarities) denominator = np.max(similarities) - np.min(similarities) + 1e-6 normalized_similarities = (similarities - np.min(similarities)) / denominator top_k_results = [] for row in sorted_ix[0 : self.k]: ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html
0e868a3117d7-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html
689d0548c394-0
Source code for langchain.retrievers.zep from __future__ import annotations from typing import TYPE_CHECKING, List, Optional from langchain.schema import BaseRetriever, Document if TYPE_CHECKING: from zep_python import SearchResult [docs]class ZepRetriever(BaseRetriever): """A Retriever implementation for the Z...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html
689d0548c394-1
) for r in results if r.message ] [docs] def get_relevant_documents(self, query: str) -> List[Document]: from zep_python import SearchPayload payload: SearchPayload = SearchPayload(text=query) results: List[SearchResult] = self.zep_client.search_memory( ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html
5e7c4f3eaed8-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html
5e7c4f3eaed8-1
return list(compressed_docs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, 2023.
https://python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html
16231b9cf5c8-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
16231b9cf5c8-1
"properties": [{"name": self._text_key, "dataType": ["text"]}], "vectorizer": "text2vec-openai", } if not self._client.schema.exists(self._index_name): self._client.schema.create_class(class_obj) [docs] class Config: """Configuration for this pydantic object.""" ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
16231b9cf5c8-2
if "errors" in result: raise ValueError(f"Error during query: {result['errors']}") docs = [] for res in result["data"]["Get"][self._index_name]: text = res.pop(self._text_key) docs.append(Document(page_content=text, metadata=res)) return docs [docs] async d...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
f6177451b88e-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, ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html
f6177451b88e-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://python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html
c29c8ccadde2-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
c29c8ccadde2-1
docs = [] for d in results: content = d.pop("text") docs.append(Document(page_content=content, metadata=d)) return docs def _create_request(self, query: str) -> tuple[str, dict, dict]: url = f"{self.url}/query" json = { "queries": [ ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
25eb49c57c72-0
Source code for langchain.retrievers.arxiv from typing import List from langchain.schema import BaseRetriever, Document from langchain.utilities.arxiv import ArxivAPIWrapper [docs]class ArxivRetriever(BaseRetriever, ArxivAPIWrapper): """ It is effectively a wrapper for ArxivAPIWrapper. It wraps load() to ge...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/arxiv.html
f5f52d30581c-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html