id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 59 127 |
|---|---|---|
e81835ae1e31-1 | [docs] def compress_documents(
self, documents: Sequence[Document], query: str
) -> Sequence[Document]:
"""Compress page content of raw documents."""
compressed_docs = []
for doc in documents:
_input = self.get_input(query, doc)
output = self.llm_chain.pred... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/document_compressors/chain_extract.html |
e81835ae1e31-2 | _get_input = get_input if get_input is not None else default_get_input
llm_chain = LLMChain(llm=llm, prompt=_prompt, **(llm_chain_kwargs or {}))
return cls(llm_chain=llm_chain, get_input=_get_input)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/document_compressors/chain_extract.html |
60740aa489fa-0 | Source code for langchain.retrievers.document_compressors.embeddings_filter
"""Document compressor that uses embeddings to drop documents unrelated to the query."""
from typing import Callable, Dict, Optional, Sequence
import numpy as np
from pydantic import root_validator
from langchain.document_transformers import (
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
60740aa489fa-1 | return values
[docs] def compress_documents(
self, documents: Sequence[Document], query: str
) -> Sequence[Document]:
"""Filter documents based on similarity of their embeddings to the query."""
stateful_documents = get_stateful_documents(documents)
embedded_documents = _get_embed... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
2f65685fb82a-0 | Source code for langchain.retrievers.document_compressors.chain_filter
"""Filter that uses an LLM to drop documents that aren't relevant to the query."""
from typing import Any, Callable, Dict, Optional, Sequence
from langchain import BasePromptTemplate, LLMChain, PromptTemplate
from langchain.base_language import Base... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/document_compressors/chain_filter.html |
2f65685fb82a-1 | include_doc = self.llm_chain.predict_and_parse(**_input)
if include_doc:
filtered_docs.append(doc)
return filtered_docs
[docs] async def acompress_documents(
self, documents: Sequence[Document], query: str
) -> Sequence[Document]:
"""Filter down documents."""
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/retrievers/document_compressors/chain_filter.html |
8822b267f193-0 | Source code for langchain.utilities.duckduckgo_search
"""Util that calls DuckDuckGo Search.
No setup required. Free.
https://pypi.org/project/duckduckgo-search/
"""
from typing import Dict, List, Optional
from pydantic import BaseModel, Extra
from pydantic.class_validators import root_validator
[docs]class DuckDuckGoSe... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/duckduckgo_search.html |
8822b267f193-1 | )
if results is None or len(results) == 0:
return ["No good DuckDuckGo Search Result was found"]
snippets = [result["body"] for result in results]
return snippets
[docs] def run(self, query: str) -> str:
snippets = self.get_snippets(query)
return " ".join(snippets)... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/duckduckgo_search.html |
1f014f3d7ed1-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/bing_search.html |
1f014f3d7ed1-1 | bing_subscription_key = get_from_dict_or_env(
values, "bing_subscription_key", "BING_SUBSCRIPTION_KEY"
)
values["bing_subscription_key"] = bing_subscription_key
bing_search_url = get_from_dict_or_env(
values,
"bing_search_url",
"BING_SEARCH_URL",
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/bing_search.html |
1f014f3d7ed1-2 | "snippet": result["snippet"],
"title": result["name"],
"link": result["url"],
}
metadata_results.append(metadata_result)
return metadata_results
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/bing_search.html |
ae20e61372a4-0 | Source code for langchain.utilities.google_places_api
"""Chain that calls Google Places API.
"""
import logging
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class GooglePlacesAPIWrapper(BaseModel):
"""Wrapper arou... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_places_api.html |
ae20e61372a4-1 | except ImportError:
raise ImportError(
"Could not import googlemaps python package. "
"Please install it with `pip install googlemaps`."
)
return values
[docs] def run(self, query: str) -> str:
"""Run Places search and get k number of places tha... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_places_api.html |
ae20e61372a4-2 | "formatted_address", "Unknown"
)
phone_number = place_details.get("result", {}).get(
"formatted_phone_number", "Unknown"
)
website = place_details.get("result", {}).get("website", "Unknown")
formatted_details = (
f"{name}\nAddre... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_places_api.html |
c3212345b4bb-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:
""... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/bash.html |
c3212345b4bb-1 | # Set the custom prompt
process.sendline("PS1=" + prompt)
process.expect_exact(prompt, timeout=10)
return process
[docs] def run(self, commands: Union[str, List[str]]) -> str:
"""Run commands and return final output."""
if isinstance(commands, str):
commands = [com... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/bash.html |
c3212345b4bb-2 | self.process.expect(self.prompt, timeout=10)
self.process.sendline("")
try:
self.process.expect([self.prompt, pexpect.EOF], timeout=10)
except pexpect.TIMEOUT:
return f"Timeout error while executing command {command}"
if self.process.after == pexpect.EOF:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/bash.html |
13e587cdb737-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html |
13e587cdb737-1 | """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 at least one of token and credentials is present."""
if "token" ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html |
13e587cdb737-2 | "Could not get a token from the supplied credentials."
) from exc
raise ClientAuthenticationError("No credential or token supplied.")
[docs] def get_table_names(self) -> Iterable[str]:
"""Get names of tables available."""
return self.table_names
[docs] def get_schemas(self)... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html |
13e587cdb737-3 | if isinstance(table_names, str) and table_names != "":
if table_names not in self.table_names:
_LOGGER.warning("Table %s not found in dataset.", table_names)
return None
return [fix_table_name(table_names)]
return self.table_names
def _... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html |
13e587cdb737-4 | tables_todo = self._get_tables_todo(tables_requested)
await asyncio.gather(*[self._aget_schema(table) for table in tables_todo])
return self._get_schema_for_tables(tables_requested)
def _get_schema(self, table: str) -> None:
"""Get the schema for a table."""
try:
result =... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html |
13e587cdb737-5 | self.schemas[table] = "unknown"
def _create_json_content(self, command: str) -> dict[str, Any]:
"""Create the json content for the request."""
return {
"queries": [{"query": rf"{command}"}],
"impersonatedUserName": self.impersonated_user_name,
"serializerSettings"... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html |
13e587cdb737-6 | table_name: Optional[str] = None,
) -> str:
"""Converts a JSON object to a markdown table."""
output_md = ""
headers = json_contents[0].keys()
for header in headers:
header.replace("[", ".").replace("]", "")
if table_name:
header.replace(f"{table_name}.", "")
output_m... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/powerbi.html |
4c4d0726e3db-0 | Source code for langchain.utilities.spark_sql
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Iterable, List, Optional
if TYPE_CHECKING:
from pyspark.sql import DataFrame, Row, SparkSession
[docs]class SparkSQL:
def __init__(
self,
spark_session: Optional[SparkSession] ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/spark_sql.html |
4c4d0726e3db-1 | f"ignore_tables {missing_tables} not found in database"
)
usable_tables = self.get_usable_table_names()
self._usable_tables = set(usable_tables) if usable_tables else self._all_tables
if not isinstance(sample_rows_in_table_info, int):
raise TypeError("sample_rows_in_t... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/spark_sql.html |
4c4d0726e3db-2 | )
# Ignore the data source provider and options to reduce the number of tokens.
using_clause_index = statement.find("USING")
return statement[:using_clause_index] + ";"
[docs] def get_table_info(self, table_names: Optional[List[str]] = None) -> str:
all_table_names = self.get_usable_t... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/spark_sql.html |
4c4d0726e3db-3 | f"{columns_str}\n"
f"{sample_rows_str}"
)
def _convert_row_as_tuple(self, row: Row) -> tuple:
return tuple(map(str, row.asDict().values()))
def _get_dataframe_results(self, df: DataFrame) -> list:
return list(map(self._convert_row_as_tuple, df.collect()))
[docs] def run(se... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/spark_sql.html |
4c4d0726e3db-4 | """
try:
from pyspark.errors import PySparkException
except ImportError:
raise ValueError(
"pyspark is not installed. Please install it with `pip install pyspark`"
)
try:
return self.run(command, fetch)
except PySparkExcepti... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/spark_sql.html |
14e4ebcf3042-0 | Source code for langchain.utilities.google_serper
"""Util that calls Google Search using the Serper.dev API."""
from typing import Any, Dict, List, Optional
import aiohttp
import requests
from pydantic.class_validators import root_validator
from pydantic.main import BaseModel
from typing_extensions import Literal
from ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_serper.html |
14e4ebcf3042-1 | arbitrary_types_allowed = True
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key exists in environment."""
serper_api_key = get_from_dict_or_env(
values, "serper_api_key", "SERPER_API_KEY"
)
values["serper_api_key"] = serp... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_serper.html |
14e4ebcf3042-2 | """Run query through GoogleSearch and parse result async."""
results = await self._async_google_serper_search_results(
query,
gl=self.gl,
hl=self.hl,
num=self.k,
search_type=self.type,
tbs=self.tbs,
**kwargs,
)
r... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_serper.html |
14e4ebcf3042-3 | return ["No good Google Search Result was found"]
return snippets
def _parse_results(self, results: dict) -> str:
return " ".join(self._parse_snippets(results))
def _google_serper_api_results(
self, search_term: str, search_type: str = "search", **kwargs: Any
) -> dict:
heade... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_serper.html |
14e4ebcf3042-4 | else:
async with self.aiosession.post(
url, params=params, headers=headers, raise_for_status=True
) as response:
search_results = await response.json()
return search_results
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updat... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_serper.html |
3e8db829d8db-0 | Source code for langchain.utilities.apify
from typing import Any, Callable, Dict, Optional
from pydantic import BaseModel, root_validator
from langchain.document_loaders import ApifyDatasetLoader
from langchain.document_loaders.base import Document
from langchain.utils import get_from_dict_or_env
[docs]class ApifyWrapp... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/apify.html |
3e8db829d8db-1 | *,
build: Optional[str] = None,
memory_mbytes: Optional[int] = None,
timeout_secs: Optional[int] = None,
) -> ApifyDatasetLoader:
"""Run an Actor on the Apify platform and wait for results to be ready.
Args:
actor_id (str): The ID or name of the Actor on the Apify... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/apify.html |
3e8db829d8db-2 | memory_mbytes: Optional[int] = None,
timeout_secs: Optional[int] = None,
) -> ApifyDatasetLoader:
"""Run an Actor on the Apify platform and wait for results to be ready.
Args:
actor_id (str): The ID or name of the Actor on the Apify platform.
run_input (Dict): The inp... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/apify.html |
eaf742a61f87-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
import aiohttp
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/metaphor_search.html |
eaf742a61f87-1 | """Run query through Metaphor Search and return metadata.
Args:
query: The query to search for.
num_results: The number of results to return.
Returns:
A list of dictionaries with the following keys:
title - The title of the
url - The ur... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/metaphor_search.html |
eaf742a61f87-2 | for result in raw_search_results:
cleaned_results.append(
{
"title": result["title"],
"url": result["url"],
"author": result["author"],
"date_created": result["dateCreated"],
}
)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/metaphor_search.html |
6a9f865b7a25-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/serpapi.html |
6a9f865b7a25-1 | aiosession: Optional[aiohttp.ClientSession] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python packag... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/serpapi.html |
6a9f865b7a25-2 | """Use aiohttp to run query through SerpAPI and return the results async."""
def construct_url_and_params() -> Tuple[str, Dict[str, str]]:
params = self.get_params(query)
params["source"] = "python"
if self.serpapi_api_key:
params["serp_api_key"] = self.serpap... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/serpapi.html |
6a9f865b7a25-3 | toret = res["answer_box"]["snippet"]
elif (
"answer_box" in res.keys()
and "snippet_highlighted_words" in res["answer_box"].keys()
):
toret = res["answer_box"]["snippet_highlighted_words"][0]
elif (
"sports_results" in res.keys()
and "g... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/serpapi.html |
caf8d6b73681-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/python.html |
b37913d5a998-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/openweathermap.html |
b37913d5a998-1 | 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['deg']}°\n"
f"Humidity: {humidity}%\n"
f"Tem... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/openweathermap.html |
219b4ab5b17e-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.
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_search.html |
219b4ab5b17e-1 | - 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 for it: https://console.cloud.googl... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_search.html |
219b4ab5b17e-2 | except ImportError:
raise ImportError(
"google-api-python-client is not installed. "
"Please install it with `pip install google-api-python-client`"
)
service = build("customsearch", "v1", developerKey=google_api_key)
values["search_engine"] = serv... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_search.html |
219b4ab5b17e-3 | metadata_result["snippet"] = result["snippet"]
metadata_results.append(metadata_result)
return metadata_results
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/google_search.html |
b41c815a9e51-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/awslambda.html |
b41c815a9e51-1 | answer = json.loads(payload_string)["body"]
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:
retu... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/awslambda.html |
e47c918abe8f-0 | Source code for langchain.utilities.twilio
"""Util that calls Twilio."""
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class TwilioAPIWrapper(BaseModel):
"""Sms Client using Twilio.
To use, you should have the ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/twilio.html |
e47c918abe8f-1 | that is enabled for the type of message you want to send. Phone numbers or
[short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from
Twilio also work here. You cannot, for example, spoof messages from a private
cell phone number. If you are using `messaging_service_sid`, th... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/twilio.html |
e47c918abe8f-2 | characters in length.
to: The destination phone number in
[E.164](https://www.twilio.com/docs/glossary/what-e164) format for
SMS/MMS or
[Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses)
for other 3rd-party chann... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/twilio.html |
9bd1c26b0f42-0 | Source code for langchain.utilities.wolfram_alpha
"""Util that calls WolframAlpha."""
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class WolframAlphaAPIWrapper(BaseModel):
"""Wrapper for Wolfram Alpha.
Docs fo... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/wolfram_alpha.html |
9bd1c26b0f42-1 | res = self.wolfram_client.query(query)
try:
assumption = next(res.pods).text
answer = next(res.results).text
except StopIteration:
return "Wolfram Alpha wasn't able to answer it"
if answer is None or answer == "":
# We don't want to return the assu... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/wolfram_alpha.html |
a244de576cc9-0 | Source code for langchain.utilities.pupmed
import json
import logging
import time
import urllib.error
import urllib.request
from typing import List
from pydantic import BaseModel, Extra
from langchain.schema import Document
logger = logging.getLogger(__name__)
[docs]class PubMedAPIWrapper(BaseModel):
"""
Wrappe... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/pupmed.html |
a244de576cc9-1 | [docs] def run(self, query: str) -> str:
"""
Run PubMed search and get the article meta information.
See https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch
It uses only the most informative fields of article meta information.
"""
try:
# Retrieve ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/pupmed.html |
a244de576cc9-2 | article = self.retrieve_article(uid, webenv)
articles.append(article)
# Convert the list of articles to a JSON string
return articles
def _transform_doc(self, doc: dict) -> Document:
summary = doc.pop("summary")
return Document(page_content=summary, metadata=doc)
[docs] ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/pupmed.html |
a244de576cc9-3 | end_tag = "</ArticleTitle>"
title = xml_text[
xml_text.index(start_tag) + len(start_tag) : xml_text.index(end_tag)
]
# Get abstract
abstract = ""
if "<AbstractText>" in xml_text and "</AbstractText>" in xml_text:
start_tag = "<AbstractText>"
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/pupmed.html |
620aaa8e3229-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:/... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html |
620aaa8e3229-1 | :class:`SearxResults` is a convenience wrapper around the raw json result.
Example usage of the ``run`` method to make a search:
.. code-block:: python
s.run(query="what is the best search engine?")
Engine Parameters
-----------------
You can pass any `accepted searx search API
<https://docs.searxng.org/dev... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html |
620aaa8e3229-2 | .. code-block:: python
# select the github engine and pass the search suffix
s = SearchWrapper("langchain library", query_suffix="!gh")
s = SearchWrapper("langchain library")
# select github the conventional google search syntax
s.run("large language models", query_suffix="site:g... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html |
620aaa8e3229-3 | return {"language": "en", "format": "json"}
[docs]class SearxResults(dict):
"""Dict like wrapper around search api results."""
_data = ""
def __init__(self, data: str):
"""Take a raw result from Searx and make it into a dict like object."""
json_data = json.loads(data)
super().__init... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html |
620aaa8e3229-4 | .. code-block:: python
from langchain.utilities import SearxSearchWrapper
# note the unsecure parameter is not needed if you pass the url scheme as
# http
searx = SearxSearchWrapper(searx_host="http://localhost:8888",
un... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html |
620aaa8e3229-5 | if categories:
values["params"]["categories"] = ",".join(categories)
searx_host = get_from_dict_or_env(values, "searx_host", "SEARX_HOST")
if not searx_host.startswith("http"):
print(
f"Warning: missing the url scheme on host \
! assuming secure ht... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html |
620aaa8e3229-6 | ) as response:
if not response.ok:
raise ValueError("Searx API returned an error: ", response.text)
result = SearxResults(await response.text())
self._result = result
else:
async with self.aiosession.get(
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html |
620aaa8e3229-7 | searx.run("what is the weather in France ?", engine="qwant")
# the same result can be achieved using the `!` syntax of searx
# to select the engine using `query_suffix`
searx.run("what is the weather in France ?", query_suffix="!qwant")
"""
_params = {
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html |
620aaa8e3229-8 | ) -> str:
"""Asynchronously version of `run`."""
_params = {
"q": query,
}
params = {**self.params, **_params, **kwargs}
if self.query_suffix and len(self.query_suffix) > 0:
params["q"] += " " + self.query_suffix
if isinstance(query_suffix, str) an... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html |
620aaa8e3229-9 | engines: List of engines to use for the query.
categories: List of categories to use for the query.
**kwargs: extra parameters to pass to the searx API.
Returns:
Dict with the following keys:
{
snippet: The description of the result.
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html |
620aaa8e3229-10 | ]
[docs] async def aresults(
self,
query: str,
num_results: int,
engines: Optional[List[str]] = None,
query_suffix: Optional[str] = "",
**kwargs: Any,
) -> List[Dict]:
"""Asynchronously query with json results.
Uses aiohttp. See `results` for more i... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/searx_search.html |
25c3228d9ebf-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/arxiv.html |
25c3228d9ebf-1 | 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 environment."""
try:
i... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/arxiv.html |
25c3228d9ebf-2 | 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, query: str) -> List[Document]:
"""
Run Arxiv search and ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/arxiv.html |
25c3228d9ebf-3 | "journal_ref": result.journal_ref,
"doi": result.doi,
"primary_category": result.primary_category,
"categories": result.categories,
"links": [link.href for link in result.links],
}
else:
extra_met... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/arxiv.html |
f40732381726-0 | Source code for langchain.utilities.wikipedia
"""Util that calls Wikipedia."""
import logging
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.schema import Document
logger = logging.getLogger(__name__)
WIKIPEDIA_MAX_QUERY_LENGTH = 300
[docs]class Wikiped... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/wikipedia.html |
f40732381726-1 | summaries = []
for page_title in page_titles[: self.top_k_results]:
if wiki_page := self._fetch_page(page_title):
if summary := self._formatted_page_summary(page_title, wiki_page):
summaries.append(summary)
if not summaries:
return "No good Wik... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/wikipedia.html |
f40732381726-2 | except (
self.wiki_client.exceptions.PageError,
self.wiki_client.exceptions.DisambiguationError,
):
return None
[docs] def load(self, query: str) -> List[Document]:
"""
Run Wikipedia search and get the article text plus the meta information.
See
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/wikipedia.html |
95d7176b16ba-0 | Source code for langchain.utilities.graphql
import json
from typing import Any, Callable, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
[docs]class GraphQLAPIWrapper(BaseModel):
"""Wrapper around GraphQL API.
To use, you should have the ``gql`` python package installed.
This wrapper w... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/graphql.html |
95d7176b16ba-1 | return json.dumps(result, indent=2)
def _execute_query(self, query: str) -> Dict[str, Any]:
"""Execute a GraphQL query and return the results."""
document_node = self.gql_function(query)
result = self.gql_client.execute(document_node)
return result
By Harrison Chase
© Copy... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/utilities/graphql.html |
17ea5f6a2a08-0 | Source code for langchain.prompts.base
"""BasePrompt schema definition."""
from __future__ import annotations
import json
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Union
import yaml
from pydantic import Extra, Field, root_validator... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/base.html |
17ea5f6a2a08-1 | "Please install it with `pip install jinja2`."
)
env = Environment()
ast = env.parse(template)
variables = meta.find_undeclared_variables(ast)
return variables
DEFAULT_FORMATTER_MAPPING: Dict[str, Callable] = {
"f-string": formatter.format,
"jinja2": jinja2_formatter,
}
DEFAULT_VALIDATOR... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/base.html |
17ea5f6a2a08-2 | input_variables: List[str]
"""A list of the names of the variables the prompt template expects."""
output_parser: Optional[BaseOutputParser] = None
"""How to parse the output of calling an LLM on this formatted prompt."""
partial_variables: Mapping[str, Union[str, Callable[[], str]]] = Field(
de... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/base.html |
17ea5f6a2a08-3 | prompt_dict["input_variables"] = list(
set(self.input_variables).difference(kwargs)
)
prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs}
return type(self)(**prompt_dict)
def _merge_partial_and_user_variables(self, **kwargs: Any) -> Dict[str, Any]:
# G... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/base.html |
17ea5f6a2a08-4 | # Convert file to Path object.
if isinstance(file_path, str):
save_path = Path(file_path)
else:
save_path = file_path
directory_path = save_path.parent
directory_path.mkdir(parents=True, exist_ok=True)
# Fetch dictionary to save
prompt_dict = self.... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/base.html |
95a04365fdd4-0 | Source code for langchain.prompts.chat
"""Chat prompt template."""
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, List, Sequence, Tuple, Type, TypeVar, Union
from pydantic import Field
from langchain.load.serializable import Serializable... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/chat.html |
95a04365fdd4-1 | f" got {value}"
)
return value
@property
def input_variables(self) -> List[str]:
"""Input variables for this prompt template."""
return [self.variable_name]
MessagePromptTemplateT = TypeVar(
"MessagePromptTemplateT", bound="BaseStringMessagePromptTemplate"
)
class Bas... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/chat.html |
95a04365fdd4-2 | text = self.prompt.format(**kwargs)
return ChatMessage(
content=text, role=self.role, additional_kwargs=self.additional_kwargs
)
class HumanMessagePromptTemplate(BaseStringMessagePromptTemplate):
def format(self, **kwargs: Any) -> BaseMessage:
text = self.prompt.format(**kwargs)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/chat.html |
95a04365fdd4-3 | input_variables: List[str]
messages: List[Union[BaseMessagePromptTemplate, BaseMessage]]
@classmethod
def from_template(cls, template: str, **kwargs: Any) -> ChatPromptTemplate:
prompt_template = PromptTemplate.from_template(template, **kwargs)
message = HumanMessagePromptTemplate(prompt=pro... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/chat.html |
95a04365fdd4-4 | kwargs = self._merge_partial_and_user_variables(**kwargs)
result = []
for message_template in self.messages:
if isinstance(message_template, BaseMessage):
result.extend([message_template])
elif isinstance(message_template, BaseMessagePromptTemplate):
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/chat.html |
3d6d238bc73d-0 | Source code for langchain.prompts.prompt
"""Prompt schema definition."""
from __future__ import annotations
from pathlib import Path
from string import Formatter
from typing import Any, Dict, List, Union
from pydantic import Extra, root_validator
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
S... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/prompt.html |
3d6d238bc73d-1 | A formatted string.
Example:
.. code-block:: python
prompt.format(variable1="foo")
"""
kwargs = self._merge_partial_and_user_variables(**kwargs)
return DEFAULT_FORMATTER_MAPPING[self.template_format](self.template, **kwargs)
@root_validator()
def template_is_v... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/prompt.html |
3d6d238bc73d-2 | return cls(input_variables=input_variables, template=template, **kwargs)
[docs] @classmethod
def from_file(
cls, template_file: Union[str, Path], input_variables: List[str], **kwargs: Any
) -> PromptTemplate:
"""Load a prompt from a file.
Args:
template_file: The path to t... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/prompt.html |
b4e412da001d-0 | Source code for langchain.prompts.few_shot_with_templates
"""Prompt template that contains few shot examples."""
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.prompts.base import DEFAULT_FORMATTER_MAPPING, StringPromptTemplate
from langchain.prompts.example_selec... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/few_shot_with_templates.html |
b4e412da001d-1 | examples = values.get("examples", None)
example_selector = values.get("example_selector", None)
if examples and example_selector:
raise ValueError(
"Only one of 'examples' and 'example_selector' should be provided"
)
if examples is None and example_selecto... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/few_shot_with_templates.html |
b4e412da001d-2 | Args:
kwargs: Any arguments to be passed to the prompt template.
Returns:
A formatted string.
Example:
.. code-block:: python
prompt.format(variable1="foo")
"""
kwargs = self._merge_partial_and_user_variables(**kwargs)
# Get the example... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/few_shot_with_templates.html |
b4e412da001d-3 | """Return a dictionary of the prompt."""
if self.example_selector:
raise ValueError("Saving an example selector is not currently supported")
return super().dict(**kwargs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/few_shot_with_templates.html |
4a77e11a2347-0 | Source code for langchain.prompts.few_shot
"""Prompt template that contains few shot examples."""
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
StringPromptTemplate,
check_valid_template,
)
from langcha... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/prompts/few_shot.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.