id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
eb40fba301bb-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 |
eb40fba301bb-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 |
db8a3cda8cc0-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 |
8a655dfe8ed0-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 |
8a655dfe8ed0-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 |
bf7970356b98-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 |
bf7970356b98-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 |
a80e4b916c83-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 |
a80e4b916c83-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 |
a80e4b916c83-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 |
a80e4b916c83-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 |
a80e4b916c83-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 |
a80e4b916c83-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 |
d07cdbcd4d2e-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 |
d07cdbcd4d2e-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 |
d07cdbcd4d2e-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 |
da0ab9f84341-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 |
ab0d12f95309-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 |
14f35980c060-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 |
89cd25962d08-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 |
e25b727060df-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 |
e25b727060df-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 |
3775b1f42e12-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 |
3775b1f42e12-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 |
3775b1f42e12-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html |
9bffa0ddd886-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 |
9bffa0ddd886-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 |
9bffa0ddd886-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 |
d2dc901b41c4-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 |
d2dc901b41c4-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 |
913439a7d98c-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 |
913439a7d98c-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 |
eb7e2eab2152-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 |
eb7e2eab2152-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 |
eb7e2eab2152-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 |
aad1b53a2d2e-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 |
aad1b53a2d2e-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 |
a1ba2cdb085d-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 |
a1ba2cdb085d-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 |
a1ba2cdb085d-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 |
102dd30f4408-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 |
102dd30f4408-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 |
102dd30f4408-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 |
68fec0a58b78-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 |
68fec0a58b78-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 |
68fec0a58b78-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 |
147a118c7e76-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 |
147a118c7e76-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 |
147a118c7e76-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 |
147a118c7e76-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 |
147a118c7e76-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 |
cbef440793ca-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 |
cbef440793ca-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 |
f86f04a74390-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 |
f86f04a74390-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 |
f86f04a74390-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 |
f86f04a74390-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 |
f86f04a74390-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 |
225a442af445-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 |
225a442af445-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 |
176f1ce95d67-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 |
176f1ce95d67-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 |
176f1ce95d67-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 |
176f1ce95d67-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 |
176f1ce95d67-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 |
7e3c647bfbe0-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 |
7e3c647bfbe0-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 |
7e3c647bfbe0-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 |
7e3c647bfbe0-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 |
ad8665c545a2-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 |
14d7e2dc2122-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 |
14d7e2dc2122-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 |
14d7e2dc2122-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 |
7d03a937ae14-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 |
7d03a937ae14-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 |
7d03a937ae14-2 | embeddings = OpenAIEmbeddings(
deployment="your-embeddings-deployment-name",
model="your-embeddings-model-name",
api_base="https://your-endpoint.openai.azure.com/",
api_type="azure",
)
text = "This is a test query."
quer... | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
7d03a937ae14-3 | """Validate that api key and python package exists in environment."""
openai_api_key = get_from_dict_or_env(
values, "openai_api_key", "OPENAI_API_KEY"
)
openai_api_base = get_from_dict_or_env(
values,
"openai_api_base",
"OPENAI_API_BASE",
... | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
7d03a937ae14-4 | "Please install it with `pip install openai`."
)
return values
# please refer to
# https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb
def _get_len_safe_embeddings(
self, texts: List[str], *, engine: str, chunk_size: Optional[int] = None
)... | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
7d03a937ae14-5 | self,
input=tokens[i : i + _chunk_size],
engine=self.deployment,
request_timeout=self.request_timeout,
headers=self.headers,
)
batched_embeddings += [r["embedding"] for r in response["data"]]
results: List[List[List[float]]]... | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
7d03a937ae14-6 | return embed_with_retry(
self,
input=[text],
engine=engine,
request_timeout=self.request_timeout,
headers=self.headers,
)["data"][0]["embedding"]
[docs] def embed_documents(
self, texts: List[str], chunk_size: Optiona... | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
b6cd6fc4f0dc-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 |
b6cd6fc4f0dc-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 |
b6cd6fc4f0dc-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 |
b6cd6fc4f0dc-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 |
380ae9432915-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 |
380ae9432915-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 |
841eb51e002d-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 |
841eb51e002d-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 |
f882c23e6342-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 |
395014fcc511-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 |
395014fcc511-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 |
3570fc788d44-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 |
3570fc788d44-1 | if expected_keys != set(prompt_variables):
raise ValueError(
"Got unexpected prompt input variables. The prompt expects "
f"{prompt_variables}, but it should have {expected_keys}."
)
return values
[docs] def save_context(self, inputs: Dict[str, Any], ou... | https://python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
dc3f328adb62-0 | Source code for langchain.memory.kg
from typing import Any, Dict, List, Type, Union
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.graphs import NetworkxEntityGraph
from langchain.graphs.networkx_graph import KnowledgeTriple, get... | https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
dc3f328adb62-1 | entities = self._get_current_entities(inputs)
summary_strings = []
for entity in entities:
knowledge = self.kg.get_entity_knowledge(entity)
if knowledge:
summary = f"On {entity}: {'. '.join(knowledge)}."
summary_strings.append(summary)
cont... | https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
dc3f328adb62-2 | human_prefix=self.human_prefix,
ai_prefix=self.ai_prefix,
)
output = chain.predict(
history=buffer_string,
input=input_string,
)
return get_entities(output)
def _get_current_entities(self, inputs: Dict[str, Any]) -> List[str]:
"""Get the cu... | https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
dc3f328adb62-3 | """Clear memory contents."""
super().clear()
self.kg.clear()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
dbc357095af2-0 | Source code for langchain.memory.buffer
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.memory.chat_memory import BaseChatMemory, BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema import get_buffer_string
[docs]class ConversationBuff... | https://python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
dbc357095af2-1 | @root_validator()
def validate_chains(cls, values: Dict) -> Dict:
"""Validate that return messages is not True."""
if values.get("return_messages", False):
raise ValueError(
"return_messages must be False for ConversationStringBufferMemory"
)
return va... | https://python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
61f5b45588ef-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.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.memory.... | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.