id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
93568b333c3a-4
def from_spec_dict(cls, spec_dict: dict) -> "OpenAPISpec": """Get an OpenAPI spec from a dict.""" return cls.parse_obj(spec_dict) [docs] @classmethod def from_text(cls, text: str) -> "OpenAPISpec": """Get an OpenAPI spec from a text.""" try: spec_dict = json.loads(text...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
93568b333c3a-5
if isinstance(operation, Operation): results.append(method.value) return results [docs] def get_operation(self, path: str, method: str) -> Operation: """Get the operation object for a given path and HTTP method.""" path_item = self._get_path_strict(path) operation_obj ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
93568b333c3a-6
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
88556a72b252-0
Source code for langchain.tools.google_search.tool """Tool for the Google search API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.google_search import Goog...
https://python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html
88556a72b252-1
api_wrapper: GoogleSearchAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query, self.num_results)) async def _arun( self, query: str, ...
https://python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html
e8a95d6a4068-0
Source code for langchain.tools.wolfram_alpha.tool """Tool for the Wolfram Alpha API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.wolfram_alpha import Wolf...
https://python.langchain.com/en/latest/_modules/langchain/tools/wolfram_alpha/tool.html
4400c171f3b9-0
Source code for langchain.tools.ddg_search.tool """Tool for the DuckDuckGo search API.""" import warnings from typing import Any, Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool f...
https://python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html
4400c171f3b9-1
description = ( "A wrapper around Duck Duck Go Search. " "Useful for when you need to answer questions about current events. " "Input should be a search query. Output is a JSON array of the query results" ) num_results: int = 4 api_wrapper: DuckDuckGoSearchAPIWrapper = Field( ...
https://python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html
1804a2900de7-0
Source code for langchain.tools.bing_search.tool """Tool for the Bing search API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.bing_search import BingSearch...
https://python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html
1804a2900de7-1
api_wrapper: BingSearchAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query, self.num_results)) async def _arun( self, query: str, ...
https://python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html
bc6a942b46f5-0
Source code for langchain.tools.powerbi.tool """Tools for interacting with a Power BI dataset.""" from typing import Any, Dict, Optional, Tuple from pydantic import Field, validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.chains.llm i...
https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html
bc6a942b46f5-1
cls, llm_chain: LLMChain ) -> LLMChain: """Make sure the LLM chain has the correct input variables.""" if llm_chain.prompt.input_variables != [ "tool_input", "tables", "schemas", "examples", ]: raise ValueError( "LLM...
https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html
bc6a942b46f5-2
return self.session_cache[tool_input] if query == "I cannot answer this": self.session_cache[tool_input] = query return self.session_cache[tool_input] pbi_result = self.powerbi.run(command=query) result, error = self._parse_output(pbi_result) iterations = kwargs.g...
https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html
bc6a942b46f5-3
self.session_cache[tool_input] = query return self.session_cache[tool_input] pbi_result = await self.powerbi.arun(command=query) result, error = self._parse_output(pbi_result) iterations = kwargs.get("iterations", 0) if error and iterations < self.max_iterations: ...
https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html
bc6a942b46f5-4
Be sure that the tables actually exist by calling list_tables_powerbi first! Example Input: "table1, table2, table3" """ # noqa: E501 powerbi: PowerBIDataset = Field(exclude=True) class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True def _run( ...
https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html
bc6a942b46f5-5
self, tool_input: Optional[str] = None, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Get the names of the tables.""" return ", ".join(self.powerbi.get_table_names()) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on ...
https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html
9d13bdf52b78-0
Source code for langchain.tools.steamship_image_generation.tool """This tool allows agents to generate images using Steamship. Steamship offers access to different third party image generation APIs using a single API key. Today the following models are supported: - Dall-E - Stable Diffusion To use this tool, you must f...
https://python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html
9d13bdf52b78-1
description = ( "Useful for when you need to generate an image." "Input: A detailed text-2-image prompt describing an image" "Output: the UUID of a generated image" ) @root_validator(pre=True) def validate_size(cls, values: Dict) -> Dict: if "size" in values: size...
https://python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html
9d13bdf52b78-2
) task = image_generator.generate(text=query, append_output_to_file=True) task.wait() blocks = task.output.blocks if len(blocks) > 0: if self.return_urls: return make_image_public(self.steamship, blocks[0]) else: return blocks[0].id...
https://python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html
b0093729c7df-0
Source code for langchain.tools.scenexplain.tool """Tool for the SceneXplain API.""" from typing import Optional from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.u...
https://python.langchain.com/en/latest/_modules/langchain/tools/scenexplain/tool.html
7f213e5a6560-0
Source code for langchain.tools.human.tool """Tool for asking human input.""" from typing import Callable, Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool def _print_func(text: st...
https://python.langchain.com/en/latest/_modules/langchain/tools/human/tool.html
c95034fce440-0
Source code for langchain.tools.openweathermap.tool """Tool for the OpenWeatherMap API.""" from typing import Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilit...
https://python.langchain.com/en/latest/_modules/langchain/tools/openweathermap/tool.html
55b921e765e0-0
Source code for langchain.tools.metaphor_search.tool """Tool for the Metaphor search API.""" from typing import Dict, List, Optional, Union from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.me...
https://python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html
5a2e94081b89-0
Source code for langchain.tools.gmail.get_thread from typing import Dict, Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.gmail.base import GmailBaseTool class GetThreadSchema(BaseMod...
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html
5a2e94081b89-1
) return thread_data async def _arun( self, thread_id: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> Dict: """Run the tool.""" raise NotImplementedError By Harrison Chase © Copyright 2023, Harrison Chase. Last updated ...
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html
4d2d2d8d3cad-0
Source code for langchain.tools.gmail.send_message """Send Gmail messages.""" import base64 from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackMa...
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html
4d2d2d8d3cad-1
mime_message["To"] = ", ".join(to) mime_message["Subject"] = subject if cc is not None: mime_message["Cc"] = ", ".join(cc) if bcc is not None: mime_message["Bcc"] = ", ".join(bcc) encoded_message = base64.urlsafe_b64encode(mime_message.as_bytes()).decode() ...
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html
4d2d2d8d3cad-2
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html
31d2c45628e2-0
Source code for langchain.tools.gmail.search import base64 import email from enum import Enum from typing import Any, Dict, List, Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.gmail...
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html
31d2c45628e2-1
name: str = "search_gmail" description: str = ( "Use this tool to search for email messages or threads." " The input must be a valid Gmail query." " The output is a JSON list of the requested resource." ) args_schema: Type[SearchArgsSchema] = SearchArgsSchema def _parse_threads(s...
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html
31d2c45628e2-2
body = clean_email_body(message_body) results.append( { "id": message["id"], "threadId": message_data["threadId"], "snippet": message_data["snippet"], "body": body, "subject": subject, ...
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html
2e26cef24e09-0
Source code for langchain.tools.gmail.get_message import base64 import email from typing import Dict, Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.gmail.base import GmailBaseTool f...
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html
2e26cef24e09-1
"snippet": message_data["snippet"], "body": body, "subject": subject, "sender": sender, } async def _arun( self, message_id: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> Dict: """Run the tool.""" raise...
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html
5c8f928ff6c8-0
Source code for langchain.tools.gmail.create_draft import base64 from email.message import EmailMessage from typing import List, Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.gmail....
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html
5c8f928ff6c8-1
draft_message["Subject"] = subject if cc is not None: draft_message["Cc"] = ", ".join(cc) if bcc is not None: draft_message["Bcc"] = ", ".join(bcc) encoded_message = base64.urlsafe_b64encode(draft_message.as_bytes()).decode() return {"message": {"raw": encoded_mes...
https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html
bbf24eee1021-0
Source code for langchain.tools.vectorstore.tool """Tools for interacting with vectorstores.""" import json from typing import Any, Dict, Optional from pydantic import BaseModel, Field from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, ...
https://python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
bbf24eee1021-1
def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" chain = RetrievalQA.from_chain_type( self.llm, retriever=self.vectorstore.as_retriever() ) return chain.run(query) async def _aru...
https://python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
bbf24eee1021-2
self.llm, retriever=self.vectorstore.as_retriever() ) return json.dumps(chain({chain.question_key: query}, return_only_outputs=True)) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchr...
https://python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html
60465eca6614-0
Source code for langchain.tools.google_serper.tool """Tool for the Serper.dev Google Search API.""" from typing import Optional from pydantic.fields import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from ...
https://python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html
60465eca6614-1
) api_wrapper: GoogleSerperAPIWrapper = Field(default_factory=GoogleSerperAPIWrapper) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query)) async def _arun( ...
https://python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html
396ea421d475-0
Source code for langchain.embeddings.huggingface_hub """Wrapper around HuggingFace Hub embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env DEFAULT_REPO_ID...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
396ea421d475-1
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" huggingfacehub_api_token = get_from_dict_or_env( values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN" ) try: ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
396ea421d475-2
texts = [text.replace("\n", " ") for text in texts] _model_kwargs = self.model_kwargs or {} responses = self.client(inputs=texts, params=_model_kwargs) return responses [docs] def embed_query(self, text: str) -> List[float]: """Call out to HuggingFaceHub's embedding endpoint for embed...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
17d9cece70bc-0
Source code for langchain.embeddings.self_hosted """Running custom embedding models on self-hosted remote hardware.""" from typing import Any, Callable, List from pydantic import Extra from langchain.embeddings.base import Embeddings from langchain.llms import SelfHostedPipeline def _embed_documents(pipeline: Any, *arg...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
17d9cece70bc-1
model_load_fn=get_pipeline, hardware=gpu model_reqs=["./", "torch", "transformers"], ) Example passing in a pipeline path: .. code-block:: python from langchain.embeddings import SelfHostedHFEmbeddings import runhouse as rh from...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
17d9cece70bc-2
[docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a HuggingFace transformer model. Args: text: The text to embed. Returns: Embeddings for the text. """ text = text.replace("\n", " ") embeddings = self.clie...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
14cb7f8ed96b-0
Source code for langchain.embeddings.mosaicml """Wrapper around MosaicML APIs.""" from typing import Any, Dict, List, Mapping, Optional, Tuple import requests from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env [docs]cla...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
14cb7f8ed96b-1
"""Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" mosaicml_api_token = get_from_dict_or_env( values, "mosaicml_api_tok...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
14cb7f8ed96b-2
f"Error raised by inference API: {parsed_response['error']}" ) if "data" not in parsed_response: raise ValueError( f"Error raised by inference API, no key data: {parsed_response}" ) embeddings = parsed_response["data"] e...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
8beb567aa05b-0
Source code for langchain.embeddings.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.llms.sagemaker_endpoint import ContentHandlerBase ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
8beb567aa05b-1
credentials_profile_name=credentials_profile_name ) """ client: Any #: :meta private: endpoint_name: str = "" """The name of the endpoint from the deployed Sagemaker model. Must be unique within an AWS Region.""" region_name: str = "" """The aws region where the Sagemaker model ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
8beb567aa05b-2
""" # noqa: E501 model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" endpoint_kwargs: Optional[Dict] = None """Optional attributes passed to the invoke_endpoint function. See `boto3`_. docs for more info. .. _boto3: <https://boto3.amazonaws.com/v1/documentation/ap...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
8beb567aa05b-3
# replace newlines, which can negatively affect performance. texts = list(map(lambda x: x.replace("\n", " "), texts)) _model_kwargs = self.model_kwargs or {} _endpoint_kwargs = self.endpoint_kwargs or {} body = self.content_handler.transform_input(texts, _model_kwargs) content_ty...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
8beb567aa05b-4
"""Compute query embeddings using a SageMaker inference endpoint. Args: text: The text to embed. Returns: Embeddings for the text. """ return self._embedding_func([text])[0] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Ma...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
2c87814e1a7f-0
Source code for langchain.embeddings.tensorflow_hub """Wrapper around TensorflowHub embedding models.""" from typing import Any, List from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings DEFAULT_MODEL_URL = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3" [docs]clas...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
2c87814e1a7f-1
[docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Compute doc embeddings using a TensorflowHub embedding model. Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text. """ texts = list(map(lambd...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
22175e325a36-0
Source code for langchain.embeddings.self_hosted_hugging_face """Wrapper around HuggingFace embedding models for self-hosted remote hardware.""" import importlib import logging from typing import Any, Callable, List, Optional from langchain.embeddings.self_hosted import SelfHostedEmbeddings DEFAULT_MODEL_NAME = "senten...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
22175e325a36-1
if device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer associated wi...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
22175e325a36-2
model_load_fn: Callable = load_embedding_model """Function to load the model remotely on the server.""" load_fn_kwargs: Optional[dict] = None """Key word arguments to pass to the model load function.""" inference_fn: Callable = _embed_documents """Inference function to extract the embeddings.""" ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
22175e325a36-3
model_name=model_name, hardware=gpu) """ model_id: str = DEFAULT_INSTRUCT_MODEL """Model name to use.""" embed_instruction: str = DEFAULT_EMBED_INSTRUCTION """Instruction to use for embedding documents.""" query_instruction: str = DEFAULT_QUERY_INSTRUCTION """Instruction to use for embedding...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
22175e325a36-4
text: The text to embed. Returns: Embeddings for the text. """ instruction_pair = [self.query_instruction, text] embedding = self.client(self.pipeline_ref, [instruction_pair])[0] return embedding.tolist() By Harrison Chase © Copyright 2023, Harrison Chase. ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
6590484d1714-0
Source code for langchain.embeddings.cohere """Wrapper around Cohere embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env [docs]class CohereEmbeddings(Base...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
6590484d1714-1
except ImportError: raise ImportError( "Could not import cohere python package. " "Please install it with `pip install cohere`." ) return values [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Call out to Cohere's emb...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
03a5291bd172-0
Source code for langchain.embeddings.aleph_alpha from typing import Any, Dict, List, Optional from pydantic import BaseModel, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env [docs]class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embeddings): """...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
03a5291bd172-1
"""Attention control parameters only apply to those tokens that have explicitly been set in the request.""" control_log_additive: Optional[bool] = True """Apply controls on prompt items by adding the log(control_factor) to attention scores.""" aleph_alpha_api_key: Optional[str] = None """API k...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
03a5291bd172-2
document_params = { "prompt": Prompt.from_text(text), "representation": SemanticRepresentation.Document, "compress_to_size": self.compress_to_size, "normalize": self.normalize, "contextual_control_threshold": self.contextual_control_thresho...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
03a5291bd172-3
request=symmetric_request, model=self.model ) return symmetric_response.embedding [docs]class AlephAlphaSymmetricSemanticEmbedding(AlephAlphaAsymmetricSemanticEmbedding): """The symmetric version of the Aleph Alpha's semantic embeddings. The main difference is that here, both the documents and ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
03a5291bd172-4
"""Call out to Aleph Alpha's Document endpoint. Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text. """ document_embeddings = [] for text in texts: document_embeddings.append(self._embed(text)) retur...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
84fbc8cfa9fb-0
Source code for langchain.embeddings.huggingface """Wrapper around HuggingFace embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, Field from langchain.embeddings.base import Embeddings DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2" DEFAULT_INSTRUCT_M...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
84fbc8cfa9fb-1
super().__init__(**kwargs) try: import sentence_transformers except ImportError as exc: raise ImportError( "Could not import sentence_transformers python package. " "Please install it with `pip install sentence_transformers`." ) from ex...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
84fbc8cfa9fb-2
from langchain.embeddings import HuggingFaceInstructEmbeddings model_name = "hkunlp/instructor-large" model_kwargs = {'device': 'cpu'} hf = HuggingFaceInstructEmbeddings( model_name=model_name, model_kwargs=model_kwargs ) """ client: Any #: :meta ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
84fbc8cfa9fb-3
Returns: List of embeddings, one for each text. """ instruction_pairs = [[self.embed_instruction, text] for text in texts] embeddings = self.client.encode(instruction_pairs) return embeddings.tolist() [docs] def embed_query(self, text: str) -> List[float]: """Compu...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
b9515522e982-0
Source code for langchain.embeddings.fake from typing import List import numpy as np from pydantic import BaseModel from langchain.embeddings.base import Embeddings [docs]class FakeEmbeddings(Embeddings, BaseModel): size: int def _get_embedding(self) -> List[float]: return list(np.random.normal(size=sel...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html
bc84873158be-0
Source code for langchain.embeddings.llamacpp """Wrapper around llama.cpp embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, Field, root_validator from langchain.embeddings.base import Embeddings [docs]class LlamaCppEmbeddings(BaseModel, Embeddings): """Wrapper ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
bc84873158be-1
use_mlock: bool = Field(False, alias="use_mlock") """Force system to keep model in RAM.""" n_threads: Optional[int] = Field(None, alias="n_threads") """Number of threads to use. If None, the number of threads is automatically determined.""" n_batch: Optional[int] = Field(8, alias="n_batch") """...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
bc84873158be-2
raise ModuleNotFoundError( "Could not import llama-cpp-python library. " "Please install the llama-cpp-python library to " "use this embedding model: pip install llama-cpp-python" ) except Exception as e: raise ValueError( f...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
1ee374e76ed4-0
Source code for langchain.embeddings.minimax """Wrapper around MiniMax APIs.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional import requests from pydantic import BaseModel, Extra, root_validator from tenacity import ( before_sleep_log, retry, stop_...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
1ee374e76ed4-1
the constructor. Example: .. code-block:: python from langchain.embeddings import MiniMaxEmbeddings embeddings = MiniMaxEmbeddings() query_text = "This is a test query." query_result = embeddings.embed_query(query_text) document_text = "This is a t...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
1ee374e76ed4-2
self, texts: List[str], embed_type: str, ) -> List[List[float]]: payload = { "model": self.model, "type": embed_type, "texts": texts, } # HTTP headers for authorization headers = { "Authorization": f"Bearer {self.minimax...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
1ee374e76ed4-3
) return embeddings[0] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
37cf40f2c72a-0
Source code for langchain.embeddings.openai """Wrapper around OpenAI embedding models.""" from __future__ import annotations import logging from typing import ( Any, Callable, Dict, List, Literal, Optional, Sequence, Set, Tuple, Union, ) import numpy as np from pydantic import Ba...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
37cf40f2c72a-1
def embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) -> Any: """Use tenacity to retry the embedding call.""" retry_decorator = _create_retry_decorator(embeddings) @retry_decorator def _embed_with_retry(**kwargs: Any) -> Any: return embeddings.client.create(**kwargs) return _embe...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
37cf40f2c72a-2
from langchain.embeddings.openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings( deployment="your-embeddings-deployment-name", model="your-embeddings-model-name", api_base="https://your-endpoint.openai.azure.com/", api_type="azure", ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
37cf40f2c72a-3
"""Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" openai_api_key = get_from_dict_or_env( values, "openai_api_key", "OP...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
37cf40f2c72a-4
if openai_api_type: openai.api_version = openai_api_version if openai_api_type: openai.api_type = openai_api_type if openai_proxy: openai.proxy = {"http": openai_proxy, "https": openai_proxy} # type: ignore[assignment] # noqa: E501 va...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
37cf40f2c72a-5
token = encoding.encode( text, allowed_special=self.allowed_special, disallowed_special=self.disallowed_special, ) for j in range(0, len(token), self.embedding_ctx_length): tokens += [token[j : j + self.embedding_ctx_length]] ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
37cf40f2c72a-6
def _embedding_func(self, text: str, *, engine: str) -> List[float]: """Call out to OpenAI's embedding endpoint.""" # handle large input text if len(text) > self.embedding_ctx_length: return self._get_len_safe_embeddings([text], engine=engine)[0] else: if self.mod...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
37cf40f2c72a-7
text: The text to embed. Returns: Embedding for the text. """ embedding = self._embedding_func(text, engine=self.deployment) return embedding By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
56097e741f53-0
Source code for langchain.embeddings.elasticsearch from __future__ import annotations from typing import TYPE_CHECKING, List, Optional from langchain.utils import get_from_env if TYPE_CHECKING: from elasticsearch.client import MlClient from langchain.embeddings.base import Embeddings [docs]class ElasticsearchEmbedd...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
56097e741f53-1
es_user: Optional[str] = None, es_password: Optional[str] = None, input_field: str = "text_field", ) -> ElasticsearchEmbeddings: """Instantiate embeddings from Elasticsearch credentials. Args: model_id (str): The model_id of the model deployed in the Elasticsearch ...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
56097e741f53-2
raise ImportError( "elasticsearch package not found, please install with 'pip install " "elasticsearch'" ) es_cloud_id = es_cloud_id or get_from_env("es_cloud_id", "ES_CLOUD_ID") es_user = es_user or get_from_env("es_user", "ES_USER") es_password = es_...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
56097e741f53-3
list. """ return self._embedding_func(texts) [docs] def embed_query(self, text: str) -> List[float]: """ Generate an embedding for a single query text. Args: text (str): The query text to generate an embedding for. Returns: List[float]: The embe...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
6a1788186c79-0
Source code for langchain.embeddings.modelscope_hub """Wrapper around ModelScopeHub embedding models.""" from typing import Any, List from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings [docs]class ModelScopeEmbeddings(BaseModel, Embeddings): """Wrapper around modelscope_hub embed...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html
6a1788186c79-1
""" texts = list(map(lambda x: x.replace("\n", " "), texts)) inputs = {"source_sentence": texts} embeddings = self.embed(input=inputs)["text_embedding"] return embeddings.tolist() [docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a model...
https://python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html
7b5212fd532a-0
Source code for langchain.memory.vectorstore """Class for a VectorStore-backed memory object.""" from typing import Any, Dict, List, Optional, Union from pydantic import Field from langchain.memory.chat_memory import BaseMemory from langchain.memory.utils import get_prompt_input_key from langchain.schema import Documen...
https://python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html
7b5212fd532a-1
docs = self.retriever.get_relevant_documents(query) result: Union[List[Document], str] if not self.return_docs: result = "\n".join([doc.page_content for doc in docs]) else: result = docs return {self.memory_key: result} def _form_documents( self, input...
https://python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html
5169df016d96-0
Source code for langchain.memory.buffer_window from typing import Any, Dict, List from langchain.memory.chat_memory import BaseChatMemory from langchain.schema import BaseMessage, get_buffer_string [docs]class ConversationBufferWindowMemory(BaseChatMemory): """Buffer for storing conversation memory.""" human_pr...
https://python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html
de0ea643fc87-0
Source code for langchain.memory.token_buffer from typing import Any, Dict, List from langchain.base_language import BaseLanguageModel from langchain.memory.chat_memory import BaseChatMemory from langchain.schema import BaseMessage, get_buffer_string [docs]class ConversationTokenBufferMemory(BaseChatMemory): """Buf...
https://python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html
de0ea643fc87-1
if curr_buffer_length > self.max_token_limit: pruned_memory = [] while curr_buffer_length > self.max_token_limit: pruned_memory.append(buffer.pop(0)) curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer) By Harrison Chase © Copyright 2023, ...
https://python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html
bb522134744e-0
Source code for langchain.memory.summary_buffer from typing import Any, Dict, List from pydantic import root_validator from langchain.memory.chat_memory import BaseChatMemory from langchain.memory.summary import SummarizerMixin from langchain.schema import BaseMessage, get_buffer_string [docs]class ConversationSummaryB...
https://python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html