id stringlengths 14 16 | source stringlengths 49 117 | text stringlengths 16 2.73k |
|---|---|---|
73a5efc7936d-11 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | type {operation_name} = (_: {{
{formatted_params}
}}) => any;
"""
return typescript_definition.strip()
@property
def query_params(self) -> List[str]:
return [
property.name
for property in self.properties
if property.location == APIPropertyLocation.QUERY
... |
e609644df4e8-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html | Source code for langchain.tools.openapi.utils.openapi_utils
"""Utility functions for parsing an OpenAPI spec."""
import copy
import json
import logging
import re
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional, Union
import requests
import yaml
from openapi_schema_pydantic import ... |
e609644df4e8-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html | """Get components or err."""
if self.components is None:
raise ValueError("No components found in spec. ")
return self.components
@property
def _parameters_strict(self) -> Dict[str, Union[Parameter, Reference]]:
"""Get parameters or err."""
parameters = self._componen... |
e609644df4e8-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html | [docs] def get_referenced_schema(self, ref: Reference) -> Schema:
"""Get a schema (or nested reference) or err."""
ref_name = ref.ref.split("/")[-1]
schemas = self._schemas_strict
if ref_name not in schemas:
raise ValueError(f"No schema found for {ref_name}")
retur... |
e609644df4e8-3 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html | + " for better support."
)
swagger_version = obj.get("swagger")
openapi_version = obj.get("openapi")
if isinstance(openapi_version, str):
if openapi_version != "3.1.0":
logger.warning(
f"Attempting to load an OpenAPI {openapi_version}"
... |
e609644df4e8-4 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html | """Get an OpenAPI spec from a text."""
try:
spec_dict = json.loads(text)
except json.JSONDecodeError:
spec_dict = yaml.safe_load(text)
return cls.from_spec_dict(spec_dict)
[docs] @classmethod
def from_file(cls, path: Union[str, Path]) -> "OpenAPISpec":
"""G... |
e609644df4e8-5 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html | raise ValueError(f"No {method} method found for {path}")
return operation_obj
[docs] def get_parameters_for_operation(self, operation: Operation) -> List[Parameter]:
"""Get the components for a given operation."""
parameters = []
if operation.parameters:
for parameter in o... |
f82a41f236e8-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html | 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... |
f82a41f236e8-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html | 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,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) ... |
df5e7213403a-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/wolfram_alpha/tool.html | 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... |
d51d3706f71d-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html | 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... |
d51d3706f71d-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html | "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(
default_factory=DuckDuckGoSearchAPIWrapper
)
def _run(
s... |
7077e70dc099-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html | 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... |
7077e70dc099-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html | 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,
run_manager: Optional[AsyncCallbackManagerForToolRun] ... |
383daff6f2b0-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html | 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... |
383daff6f2b0-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html | """Make sure the LLM chain has the correct input variables."""
if llm_chain.prompt.input_variables != [
"tool_input",
"tables",
"schemas",
"examples",
]:
raise ValueError(
"LLM chain for QueryPowerBITool must have input variable... |
383daff6f2b0-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html | return self.session_cache[tool_input]
pbi_result = self.powerbi.run(command=query)
result, error = self._parse_output(pbi_result)
iterations = kwargs.get("iterations", 0)
if error and iterations < self.max_iterations:
return self._run(
tool_input=RETRY_RESPONS... |
383daff6f2b0-3 | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html | iterations = kwargs.get("iterations", 0)
if error and iterations < self.max_iterations:
return await self._arun(
tool_input=RETRY_RESPONSE.format(
tool_input=tool_input, query=query, error=error
),
run_manager=run_manager,
... |
383daff6f2b0-4 | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html | powerbi: PowerBIDataset = Field(exclude=True)
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
def _run(
self,
tool_input: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Get the schema for t... |
383daff6f2b0-5 | https://python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html | return ", ".join(self.powerbi.get_table_names())
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
3b7b27e22a83-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html | 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... |
3b7b27e22a83-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html | "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 = values["size"]
model_name = values["model_name"]
if si... |
3b7b27e22a83-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html | 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
raise RuntimeError(f"[{self.name}] Tool unable to generate image!")
async def _arun(
self... |
881c5f179626-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/brave_search/tool.html | Source code for langchain.tools.brave_search.tool
from __future__ import annotations
from typing import Any, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from langchain.utilities.brave_search import Brav... |
cd95b68ee113-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/pubmed/tool.html | Source code for langchain.tools.pubmed.tool
"""Tool for the Pubmed API."""
from typing import Optional
from pydantic import Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from langchain.utilities.pupmed impor... |
bc16c22b0258-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/scenexplain/tool.html | 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... |
bd67f656ecc4-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/human/tool.html | 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... |
5dab190f82c5-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/openweathermap/tool.html | 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... |
7de065b42627-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html | 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... |
f8055894b9e2-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html | 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... |
f8055894b9e2-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html | thread_id: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> Dict:
"""Run the tool."""
raise NotImplementedError
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
6642553b92f6-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html | 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... |
6642553b92f6-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html | 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()
return {"raw": encoded_message}
def _r... |
6642553b92f6-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html | Last updated on Jun 04, 2023. |
2fff1efcf0a3-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html | 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... |
2fff1efcf0a3-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html | "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(self, threads: List[Dict[str, Any]]) -> List[Dict[str, Any]]:... |
2fff1efcf0a3-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html | "threadId": message_data["threadId"],
"snippet": message_data["snippet"],
"body": body,
"subject": subject,
"sender": sender,
}
)
return results
def _run(
self,
query: str,
res... |
ddef34afc19c-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html | 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... |
ddef34afc19c-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html | "body": body,
"subject": subject,
"sender": sender,
}
async def _arun(
self,
message_id: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> Dict:
"""Run the tool."""
raise NotImplementedError
By Harrison Chase
... |
37cb42529b98-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html | 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.... |
37cb42529b98-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html | 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_message}}
def _run(
self,
message: str,
to: List[... |
42fa2135ba24-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html | 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,
... |
42fa2135ba24-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html | 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 _arun(
self,
query: str,
run_man... |
42fa2135ba24-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html | 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 asynchronously."""
raise NotImplementedError("VectorStoreQAWithSource... |
7611366f5538-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html | 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 ... |
7611366f5538-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html | 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(
... |
68220f9a33ec-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html | 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... |
68220f9a33ec-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html | """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:
from huggingface_hub.inference_api import InferenceApi
repo_id = values... |
68220f9a33ec-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html | return responses
[docs] def embed_query(self, text: str) -> List[float]:
"""Call out to HuggingFaceHub's embedding endpoint for embedding query text.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
response = self.embed_documents([t... |
f75b5b5f818f-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html | Source code for langchain.embeddings.bedrock
import json
import os
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
[docs]class BedrockEmbeddings(BaseModel, Embeddings):
"""Embeddings provider to invoke Bedrock embedd... |
f75b5b5f818f-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html | credentials from IMDS will be used.
See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
"""
model_id: str = "amazon.titan-e1t-medium"
"""Id of the model to call, e.g., amazon.titan-e1t-medium, this is
equivalent to the modelId property in the list-foundation-models ap... |
f75b5b5f818f-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html | """Call out to Bedrock embedding endpoint."""
# replace newlines, which can negatively affect performance.
text = text.replace(os.linesep, " ")
_model_kwargs = self.model_kwargs or {}
input_body = {**_model_kwargs}
input_body["inputText"] = text
body = json.dumps(input_bo... |
f75b5b5f818f-3 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html | return self._embedding_func(text)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
b8151c12f0e9-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html | 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... |
b8151c12f0e9-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html | model_reqs=["./", "torch", "transformers"],
)
Example passing in a pipeline path:
.. code-block:: python
from langchain.embeddings import SelfHostedHFEmbeddings
import runhouse as rh
from transformers import pipeline
gpu = rh.cluster(name="rh-a10x"... |
b8151c12f0e9-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html | Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
text = text.replace("\n", " ")
embeddings = self.client(self.pipeline_ref, text)
if not isinstance(embeddings, list):
return embeddings.tolist()
return embeddings
By H... |
f95fe7655f4b-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html | 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... |
f95fe7655f4b-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html | @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_token", "MOSAICML_API_TOKEN"
)
values["mosaicml_api_token"] = mosa... |
f95fe7655f4b-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html | f"Error raised by inference API, no key data: {parsed_response}"
)
embeddings = parsed_response["data"]
except requests.exceptions.JSONDecodeError as e:
raise ValueError(
f"Error raised by inference API: {e}.\nResponse: {response.text}"
)
... |
6e1c7eb58144-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html | 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
... |
6e1c7eb58144-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html | 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 is deployed, eg. `us-west-2`."""
credentials_profile_name: Optional[str]... |
6e1c7eb58144-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html | 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/api/latest/index.html>
"""
class Config:
"""Configuration for this pydantic object."""
extr... |
6e1c7eb58144-3 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html | _endpoint_kwargs = self.endpoint_kwargs or {}
body = self.content_handler.transform_input(texts, _model_kwargs)
content_type = self.content_handler.content_type
accepts = self.content_handler.accepts
# send request
try:
response = self.client.invoke_endpoint(
... |
6e1c7eb58144-4 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html | © Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
d8b678da9124-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html | 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... |
d8b678da9124-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html | """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(lambda x: x.replace("\n", " "), texts))
embeddings = self.embed(texts).numpy()
... |
cffe8d09dd98-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html | 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... |
cffe8d09dd98-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html | "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 with CUDA device id.",
cuda_device_count,
)
client ... |
cffe8d09dd98-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html | 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."""
def __init__(self, **kwargs: Any):
"""Initialize the remote inference function."""
load_fn_kwar... |
cffe8d09dd98-3 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html | embed_instruction: str = DEFAULT_EMBED_INSTRUCTION
"""Instruction to use for embedding documents."""
query_instruction: str = DEFAULT_QUERY_INSTRUCTION
"""Instruction to use for embedding query."""
model_reqs: List[str] = ["./", "InstructorEmbedding", "torch"]
"""Requirements to install on hardware ... |
cffe8d09dd98-4 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html | return embedding.tolist()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
e96c9d8565d2-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html | 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... |
e96c9d8565d2-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html | "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 embedding endpoint.
Args:
texts: The list of texts... |
7091726dac6b-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html | 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):
"""... |
7091726dac6b-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html | 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 key for Aleph Alpha API."""
@root_validator()
def validate_environm... |
7091726dac6b-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html | "compress_to_size": self.compress_to_size,
"normalize": self.normalize,
"contextual_control_threshold": self.contextual_control_threshold,
"control_log_additive": self.control_log_additive,
}
document_request = SemanticEmbeddingRequest(**document_p... |
7091726dac6b-3 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html | The main difference is that here, both the documents and
queries are embedded with a SemanticRepresentation.Symmetric
Example:
.. code-block:: python
from aleph_alpha import AlephAlphaSymmetricSemanticEmbedding
embeddings = AlephAlphaAsymmetricSemanticEmbedding()
text... |
7091726dac6b-4 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html | return document_embeddings
[docs] def embed_query(self, text: str) -> List[float]:
"""Call out to Aleph Alpha's asymmetric, query embedding endpoint
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
return self._embed(text)
By Harriso... |
4bc947884bc3-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html | 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... |
4bc947884bc3-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html | def __init__(self, **kwargs: Any):
"""Initialize the sentence_transformer."""
super().__init__(**kwargs)
try:
import sentence_transformers
except ImportError as exc:
raise ImportError(
"Could not import sentence_transformers python package. "
... |
4bc947884bc3-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html | .. code-block:: python
from langchain.embeddings import HuggingFaceInstructEmbeddings
model_name = "hkunlp/instructor-large"
model_kwargs = {'device': 'cpu'}
encode_kwargs = {'normalize_embeddings': True}
hf = HuggingFaceInstructEmbeddings(
mod... |
4bc947884bc3-3 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html | [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Compute doc embeddings using a HuggingFace instruct model.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
instruction_pairs = [[sel... |
9b40c83fdf9d-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html | 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... |
31d39339d434-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html | 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 ... |
31d39339d434-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html | """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")
"""Number of tokens to process in parallel.
Should be... |
31d39339d434-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html | "use this embedding model: pip install llama-cpp-python"
)
except Exception as e:
raise ValueError(
f"Could not load Llama model from path: {model_path}. "
f"Received error {e}"
)
return values
[docs] def embed_documents(self, texts:... |
c69e259cfa0f-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html | 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_... |
c69e259cfa0f-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html | 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 test document."
... |
c69e259cfa0f-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html | payload = {
"model": self.model,
"type": embed_type,
"texts": texts,
}
# HTTP headers for authorization
headers = {
"Authorization": f"Bearer {self.minimax_api_key}",
"Content-Type": "application/json",
}
params = {
... |
c69e259cfa0f-3 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html | Last updated on Jun 04, 2023. |
82bf94877461-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html | 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... |
82bf94877461-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html | """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 _embed_with_retry(**kwargs)
[docs]class OpenAIEmbeddings(BaseModel, Embeddings):
... |
82bf94877461-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html | 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."
query_result = embeddings.embed_query(text)
"""... |
82bf94877461-3 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html | """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",
... |
82bf94877461-4 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html | openai.proxy = {"http": openai_proxy, "https": openai_proxy} # type: ignore[assignment] # noqa: E501
values["client"] = openai.Embedding
except ImportError:
raise ImportError(
"Could not import openai python package. "
"Please install it with `pip instal... |
82bf94877461-5 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html | indices += [i]
batched_embeddings = []
_chunk_size = chunk_size or self.chunk_size
for i in range(0, len(tokens), _chunk_size):
response = embed_with_retry(
self,
input=tokens[i : i + _chunk_size],
engine=self.deployment,
... |
82bf94877461-6 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html | # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500
# replace newlines, which can negatively affect performance.
text = text.replace("\n", " ")
return embed_with_retry(
self,
input=[text],
engine=en... |
7ebbd3450080-0 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html | 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 import Elasticsearch
from elasticsearch.client import MlClient
from langchain.embeddings.base impor... |
7ebbd3450080-1 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html | 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
cluster.
input_fie... |
7ebbd3450080-2 | https://python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html | "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_password or get_from_env("es_password", "ES_PASSWORD")
# Connect to Elasticsearch
es_connection = Elasti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.