id
stringlengths
14
16
text
stringlengths
44
2.73k
source
stringlengths
49
115
c4e97f8adab2-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() ...
https://python.langchain.com/en/latest/_modules/langchain/memory/simple.html
1ffebbffbaa5-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...
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
1ffebbffbaa5-1
[docs] def set(self, key: str, value: Optional[str]) -> None: self.store[key] = value [docs] def delete(self, key: str) -> None: del self.store[key] [docs] def exists(self, key: str) -> bool: return key in self.store [docs] def clear(self) -> None: return self.store.clear() [...
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
1ffebbffbaa5-2
except redis.exceptions.ConnectionError as error: logger.error(error) self.session_id = session_id self.key_prefix = key_prefix self.ttl = ttl self.recall_ttl = recall_ttl or ttl @property def full_key_prefix(self) -> str: return f"{self.key_prefix}:{self.sess...
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
1ffebbffbaa5-3
yield batch for keybatch in batched( self.redis_client.scan_iter(f"{self.full_key_prefix}:*"), 500 ): self.redis_client.delete(*keybatch) [docs]class ConversationEntityMemory(BaseChatMemory): """Entity extractor & summarizer to memory.""" human_prefix: str = "Human" a...
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
1ffebbffbaa5-4
history=buffer_string, input=inputs[prompt_input_key], ) if output.strip() == "NONE": entities = [] else: entities = [w.strip() for w in output.split(",")] entity_summaries = {} for entity in entities: entity_summaries[entity] = sel...
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
1ffebbffbaa5-5
"""Clear memory contents.""" self.chat_memory.clear() self.entity_cache.clear() self.entity_store.clear() By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html
2d9aef25e9e0-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]: ...
https://python.langchain.com/en/latest/_modules/langchain/memory/readonly.html
b099e9283533-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.""" ...
https://python.langchain.com/en/latest/_modules/langchain/memory/combined.html
a1172f84beca-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...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html
7c8e25388bd1-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, ...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
7c8e25388bd1-1
self.credential = credential self.session_id = session_id self.user_id = user_id self.ttl = ttl self._client: Optional[CosmosClient] = None self._container: Optional[ContainerProxy] = None self.messages: List[BaseMessage] = [] [docs] def prepare_cosmos(self) -> None: ...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
7c8e25388bd1-2
) -> None: """Context manager exit""" self.upsert_messages() if self._client: self._client.__exit__(exc_type, exc_val, traceback) [docs] def load_messages(self) -> None: """Retrieve the messages from Cosmos""" if not self._container: raise ValueError("C...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
7c8e25388bd1-3
self.messages.append(new_message) if not self._container: raise ValueError("Container not initialized") self._container.upsert_item( body={ "id": self.session_id, "user_id": self.user_id, "messages": messages_to_dict(self.messages),...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
0add942c6e9b-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...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
0add942c6e9b-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(AIMessage(content=message)) [docs] def append(self, message: BaseMe...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
403b288bc7f4-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...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html
403b288bc7f4-1
self.append(HumanMessage(content=message)) [docs] def add_ai_message(self, message: str) -> None: self.append(AIMessage(content=message)) [docs] def append(self, message: BaseMessage) -> None: """Append the message to the record in Redis""" self.redis_client.lpush(self.key, json.dumps(_mes...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html
0f898b7504e8-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__) ...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
0f898b7504e8-1
items = [] 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(AIMessage(content=message)) [docs] def append(se...
https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
17593e1d3102-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
17593e1d3102-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, ) -> float: """Return the combined score for a ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
17593e1d3102-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
17593e1d3102-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", datetime.now(...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
c05ab6c49cd1-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
d65ece8a88cc-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
9ebf99031286-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
9ebf99031286-1
return list(compressed_docs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html
2b5d1e151199-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
2b5d1e151199-1
vectors = [] # loop through the data and create dictionaries for upserts for doc_id, sparse, dense, metadata in zip( batch_ids, sparse_embeds, dense_embeds, meta ): vectors.append( { "id": doc_id, "sparse_values": sp...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
2b5d1e151199-2
[docs] def get_relevant_documents(self, query: str) -> List[Document]: from pinecone_text.hybrid import hybrid_convex_scale sparse_vec = self.sparse_encoder.encode_queries(query) # convert the question into a dense vector dense_vec = self.embeddings.embed_query(query) # scale ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
d8ed6a7c7997-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
d8ed6a7c7997-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
84ddf7a71e3b-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
84ddf7a71e3b-1
"""Upload documents to Weaviate.""" from weaviate.util import get_valid_uuid with self._client.batch as batch: ids = [] for i, doc in enumerate(docs): metadata = doc.metadata or {} data_properties = {self._text_key: doc.page_content, **metadata} ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
75cea1bb0d64-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
75cea1bb0d64-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
75cea1bb0d64-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
8d74bfe05b3a-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
8d74bfe05b3a-1
results = cosine_similarity(self.tfidf_array, query_vec).reshape( (-1,) ) # Op -- (n_docs,1) -- Cosine Sim with each doc return_docs = [] for i in results.argsort()[-self.k :][::-1]: return_docs.append(self.docs[i]) return return_docs [docs] async def aget_rel...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
05a85015c944-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
05a85015c944-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
52a91d9379ad-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
52a91d9379ad-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
71031a6b20f8-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
71031a6b20f8-1
self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Compress page content of raw documents.""" compressed_docs = [] for doc in documents: _input = self.get_input(query, doc) output = self.llm_chain.predict_and_parse(**_input) if len...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
0057c77c99f2-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
0057c77c99f2-1
self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Compress retrieved documents given the query context.""" for _transformer in self.transformers: if isinstance(_transformer, BaseDocumentCompressor): documents = await _transformer.acompress_docume...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
9e51316d4329-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 ( ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html
9e51316d4329-1
return values [docs] def compress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Filter documents based on similarity of their embeddings to the query.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embed...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html
156d71e386ee-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...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html
156d71e386ee-1
include_doc = self.llm_chain.predict_and_parse(**_input) if include_doc: filtered_docs.append(doc) return filtered_docs [docs] async def acompress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Filter down documents.""" ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html
d4307603436c-0
Source code for langchain.utilities.arxiv """Util that calls Arxiv.""" import logging from typing import Any, Dict, List from pydantic import BaseModel, Extra, root_validator from langchain.schema import Document logger = logging.getLogger(__name__) [docs]class ArxivAPIWrapper(BaseModel): """Wrapper around ArxivAPI...
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
d4307603436c-1
"""Validate that the python package exists in environment.""" try: import arxiv values["arxiv_search"] = arxiv.Search values["arxiv_exceptions"] = ( arxiv.ArxivError, arxiv.UnexpectedEmptyPageError, arxiv.HTTPError, ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
d4307603436c-2
""" Run Arxiv search and get the PDF documents plus the meta information. See https://lukasschwab.me/arxiv.py/index.html#Search Returns: a list of documents with the document.page_content in PDF format """ try: import fitz except ImportError: raise...
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
d4307603436c-3
**add_meta, } ), ) docs.append(doc) except FileNotFoundError as f_ex: logger.debug(f_ex) return docs except self.arxiv_exceptions as ex: logger....
https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html
16eb807beff4-0
Source code for langchain.utilities.python import sys from io import StringIO from typing import Dict, Optional from pydantic import BaseModel, Field [docs]class PythonREPL(BaseModel): """Simulates a standalone Python REPL.""" globals: Optional[Dict] = Field(default_factory=dict, alias="_globals") locals: O...
https://python.langchain.com/en/latest/_modules/langchain/utilities/python.html
66c1beb03497-0
Source code for langchain.utilities.serpapi """Chain that calls SerpAPI. Heavily borrowed from https://github.com/ofirpress/self-ask """ import os import sys from typing import Any, Dict, Optional, Tuple import aiohttp from pydantic import BaseModel, Extra, Field, root_validator from langchain.utils import get_from_dic...
https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
66c1beb03497-1
aiosession: Optional[aiohttp.ClientSession] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python packag...
https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
66c1beb03497-2
"""Use aiohttp to run query through SerpAPI and return the results async.""" def construct_url_and_params() -> Tuple[str, Dict[str, str]]: params = self.get_params(query) params["source"] = "python" if self.serpapi_api_key: params["serp_api_key"] = self.serpap...
https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
66c1beb03497-3
toret = res["answer_box"]["snippet"] elif ( "answer_box" in res.keys() and "snippet_highlighted_words" in res["answer_box"].keys() ): toret = res["answer_box"]["snippet_highlighted_words"][0] elif ( "sports_results" in res.keys() and "g...
https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html
d171baae5457-0
Source code for langchain.utilities.wolfram_alpha """Util that calls WolframAlpha.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class WolframAlphaAPIWrapper(BaseModel): """Wrapper for Wolfram Alpha. Docs fo...
https://python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
d171baae5457-1
res = self.wolfram_client.query(query) try: assumption = next(res.pods).text answer = next(res.results).text except StopIteration: return "Wolfram Alpha wasn't able to answer it" if answer is None or answer == "": # We don't want to return the assu...
https://python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html
1faf6bf5a1bf-0
Source code for langchain.utilities.searx_search """Utility for using SearxNG meta search API. SearxNG is a privacy-friendly free metasearch engine that aggregates results from `multiple search engines <https://docs.searxng.org/admin/engines/configured_engines.html>`_ and databases and supports the `OpenSearch <https:...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
1faf6bf5a1bf-1
Other methods are are available for convenience. :class:`SearxResults` is a convenience wrapper around the raw json result. Example usage of the ``run`` method to make a search: .. code-block:: python s.run(query="what is the best search engine?") Engine Parameters ----------------- You can pass any `accept...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
1faf6bf5a1bf-2
.. code-block:: python # select the github engine and pass the search suffix s = SearchWrapper("langchain library", query_suffix="!gh") s = SearchWrapper("langchain library") # select github the conventional google search syntax s.run("large language models", query_suffix="site:g...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
1faf6bf5a1bf-3
return {"language": "en", "format": "json"} [docs]class SearxResults(dict): """Dict like wrapper around search api results.""" _data = "" def __init__(self, data: str): """Take a raw result from Searx and make it into a dict like object.""" json_data = json.loads(data) super().__init...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
1faf6bf5a1bf-4
.. code-block:: python from langchain.utilities import SearxSearchWrapper # note the unsecure parameter is not needed if you pass the url scheme as # http searx = SearxSearchWrapper(searx_host="http://localhost:8888", un...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
1faf6bf5a1bf-5
if categories: values["params"]["categories"] = ",".join(categories) searx_host = get_from_dict_or_env(values, "searx_host", "SEARX_HOST") if not searx_host.startswith("http"): print( f"Warning: missing the url scheme on host \ ! assuming secure ht...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
1faf6bf5a1bf-6
) as response: if not response.ok: raise ValueError("Searx API returned an error: ", response.text) result = SearxResults(await response.text()) self._result = result else: async with self.aiosession.get( ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
1faf6bf5a1bf-7
searx.run("what is the weather in France ?", engine="qwant") # the same result can be achieved using the `!` syntax of searx # to select the engine using `query_suffix` searx.run("what is the weather in France ?", query_suffix="!qwant") """ _params = { ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
1faf6bf5a1bf-8
) -> str: """Asynchronously version of `run`.""" _params = { "q": query, } params = {**self.params, **_params, **kwargs} if self.query_suffix and len(self.query_suffix) > 0: params["q"] += " " + self.query_suffix if isinstance(query_suffix, str) an...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
1faf6bf5a1bf-9
categories: List of categories to use for the query. **kwargs: extra parameters to pass to the searx API. Returns: Dict with the following keys: { snippet: The description of the result. title: The title of the result. link: T...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
1faf6bf5a1bf-10
self, query: str, num_results: int, engines: Optional[List[str]] = None, query_suffix: Optional[str] = "", **kwargs: Any, ) -> List[Dict]: """Asynchronously query with json results. Uses aiohttp. See `results` for more info. """ _params = { ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html
6d5bbb9165ee-0
Source code for langchain.utilities.bing_search """Util that calls Bing Search. In order to set this up, follow instructions at: https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e """ from typing import Dict, List import requests from pydantic import BaseModel, Extra, ro...
https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
6d5bbb9165ee-1
bing_subscription_key = get_from_dict_or_env( values, "bing_subscription_key", "BING_SUBSCRIPTION_KEY" ) values["bing_subscription_key"] = bing_subscription_key bing_search_url = get_from_dict_or_env( values, "bing_search_url", "BING_SEARCH_URL", ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
6d5bbb9165ee-2
"snippet": result["snippet"], "title": result["name"], "link": result["url"], } metadata_results.append(metadata_result) return metadata_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html
6ee68da6c8e6-0
Source code for langchain.utilities.google_places_api """Chain that calls Google Places API. """ import logging from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class GooglePlacesAPIWrapper(BaseModel): """Wrapper arou...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
6ee68da6c8e6-1
except ImportError: raise ValueError( "Could not import googlemaps python packge. " "Please install it with `pip install googlemaps`." ) return values [docs] def run(self, query: str) -> str: """Run Places search and get k number of places that ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
6ee68da6c8e6-2
"formatted_address", "Unknown" ) phone_number = place_details.get("result", {}).get( "formatted_phone_number", "Unknown" ) website = place_details.get("result", {}).get("website", "Unknown") formatted_details = ( f"{name}\nAddre...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html
09ea87c975f5-0
Source code for langchain.utilities.apify from typing import Any, Callable, Dict, Optional from pydantic import BaseModel, root_validator from langchain.document_loaders import ApifyDatasetLoader from langchain.document_loaders.base import Document from langchain.utils import get_from_dict_or_env [docs]class ApifyWrapp...
https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
09ea87c975f5-1
*, build: Optional[str] = None, memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None, ) -> ApifyDatasetLoader: """Run an Actor on the Apify platform and wait for results to be ready. Args: actor_id (str): The ID or name of the Actor on the Apify...
https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
09ea87c975f5-2
memory_mbytes: Optional[int] = None, timeout_secs: Optional[int] = None, ) -> ApifyDatasetLoader: """Run an Actor on the Apify platform and wait for results to be ready. Args: actor_id (str): The ID or name of the Actor on the Apify platform. run_input (Dict): The inp...
https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html
9585245cc724-0
Source code for langchain.utilities.powerbi """Wrapper around a Power BI endpoint.""" from __future__ import annotations import logging import os from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union import aiohttp import requests from aiohttp import ServerTimeoutError from pydantic import BaseMo...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
9585245cc724-1
arbitrary_types_allowed = True @root_validator(pre=True, allow_reuse=True) def token_or_credential_present(cls, values: Dict[str, Any]) -> Dict[str, Any]: """Validate that at least one of token and credentials is present.""" if "token" in values or "credential" in values: return valu...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
9585245cc724-2
"""Get names of tables available.""" return self.table_names [docs] def get_schemas(self) -> str: """Get the available schema's.""" if self.schemas: return ", ".join([f"{key}: {value}" for key, value in self.schemas.items()]) return "No known schema's yet. Use the schema_p...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
9585245cc724-3
) -> str: """Get information about specified tables.""" tables_requested = self._get_tables_to_query(table_names) tables_todo = self._get_tables_todo(tables_requested) for table in tables_todo: try: result = self.run( f"EVALUATE TOPN({self....
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
9585245cc724-4
if "bad request" in str(exc).lower(): return SCHEMA_ERROR_RESPONSE if "unauthorized" in str(exc).lower(): return UNAUTHORIZED_RESPONSE return str(exc) self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"]) r...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
9585245cc724-5
) as response: response.raise_for_status() response_json = await response.json() return response_json def json_to_md( json_contents: List[Dict[str, Union[str, int, float]]], table_name: Optional[str] = None, ) -> str: """Converts a JSON object to a markdown ta...
https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html
55fd5ee48c3c-0
Source code for langchain.utilities.wikipedia """Util that calls Wikipedia.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, root_validator WIKIPEDIA_MAX_QUERY_LENGTH = 300 [docs]class WikipediaAPIWrapper(BaseModel): """Wrapper around WikipediaAPI. To use, you should have the ``w...
https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
55fd5ee48c3c-1
summary = self.fetch_formatted_page_summary(search_results[i]) if summary is not None: summaries.append(summary) return "\n\n".join(summaries) [docs] def fetch_formatted_page_summary(self, page: str) -> Optional[str]: try: wiki_page = self.wiki_client.page(titl...
https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html
33d1a35dc91b-0
Source code for langchain.utilities.openweathermap """Util that calls OpenWeatherMap using PyOWM.""" from typing import Any, Dict, Optional from pydantic import Extra, root_validator from langchain.tools.base import BaseModel from langchain.utils import get_from_dict_or_env [docs]class OpenWeatherMapAPIWrapper(BaseMode...
https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
33d1a35dc91b-1
temperature = w.temperature("celsius") rain = w.rain heat_index = w.heat_index clouds = w.clouds return ( f"In {location}, the current weather is as follows:\n" f"Detailed status: {detailed_status}\n" f"Wind speed: {wind['speed']} m/s, direction: {wind...
https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html
726849bdef50-0
Source code for langchain.utilities.bash """Wrapper around subprocess to run commands.""" from __future__ import annotations import platform import re import subprocess from typing import TYPE_CHECKING, List, Union from uuid import uuid4 if TYPE_CHECKING: import pexpect def _lazy_import_pexpect() -> pexpect: ""...
https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html
726849bdef50-1
# Set the custom prompt process.sendline("PS1=" + prompt) process.expect_exact(prompt, timeout=10) return process [docs] def run(self, commands: Union[str, List[str]]) -> str: """Run commands and return final output.""" if isinstance(commands, str): commands = [com...
https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html
726849bdef50-2
self.process.expect(self.prompt, timeout=10) self.process.sendline("") try: self.process.expect([self.prompt, pexpect.EOF], timeout=10) except pexpect.TIMEOUT: return f"Timeout error while executing command {command}" if self.process.after == pexpect.EOF: ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html
1e7368da0eb9-0
Source code for langchain.utilities.google_serper """Util that calls Google Search using the Serper.dev API.""" from typing import Dict, Optional import requests from pydantic.class_validators import root_validator from pydantic.main import BaseModel from langchain.utils import get_from_dict_or_env [docs]class GoogleSe...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
1e7368da0eb9-1
snippets = [] if results.get("answerBox"): answer_box = results.get("answerBox", {}) if answer_box.get("answer"): return answer_box.get("answer") elif answer_box.get("snippet"): return answer_box.get("snippet").replace("\n", " ") el...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
1e7368da0eb9-2
) response.raise_for_status() search_results = response.json() return search_results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html
aee2531c542c-0
Source code for langchain.utilities.google_search """Util that calls Google Search.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]class GoogleSearchAPIWrapper(BaseModel): """Wrapper for Google Search API. ...
https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html