id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
7403d9ea8923-3 | texts (List[str]): Text data.
embedding (Embeddings): Embedding function.
metadatas (Optional[List[dict]]): Metadata for each text if it exists.
Defaults to None.
collection_name (str, optional): Collection name to use. Defaults to
"LangChainCollection... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
7403d9ea8923-4 | Returns:
Zilliz: Zilliz Vector Store
"""
vector_db = cls(
embedding_function=embedding,
collection_name=collection_name,
connection_args=connection_args,
consistency_level=consistency_level,
index_params=index_params,
se... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html |
1bb1e34f84ac-0 | Source code for langchain.vectorstores.supabase
from __future__ import annotations
import uuid
from itertools import repeat
from typing import (
TYPE_CHECKING,
Any,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import numpy as np
from langchain.docstore.document import Document
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-1 | https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/supabase
You can implement your own `match_documents` function in order to limit the search
space to a subset of documents based on your own authorization or business logic.
Note that the Supabase Python client does not yet support asy... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-2 | def __init__(
self,
client: supabase.client.Client,
embedding: Embeddings,
table_name: str,
query_name: Union[str, None] = None,
) -> None:
"""Initialize with supabase client."""
try:
import supabase # noqa: F401
except ImportError:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-3 | ids: Optional[List[str]] = None,
**kwargs: Any,
) -> List[str]:
ids = ids or [str(uuid.uuid4()) for _ in texts]
docs = self._texts_to_documents(texts, metadatas)
vectors = self._embedding.embed_documents(list(texts))
return self.add_vectors(vectors, docs, ids)
[docs] @clas... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-4 | **kwargs: Any,
) -> "SupabaseVectorStore":
"""Return VectorStore initialized from texts and embeddings."""
if not client:
raise ValueError("Supabase client is required.")
if not table_name:
raise ValueError("Supabase document table_name is required.")
embeddin... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-5 | documents: List[Document],
ids: List[str],
) -> List[str]:
return self._add_vectors(self._client, self.table_name, vectors, documents, ids)
[docs] def similarity_search(
self, query: str, k: int = 4, **kwargs: Any
) -> List[Document]:
vectors = self._embedding.embed_documents(... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-6 | self, query: str, k: int = 4, **kwargs: Any
) -> List[Tuple[Document, float]]:
vectors = self._embedding.embed_documents([query])
return self.similarity_search_by_vector_with_relevance_scores(vectors[0], k)
[docs] def similarity_search_by_vector_with_relevance_scores(
self, query: List[fl... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-7 | )
for search in res.data
if search.get("content")
]
return match_result
[docs] def similarity_search_by_vector_returning_embeddings(
self, query: List[float], k: int
) -> List[Tuple[Document, float, np.ndarray[np.float32, Any]]]:
match_documents_params = di... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-8 | np.fromstring(
search.get("embedding", "").strip("[]"), np.float32, sep=","
),
)
for search in res.data
if search.get("content")
]
return match_result
@staticmethod
def _texts_to_documents(
texts: Iterable[str],
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-9 | table_name: str,
vectors: List[List[float]],
documents: List[Document],
ids: List[str],
) -> List[str]:
"""Add vectors to Supabase table."""
rows: List[dict[str, Any]] = [
{
"id": ids[idx],
"content": documents[idx].page_content,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-10 | result = client.from_(table_name).upsert(chunk).execute() # type: ignore
if len(result.data) == 0:
raise Exception("Error inserting: No rows added")
# VectorStore.add_vectors returns ids as strings
ids = [str(i.get("id")) for i in result.data if i.get("id")]
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-11 | among selected documents.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-12 | np.array([embedding], dtype=np.float32),
matched_embeddings,
k=k,
lambda_mult=lambda_mult,
)
filtered_documents = [matched_documents[i] for i in mmr_selected]
return filtered_documents
[docs] def max_marginal_relevance_search(
self,
query: s... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-13 | fetch_k: Number of Documents to fetch to pass to MMR algorithm.
lambda_mult: Number between 0 and 1 that determines the degree
of diversity among the results with 0 corresponding
to maximum diversity and 1 to minimum diversity.
Defaults... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-14 | BEGIN
RETURN query
SELECT
id,
content,
metadata,
embedding,
1 -(docstore.embedding <=> query_embedding) AS similarity
FROM
docstore
ORDER BY
docstore.embedding ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
1bb1e34f84ac-15 | "id": id,
}
for id in ids
]
# TODO: Check if this can be done in bulk
for row in rows:
self._client.from_(self.table_name).delete().eq("id", row["id"]).execute() | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html |
d2b641486c7d-0 | Source code for langchain.vectorstores.docarray.in_memory
"""Wrapper around in-memory storage."""
from __future__ import annotations
from typing import Any, Dict, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_doc... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
d2b641486c7d-1 | ] = "cosine_sim",
**kwargs: Any,
) -> DocArrayInMemorySearch:
"""Initialize DocArrayInMemorySearch store.
Args:
embedding (Embeddings): Embedding function.
metric (str): metric for exact nearest-neighbor search.
Can be one of: "cosine_sim", "euclidean_... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
d2b641486c7d-2 | def from_texts(
cls,
texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[Dict[Any, Any]]] = None,
**kwargs: Any,
) -> DocArrayInMemorySearch:
"""Create an DocArrayInMemorySearch store and insert data.
Args:
texts (List[str]): Text dat... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
d2b641486c7d-3 | """
store = cls.from_params(embedding, **kwargs)
store.add_texts(texts=texts, metadatas=metadatas)
return store | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html |
abf101b55ff0-0 | Source code for langchain.vectorstores.docarray.hnsw
"""Wrapper around Hnswlib store."""
from __future__ import annotations
from typing import Any, List, Literal, Optional
from langchain.embeddings.base import Embeddings
from langchain.vectorstores.docarray.base import (
DocArrayIndex,
_check_docarray_import,
)... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
abf101b55ff0-1 | n_dim: int,
dist_metric: Literal["cosine", "ip", "l2"] = "cosine",
max_elements: int = 1024,
index: bool = True,
ef_construction: int = 200,
ef: int = 10,
M: int = 16,
allow_replace_deleted: bool = True,
num_threads: int = 1,
**kwargs: Any,
) -... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
abf101b55ff0-2 | "cosine", "ip", and "l2". Defaults to "cosine".
max_elements (int): Maximum number of vectors that can be stored.
Defaults to 1024.
index (bool): Whether an index should be built for this field.
Defaults to True.
ef_construction (int): defines a constr... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
abf101b55ff0-3 | **kwargs: Other keyword arguments to be passed to the get_doc_cls method.
"""
_check_docarray_import()
from docarray.index import HnswDocumentIndex
doc_cls = cls._get_doc_cls(
dim=n_dim,
space=dist_metric,
max_elements=max_elements,
index=i... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
abf101b55ff0-4 | embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
work_dir: Optional[str] = None,
n_dim: Optional[int] = None,
**kwargs: Any,
) -> DocArrayHnswSearch:
"""Create an DocArrayHnswSearch store and insert data.
Args:
texts (List[str]): Text data.
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
abf101b55ff0-5 | """
if work_dir is None:
raise ValueError("`work_dir` parameter has not been set.")
if n_dim is None:
raise ValueError("`n_dim` parameter has not been set.")
store = cls.from_params(embedding, work_dir, n_dim, **kwargs)
store.add_texts(texts=texts, metadatas=metad... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html |
a1679a21e396-0 | Source code for langchain.utilities.powerbi
"""Wrapper around a Power BI endpoint."""
from __future__ import annotations
import asyncio
import logging
import os
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
import aiohttp
import requests
from aiohttp import ServerTimeoutError
from pydanti... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-1 | The impersonated_user_name is the UPN of a user to be impersonated.
If the model is not RLS enabled, this will be ignored.
"""
dataset_id: str
table_names: List[str]
group_id: Optional[str] = None
credential: Optional[TokenCredential] = None
token: Optional[str] = None
impersonated_user_... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-2 | def fix_table_names(cls, table_names: List[str]) -> List[str]:
"""Fix the table names."""
return [fix_table_name(table) for table in table_names]
@root_validator(pre=True, allow_reuse=True)
def token_or_credential_present(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that a... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-3 | return f"{BASE_URL}/datasets/{self.dataset_id}/executeQueries" # noqa: E501 # pylint: disable=C0301
@property
def headers(self) -> Dict[str, str]:
"""Get the token."""
if self.token:
return {
"Content-Type": "application/json",
"Authorization": "Beare... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-4 | }
except Exception as exc: # pylint: disable=broad-exception-caught
raise ClientAuthenticationError(
"Could not get a token from the supplied credentials."
) from exc
raise ClientAuthenticationError("No credential or token supplied.")
[docs] de... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-5 | return self.get_table_info()
def _get_tables_to_query(
self, table_names: Optional[Union[List[str], str]] = None
) -> Optional[List[str]]:
"""Get the tables names that need to be queried, after checking they exist."""
if table_names is not None:
if (
isinstanc... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-6 | )
tables = [
table for table in fixed_tables if table not in non_existing_tables
]
return tables if tables else None
if isinstance(table_names, str) and table_names != "":
if table_names not in self.table_names:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-7 | schemas = [
schema for table, schema in self.schemas.items() if table in table_names
]
return ", ".join(schemas)
[docs] def get_table_info(
self, table_names: Optional[Union[List[str], str]] = None
) -> str:
"""Get information about specified tables."""
tables_... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-8 | """Get information about specified tables."""
tables_requested = self._get_tables_to_query(table_names)
if tables_requested is None:
return "No (valid) tables requested."
tables_todo = self._get_tables_todo(tables_requested)
await asyncio.gather(*[self._aget_schema(table) for... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-9 | self.schemas[table] = "unknown"
except Exception as exc: # pylint: disable=broad-exception-caught
_LOGGER.warning("Error while getting table info for %s: %s", table, exc)
self.schemas[table] = "unknown"
async def _aget_schema(self, table: str) -> None:
"""Get the schema for ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-10 | except Exception as exc: # pylint: disable=broad-exception-caught
_LOGGER.warning("Error while getting table info for %s: %s", table, exc)
self.schemas[table] = "unknown"
def _create_json_content(self, command: str) -> dict[str, Any]:
"""Create the json content for the request."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-11 | json=self._create_json_content(command),
headers=self.headers,
timeout=10,
)
return result.json()
[docs] async def arun(self, command: str) -> Any:
"""Execute a DAX command and return the result asynchronously."""
_LOGGER.debug("Running command: %s", command)
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-12 | timeout=10,
) as response:
response_json = await response.json(content_type=response.content_type)
return response_json
def json_to_md(
json_contents: List[Dict[str, Union[str, int, float]]],
table_name: Optional[str] = None,
) -> str:
"""Converts a JSON object to... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
a1679a21e396-13 | return output_md
def fix_table_name(table: str) -> str:
"""Add single quotes around table names that contain spaces."""
if " " in table and not table.startswith("'") and not table.endswith("'"):
return f"'{table}'"
return table | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
876d9a54665d-0 | Source code for langchain.utilities.bing_search
"""Util that calls Bing Search.
In order to set this up, follow instructions at:
https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e
"""
from typing import Dict, List
import requests
from pydantic import BaseModel, Extra, ro... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
876d9a54665d-1 | class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
def _bing_search_results(self, search_term: str, count: int) -> List[dict]:
headers = {"Ocp-Apim-Subscription-Key": self.bing_subscription_key}
params = {
"q": search_term,
"count... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
876d9a54665d-2 | bing_subscription_key = get_from_dict_or_env(
values, "bing_subscription_key", "BING_SUBSCRIPTION_KEY"
)
values["bing_subscription_key"] = bing_subscription_key
bing_search_url = get_from_dict_or_env(
values,
"bing_search_url",
"BING_SEARCH_URL",
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
876d9a54665d-3 | snippets.append(result["snippet"])
return " ".join(snippets)
[docs] def results(self, query: str, num_results: int) -> List[Dict]:
"""Run query through BingSearch and return metadata.
Args:
query: The query to search for.
num_results: The number of results to return.
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
876d9a54665d-4 | "snippet": result["snippet"],
"title": result["name"],
"link": result["url"],
}
metadata_results.append(metadata_result)
return metadata_results | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
dc4ead4e8a3a-0 | Source code for langchain.utilities.serpapi
"""Chain that calls SerpAPI.
Heavily borrowed from https://github.com/ofirpress/self-ask
"""
import os
import sys
from typing import Any, Dict, Optional, Tuple
import aiohttp
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.utils import get_from_dic... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
dc4ead4e8a3a-1 | """Wrapper around SerpAPI.
To use, you should have the ``google-search-results`` python package installed,
and the environment variable ``SERPAPI_API_KEY`` set with your API key, or pass
`serpapi_api_key` as a named parameter to the constructor.
Example:
.. code-block:: python
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
dc4ead4e8a3a-2 | class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
serpapi_api_key = g... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
dc4ead4e8a3a-3 | )
return values
[docs] async def arun(self, query: str, **kwargs: Any) -> str:
"""Run query through SerpAPI and parse result async."""
return self._process_response(await self.aresults(query))
[docs] def run(self, query: str, **kwargs: Any) -> str:
"""Run query through SerpAPI and ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
dc4ead4e8a3a-4 | """Use aiohttp to run query through SerpAPI and return the results async."""
def construct_url_and_params() -> Tuple[str, Dict[str, str]]:
params = self.get_params(query)
params["source"] = "python"
if self.serpapi_api_key:
params["serp_api_key"] = self.serpap... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
dc4ead4e8a3a-5 | return res
[docs] def get_params(self, query: str) -> Dict[str, str]:
"""Get parameters for SerpAPI."""
_params = {
"api_key": self.serpapi_api_key,
"q": query,
}
params = {**self.params, **_params}
return params
@staticmethod
def _process_respo... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
dc4ead4e8a3a-6 | toret = res["answer_box"]["answer"]
elif "answer_box" in res.keys() and "snippet" in res["answer_box"].keys():
toret = res["answer_box"]["snippet"]
elif (
"answer_box" in res.keys()
and "snippet_highlighted_words" in res["answer_box"].keys()
):
tor... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
dc4ead4e8a3a-7 | elif (
"knowledge_graph" in res.keys()
and "description" in res["knowledge_graph"].keys()
):
toret = res["knowledge_graph"]["description"]
elif "snippet" in res["organic_results"][0].keys():
toret = res["organic_results"][0]["snippet"]
elif "link" ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
fc1232f33a70-0 | Source code for langchain.utilities.awslambda
"""Util that calls Lambda."""
import json
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
[docs]class LambdaWrapper(BaseModel):
"""Wrapper for AWS Lambda SDK.
Docs for using:
1. pip install boto3
2. Create a lambd... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html |
fc1232f33a70-1 | """Validate that python package exists in environment."""
try:
import boto3
except ImportError:
raise ImportError(
"boto3 is not installed. Please install it with `pip install boto3`"
)
values["lambda_client"] = boto3.client("lambda")
v... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html |
fc1232f33a70-2 | except StopIteration:
return "Failed to parse response from Lambda"
if answer is None or answer == "":
# We don't want to return the assumption alone if answer is empty
return "Request failed."
else:
return f"Result: {answer}" | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html |
a51280588ea7-0 | Source code for langchain.utilities.bash
"""Wrapper around subprocess to run commands."""
from __future__ import annotations
import platform
import re
import subprocess
from typing import TYPE_CHECKING, List, Union
from uuid import uuid4
if TYPE_CHECKING:
import pexpect
def _lazy_import_pexpect() -> pexpect:
""... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
a51280588ea7-1 | strip_newlines: bool = False,
return_err_output: bool = False,
persistent: bool = False,
):
"""Initialize with stripping newlines."""
self.strip_newlines = strip_newlines
self.return_err_output = return_err_output
self.prompt = ""
self.process = None
i... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
a51280588ea7-2 | )
# Set the custom prompt
process.sendline("PS1=" + prompt)
process.expect_exact(prompt, timeout=10)
return process
[docs] def run(self, commands: Union[str, List[str]]) -> str:
"""Run commands and return final output."""
if isinstance(commands, str):
comma... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
a51280588ea7-3 | ).stdout.decode()
except subprocess.CalledProcessError as error:
if self.return_err_output:
return error.stdout.decode()
return str(error)
if self.strip_newlines:
output = output.strip()
return output
[docs] def process_output(self, output: ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
a51280588ea7-4 | # Clear the output with an empty string
self.process.expect(self.prompt, timeout=10)
self.process.sendline("")
try:
self.process.expect([self.prompt, pexpect.EOF], timeout=10)
except pexpect.TIMEOUT:
return f"Timeout error while executing command {command}"
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
ec2fd479ab82-0 | Source code for langchain.utilities.google_search
"""Util that calls Google Search."""
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class GoogleSearchAPIWrapper(BaseModel):
"""Wrapper for Google Search API.
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
ec2fd479ab82-1 | The current version of the library is 2.70.0 at this time
2. To create an API key:
- Navigate to the APIs & Services→Credentials panel in Cloud Console.
- Select Create credentials, then select API key from the drop-down menu.
- The API key created dialog box displays your newly created key.
- You n... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
ec2fd479ab82-2 | the list of Sites to search.
- Under Search engine ID you’ll find the search-engine-ID.
4. Enable the Custom Search API
- Navigate to the APIs & Services→Dashboard panel in Cloud Console.
- Click Enable APIs and Services.
- Search for Custom Search API and click on it.
- Click Enable.
URL fo... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
ec2fd479ab82-3 | extra = Extra.forbid
def _google_search_results(self, search_term: str, **kwargs: Any) -> List[dict]:
cse = self.search_engine.cse()
if self.siterestrict:
cse = cse.siterestrict()
res = cse.list(q=search_term, cx=self.google_cse_id, **kwargs).execute()
return res.get("ite... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
ec2fd479ab82-4 | values["google_cse_id"] = google_cse_id
try:
from googleapiclient.discovery import build
except ImportError:
raise ImportError(
"google-api-python-client is not installed. "
"Please install it with `pip install google-api-python-client`"
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
ec2fd479ab82-5 | snippets.append(result["snippet"])
return " ".join(snippets)
[docs] def results(self, query: str, num_results: int) -> List[Dict]:
"""Run query through GoogleSearch and return metadata.
Args:
query: The query to search for.
num_results: The number of results to return.... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
ec2fd479ab82-6 | "title": result["title"],
"link": result["link"],
}
if "snippet" in result:
metadata_result["snippet"] = result["snippet"]
metadata_results.append(metadata_result)
return metadata_results | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
9ce3780728f4-0 | Source code for langchain.utilities.max_compute
from __future__ import annotations
from typing import TYPE_CHECKING, Iterator, List, Optional
from langchain.utils import get_from_env
if TYPE_CHECKING:
from odps import ODPS
[docs]class MaxComputeAPIWrapper:
"""Interface for querying Alibaba Cloud MaxCompute tabl... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html |
9ce3780728f4-1 | ) -> MaxComputeAPIWrapper:
"""Convenience constructor that builds the odsp.ODPS MaxCompute client from
given parameters.
Args:
endpoint: MaxCompute endpoint.
project: A project is a basic organizational unit of MaxCompute, which is
similar to a databas... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html |
9ce3780728f4-2 | "https://pyodps.readthedocs.io/."
) from ex
access_id = access_id or get_from_env("access_id", "MAX_COMPUTE_ACCESS_ID")
secret_access_key = secret_access_key or get_from_env(
"secret_access_key", "MAX_COMPUTE_SECRET_ACCESS_KEY"
)
client = ODPS(
access_... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html |
9ce3780728f4-3 | if reader.count == 0:
raise ValueError("Table contains no data.")
for record in reader:
yield {k: v for k, v in record}
[docs] def query(self, query: str) -> List[dict]:
return list(self.lazy_query(query)) | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html |
cce83e8369db-0 | Source code for langchain.utilities.arxiv
"""Util that calls Arxiv."""
import logging
import os
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.schema import Document
logger = logging.getLogger(__name__)
[docs]class ArxivAPIWrapper(BaseModel):
"""Wra... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
cce83e8369db-1 | Parameters:
top_k_results: number of the top-scored document used for the arxiv tool
ARXIV_MAX_QUERY_LENGTH: the cut limit on the query used for the arxiv tool.
load_max_docs: a limit to the number of loaded documents
load_all_available_meta:
if True: the `metadata` of the load... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
cce83e8369db-2 | load_all_available_meta: bool = False
doc_content_chars_max: Optional[int] = 4000
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that the python package exists in ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
cce83e8369db-3 | )
return values
[docs] def run(self, query: str) -> str:
"""
Run Arxiv search and get the article meta information.
See https://lukasschwab.me/arxiv.py/index.html#Search
See https://lukasschwab.me/arxiv.py/index.html#Result
It uses only the most informative fields of a... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
cce83e8369db-4 | f"Authors: {', '.join(a.name for a in result.authors)}\n"
f"Summary: {result.summary}"
for result in results
]
if docs:
return "\n\n".join(docs)[: self.doc_content_chars_max]
else:
return "No good Arxiv Result was found"
[docs] def load(self, qu... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
cce83e8369db-5 | )
try:
results = self.arxiv_search( # type: ignore
query[: self.ARXIV_MAX_QUERY_LENGTH], max_results=self.load_max_docs
).results()
except self.arxiv_exceptions as ex:
logger.debug("Error on arxiv: %s", ex)
return []
docs: List[Doc... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
cce83e8369db-6 | "comment": result.comment,
"journal_ref": result.journal_ref,
"doi": result.doi,
"primary_category": result.primary_category,
"categories": result.categories,
"links": [link.href for link in result.links],
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
6c06f4c78f9a-0 | Source code for langchain.utilities.python
import sys
from io import StringIO
from typing import Dict, Optional
from pydantic import BaseModel, Field
[docs]class PythonREPL(BaseModel):
"""Simulates a standalone Python REPL."""
globals: Optional[Dict] = Field(default_factory=dict, alias="_globals")
locals: O... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/python.html |
65430488521e-0 | Source code for langchain.utilities.openweathermap
"""Util that calls OpenWeatherMap using PyOWM."""
from typing import Any, Dict, Optional
from pydantic import Extra, root_validator
from langchain.tools.base import BaseModel
from langchain.utils import get_from_dict_or_env
[docs]class OpenWeatherMapAPIWrapper(BaseMode... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
65430488521e-1 | @root_validator(pre=True)
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key exists in environment."""
openweathermap_api_key = get_from_dict_or_env(
values, "openweathermap_api_key", "OPENWEATHERMAP_API_KEY"
)
try:
import pyowm
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
65430488521e-2 | temperature = w.temperature("celsius")
rain = w.rain
heat_index = w.heat_index
clouds = w.clouds
return (
f"In {location}, the current weather is as follows:\n"
f"Detailed status: {detailed_status}\n"
f"Wind speed: {wind['speed']} m/s, direction: {wind... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
65430488521e-3 | f"Heat index: {heat_index}\n"
f"Cloud cover: {clouds}%"
)
[docs] def run(self, location: str) -> str:
"""Get the current weather information for a specified location."""
mgr = self.owm.weather_manager()
observation = mgr.weather_at_place(location)
w = observation.w... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
b3a4a5a78c3e-0 | Source code for langchain.utilities.metaphor_search
"""Util that calls Metaphor Search API.
In order to set this up, follow instructions at:
"""
import json
from typing import Dict, List, Optional
import aiohttp
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_d... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
b3a4a5a78c3e-1 | exclude_domains: Optional[List[str]] = None,
start_crawl_date: Optional[str] = None,
end_crawl_date: Optional[str] = None,
start_published_date: Optional[str] = None,
end_published_date: Optional[str] = None,
) -> List[dict]:
headers = {"X-Api-Key": self.metaphor_api_key}
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
b3a4a5a78c3e-2 | # type: ignore
f"{METAPHOR_API_URL}/search",
headers=headers,
json=params,
)
response.raise_for_status()
search_results = response.json()
print(search_results)
return search_results["results"]
@root_validator(pre=True)
def validate_envi... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
b3a4a5a78c3e-3 | start_crawl_date: Optional[str] = None,
end_crawl_date: Optional[str] = None,
start_published_date: Optional[str] = None,
end_published_date: Optional[str] = None,
) -> List[Dict]:
"""Run query through Metaphor Search and return metadata.
Args:
query: The query to... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
b3a4a5a78c3e-4 | include_domains=include_domains,
exclude_domains=exclude_domains,
start_crawl_date=start_crawl_date,
end_crawl_date=end_crawl_date,
start_published_date=start_published_date,
end_published_date=end_published_date,
)
return self._clean_results(r... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
b3a4a5a78c3e-5 | # Function to perform the API call
async def fetch() -> str:
headers = {"X-Api-Key": self.metaphor_api_key}
params = {
"numResults": num_results,
"query": query,
"includeDomains": include_domains,
"excludeDomains": exclude_d... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
b3a4a5a78c3e-6 | return data
else:
raise Exception(f"Error {res.status}: {res.reason}")
results_json_str = await fetch()
results_json = json.loads(results_json_str)
return self._clean_results(results_json["results"])
def _clean_results(self, raw_search_results: Lis... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
babbc793f33e-0 | Source code for langchain.utilities.bibtex
"""Util that calls bibtexparser."""
import logging
from typing import Any, Dict, List, Mapping
from pydantic import BaseModel, Extra, root_validator
logger = logging.getLogger(__name__)
OPTIONAL_FIELDS = [
"annotate",
"booktitle",
"editor",
"howpublished",
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html |
babbc793f33e-1 | This wrapper will use bibtexparser to load a collection of references from
a bibtex file and fetch document summaries.
"""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html |
babbc793f33e-2 | import bibtexparser
with open(path) as file:
entries = bibtexparser.load(file).entries
return entries
[docs] def get_metadata(
self, entry: Mapping[str, Any], load_extra: bool = False
) -> Dict[str, Any]:
"""Get metadata for the given entry."""
publication = en... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html |
babbc793f33e-3 | "authors": entry.get("author"),
"abstract": entry.get("abstract"),
"url": url,
}
if load_extra:
for field in OPTIONAL_FIELDS:
meta[field] = entry.get(field)
return {k: v for k, v in meta.items() if v is not None} | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html |
6b8a3e42080e-0 | Source code for langchain.utilities.searx_search
"""Utility for using SearxNG meta search API.
SearxNG is a privacy-friendly free metasearch engine that aggregates results from
`multiple search engines
<https://docs.searxng.org/admin/engines/configured_engines.html>`_ and databases and
supports the `OpenSearch
<https:/... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
6b8a3e42080e-1 | or exporting the environment variable SEARX_HOST.
Note: this is the only required parameter.
Then create a searx search instance like this:
.. code-block:: python
from langchain.utilities import SearxSearchWrapper
# when the host starts with `http` SSL is disabled and the connection
# is ass... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
6b8a3e42080e-2 | Example usage of the ``run`` method to make a search:
.. code-block:: python
s.run(query="what is the best search engine?")
Engine Parameters
-----------------
You can pass any `accepted searx search API
<https://docs.searxng.org/dev/search_api.html>`_ parameters to the
:py:class:`SearxSearchWrapper` instan... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.