id stringlengths 14 16 | text stringlengths 44 2.73k | source stringlengths 49 114 |
|---|---|---|
59c1f05558a3-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... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
59c1f05558a3-2 | else:
async with self.aiosession.get(url, params=params) as response:
res = await response.json()
return self._process_response(res)
[docs] def run(self, query: str) -> str:
"""Run query through SerpAPI and parse result."""
return self._process_response(self.result... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
59c1f05558a3-3 | ):
toret = res["answer_box"]["snippet_highlighted_words"][0]
elif (
"sports_results" in res.keys()
and "game_spotlight" in res["sports_results"].keys()
):
toret = res["sports_results"]["game_spotlight"]
elif (
"knowledge_graph" in res.k... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
99cbc9b7a787-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... | https://python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html |
99cbc9b7a787-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... | https://python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html |
51f7c28eeaed-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://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
51f7c28eeaed-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... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
51f7c28eeaed-2 | 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`"
)
service = build("customsearch", "v1", developerKey=go... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
51f7c28eeaed-3 | if "snippet" in result:
metadata_result["snippet"] = result["snippet"]
metadata_results.append(metadata_result)
return metadata_results
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 25, 2023. | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
476d98ad312b-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://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
476d98ad312b-1 | 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://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
3166e1c08acf-0 | Source code for langchain.utilities.bash
"""Wrapper around subprocess to run commands."""
import subprocess
from typing import List, Union
[docs]class BashProcess:
"""Executes bash commands and returns the output."""
def __init__(self, strip_newlines: bool = False, return_err_output: bool = False):
"""I... | https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
e7b8f54630a4-0 | Source code for langchain.utilities.arxiv
"""Util that calls Arxiv."""
from typing import Any, Dict
from pydantic import BaseModel, Extra, root_validator
[docs]class ArxivAPIWrapper(BaseModel):
"""Wrapper around ArxivAPI.
To use, you should have the ``arxiv`` python package installed.
https://lukasschwab.me... | https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
e7b8f54630a4-1 | 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 document meta information.
"""
try:
docs = [
f"Published: {result.updated.date()}\nTitle: {result.title}\n"
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
b8e80ea7ad51-0 | Source code for langchain.utilities.wikipedia
"""Util that calls Wikipedia."""
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
WIKIPEDIA_MAX_QUERY_LENGTH = 300
[docs]class WikipediaAPIWrapper(BaseModel):
"""Wrapper around WikipediaAPI.
To use, you should have the ``w... | https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
b8e80ea7ad51-1 | summary = self.fetch_formatted_page_summary(search_results[i])
if summary is not None:
summaries.append(summary)
return "\n\n".join(summaries)
[docs] def fetch_formatted_page_summary(self, page: str) -> Optional[str]:
try:
wiki_page = self.wiki_client.page(titl... | https://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
90fbe6992c42-0 | Source code for langchain.utilities.powerbi
"""Wrapper around a Power BI endpoint."""
from __future__ import annotations
import logging
import os
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
import aiohttp
import requests
from aiohttp import ServerTimeoutError
from pydantic import BaseMo... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
90fbe6992c42-1 | class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
@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."""
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
90fbe6992c42-2 | """Get names of tables available."""
return self.table_names
[docs] def get_schemas(self) -> str:
"""Get the available schema's."""
if self.schemas:
return ", ".join([f"{key}: {value}" for key, value in self.schemas.items()])
return "No known schema's yet. Use the schema_p... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
90fbe6992c42-3 | ) -> str:
"""Get information about specified tables."""
tables_requested = self._get_tables_to_query(table_names)
tables_todo = self._get_tables_todo(tables_requested)
for table in tables_todo:
try:
result = self.run(
f"EVALUATE TOPN({self.... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
90fbe6992c42-4 | if "bad request" in str(exc).lower():
return BAD_REQUEST_RESPONSE
if "unauthorized" in str(exc).lower():
return UNAUTHORIZED_RESPONSE
return str(exc)
self.schemas[table] = json_to_md(result["results"][0]["tables"][0]["rows"])
re... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
90fbe6992c42-5 | ) as response:
response.raise_for_status()
response_json = await response.json()
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 a markdown ta... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
7aae1d7a91ff-0 | Source code for langchain.chains.llm
"""Chain that just formats a prompt and calls an LLM."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
from pydantic import Extra
from langchain.chains.base import Chain
from langchain.input import get_colored_text
from langc... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
7aae1d7a91ff-1 | return self.apply([inputs])[0]
[docs] def generate(self, input_list: List[Dict[str, Any]]) -> LLMResult:
"""Generate LLM result from inputs."""
prompts, stop = self.prep_prompts(input_list)
return self.llm.generate_prompt(prompts, stop)
[docs] async def agenerate(self, input_list: List[Dic... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
7aae1d7a91ff-2 | self, input_list: List[Dict[str, Any]]
) -> Tuple[List[PromptValue], Optional[List[str]]]:
"""Prepare prompts from inputs."""
stop = None
if "stop" in input_list[0]:
stop = input_list[0]["stop"]
prompts = []
for inputs in input_list:
selected_inputs = ... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
7aae1d7a91ff-3 | """Create outputs from response."""
return [
# Get the text of the top generated string.
{self.output_key: generation[0].text}
for generation in response.generations
]
async def _acall(self, inputs: Dict[str, Any]) -> Dict[str, str]:
return (await self.aap... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
7aae1d7a91ff-4 | ) -> Union[str, List[str], Dict[str, str]]:
"""Call apredict and then parse the results."""
result = await self.apredict(**kwargs)
if self.prompt.output_parser is not None:
return self.prompt.output_parser.parse(result)
else:
return result
[docs] def apply_and_... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
7aae1d7a91ff-5 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 25, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
c4deb884d8b0-0 | Source code for langchain.chains.sequential
"""Chain pipeline where the outputs of one step feed directly into next."""
from typing import Dict, List
from pydantic import Extra, root_validator
from langchain.chains.base import Chain
from langchain.input import get_color_mapping
[docs]class SequentialChain(Chain):
"... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
c4deb884d8b0-1 | f"in the Memory keys ({memory_keys}) - please use input and "
f"memory keys that don't overlap."
)
known_variables = set(input_variables + memory_keys)
for chain in chains:
missing_vars = set(chain.input_keys).difference(known_variables)
if mis... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
c4deb884d8b0-2 | chains: List[Chain]
strip_outputs: bool = False
input_key: str = "input" #: :meta private:
output_key: str = "output" #: :meta private:
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@property
def input_ke... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
c4deb884d8b0-3 | if self.strip_outputs:
_input = _input.strip()
self.callback_manager.on_text(
_input, color=color_mapping[str(i)], end="\n", verbose=self.verbose
)
return {self.output_key: _input}
By Harrison Chase
© Copyright 2023, Harrison Chase.
Las... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
902c7621310b-0 | Source code for langchain.chains.transform
"""Chain that runs an arbitrary python function."""
from typing import Callable, Dict, List
from langchain.chains.base import Chain
[docs]class TransformChain(Chain):
"""Chain transform chain output.
Example:
.. code-block:: python
from langchain im... | https://python.langchain.com/en/latest/_modules/langchain/chains/transform.html |
8b84f920fd65-0 | Source code for langchain.chains.loading
"""Functionality for loading chains."""
import json
from pathlib import Path
from typing import Any, Union
import yaml
from langchain.chains.api.base import APIChain
from langchain.chains.base import Chain
from langchain.chains.combine_documents.map_reduce import MapReduceDocume... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-1 | """Load LLM chain from config dict."""
if "llm" in config:
llm_config = config.pop("llm")
llm = load_llm_from_config(llm_config)
elif "llm_path" in config:
llm = load_llm(config.pop("llm_path"))
else:
raise ValueError("One of `llm` or `llm_path` must be present.")
if "pro... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-2 | llm_chain=llm_chain, base_embeddings=embeddings, **config
)
def _load_stuff_documents_chain(config: dict, **kwargs: Any) -> StuffDocumentsChain:
if "llm_chain" in config:
llm_chain_config = config.pop("llm_chain")
llm_chain = load_chain_from_config(llm_chain_config)
elif "llm_chain_path" in ... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-3 | llm_chain = load_chain(config.pop("llm_chain_path"))
else:
raise ValueError("One of `llm_chain` or `llm_chain_config` must be present.")
if not isinstance(llm_chain, LLMChain):
raise ValueError(f"Expected LLMChain, got {llm_chain}")
if "combine_document_chain" in config:
combine_docu... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-4 | elif "llm_path" in config:
llm = load_llm(config.pop("llm_path"))
else:
raise ValueError("One of `llm` or `llm_path` must be present.")
if "prompt" in config:
prompt_config = config.pop("prompt")
prompt = load_prompt_from_config(prompt_config)
elif "prompt_path" in config:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-5 | list_assertions_prompt = load_prompt(config.pop("list_assertions_prompt_path"))
if "check_assertions_prompt" in config:
check_assertions_prompt_config = config.pop("check_assertions_prompt")
check_assertions_prompt = load_prompt_from_config(
check_assertions_prompt_config
)
e... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-6 | prompt = load_prompt_from_config(prompt_config)
elif "prompt_path" in config:
prompt = load_prompt(config.pop("prompt_path"))
return LLMMathChain(llm=llm, prompt=prompt, **config)
def _load_map_rerank_documents_chain(
config: dict, **kwargs: Any
) -> MapRerankDocumentsChain:
if "llm_chain" in co... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-7 | return PALChain(llm=llm, prompt=prompt, **config)
def _load_refine_documents_chain(config: dict, **kwargs: Any) -> RefineDocumentsChain:
if "initial_llm_chain" in config:
initial_llm_chain_config = config.pop("initial_llm_chain")
initial_llm_chain = load_chain_from_config(initial_llm_chain_config)
... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-8 | if "combine_documents_chain" in config:
combine_documents_chain_config = config.pop("combine_documents_chain")
combine_documents_chain = load_chain_from_config(combine_documents_chain_config)
elif "combine_documents_chain_path" in config:
combine_documents_chain = load_chain(config.pop("comb... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-9 | if "combine_documents_chain" in config:
combine_documents_chain_config = config.pop("combine_documents_chain")
combine_documents_chain = load_chain_from_config(combine_documents_chain_config)
elif "combine_documents_chain_path" in config:
combine_documents_chain = load_chain(config.pop("comb... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-10 | api_request_chain = load_chain_from_config(api_request_chain_config)
elif "api_request_chain_path" in config:
api_request_chain = load_chain(config.pop("api_request_chain_path"))
else:
raise ValueError(
"One of `api_request_chain` or `api_request_chain_path` must be present."
... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-11 | if "requests_wrapper" in kwargs:
requests_wrapper = kwargs.pop("requests_wrapper")
return LLMRequestsChain(
llm_chain=llm_chain, requests_wrapper=requests_wrapper, **config
)
else:
return LLMRequestsChain(llm_chain=llm_chain, **config)
type_to_loader_dict = {
"api_cha... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-12 | if config_type not in type_to_loader_dict:
raise ValueError(f"Loading {config_type} chain not supported")
chain_loader = type_to_loader_dict[config_type]
return chain_loader(config, **kwargs)
[docs]def load_chain(path: Union[str, Path], **kwargs: Any) -> Chain:
"""Unified method for loading a chain ... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
8b84f920fd65-13 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 25, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
3d76e78cb830-0 | Source code for langchain.chains.llm_requests
"""Chain that hits a URL and then uses an LLM to parse results."""
from __future__ import annotations
from typing import Dict, List
from pydantic import Extra, Field, root_validator
from langchain.chains import LLMChain
from langchain.chains.base import Chain
from langchain... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
3d76e78cb830-1 | """
return [self.output_key]
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
try:
from bs4 import BeautifulSoup # noqa: F401
except ImportError:
raise ValueError(... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
1634108e904f-0 | Source code for langchain.chains.moderation
"""Pass input through a moderation endpoint."""
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.chains.base import Chain
from langchain.utils import get_from_dict_or_env
[docs]class OpenAIModerationChain(Chain):
"""Pass inpu... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
1634108e904f-1 | "OPENAI_ORGANIZATION",
default="",
)
try:
import openai
openai.api_key = openai_api_key
if openai_organization:
openai.organization = openai_organization
values["client"] = openai.Moderation
except ImportError:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
3443a13eca32-0 | Source code for langchain.chains.mapreduce
"""Map-reduce chain.
Splits up a document, sends the smaller parts to the LLM with one prompt,
then combines the results with another one.
"""
from __future__ import annotations
from typing import Dict, List
from pydantic import Extra
from langchain.chains.base import Chain
fr... | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
3443a13eca32-1 | )
return cls(
combine_documents_chain=combine_documents_chain, text_splitter=text_splitter
)
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@property
def input_keys(self) -> List[str]:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
9467364d8485-0 | Source code for langchain.chains.llm_summarization_checker.base
"""Chain for summarization with self-verification."""
from pathlib import Path
from typing import Dict, List
from pydantic import Extra
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.chains.sequential impor... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html |
9467364d8485-1 | revised_summary_prompt: PromptTemplate = REVISED_SUMMARY_PROMPT
are_all_true_prompt: PromptTemplate = ARE_ALL_TRUE_PROMPT
input_key: str = "query" #: :meta private:
output_key: str = "result" #: :meta private:
max_checks: int = 2
"""Maximum number of times to check the assertions. Default to doubl... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html |
9467364d8485-2 | output_key="revised_summary",
verbose=self.verbose,
),
LLMChain(
llm=self.llm,
output_key="all_true",
prompt=self.are_all_true_prompt,
verbose=self.verbose,
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_summarization_checker/base.html |
0f7775e3f4b7-0 | Source code for langchain.chains.hyde.base
"""Hypothetical Document Embeddings.
https://arxiv.org/abs/2212.10496
"""
from __future__ import annotations
from typing import Dict, List
import numpy as np
from pydantic import Extra
from langchain.chains.base import Chain
from langchain.chains.hyde.prompts import PROMPT_MAP... | https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html |
0f7775e3f4b7-1 | """Generate a hypothetical document and embedded it."""
var_name = self.llm_chain.input_keys[0]
result = self.llm_chain.generate([{var_name: text}])
documents = [generation.text for generation in result.generations[0]]
embeddings = self.embed_documents(documents)
return self.comb... | https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html |
d50ffdbfd046-0 | Source code for langchain.chains.graph_qa.base
"""Question answering over a graph."""
from __future__ import annotations
from typing import Any, Dict, List
from pydantic import Field
from langchain.chains.base import Chain
from langchain.chains.graph_qa.prompts import ENTITY_EXTRACTION_PROMPT, PROMPT
from langchain.cha... | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html |
d50ffdbfd046-1 | qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
entity_chain = LLMChain(llm=llm, prompt=entity_prompt)
return cls(qa_chain=qa_chain, entity_extraction_chain=entity_chain, **kwargs)
def _call(self, inputs: Dict[str, str]) -> Dict[str, Any]:
"""Extract entities, look up info and answer question... | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html |
4f649a0dd29b-0 | Source code for langchain.chains.qa_generation.base
from __future__ import annotations
import json
from typing import Any, Dict, List, Optional
from pydantic import Field
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.chains.qa_generation.prompt import PROMPT_SELECTOR
f... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html |
4f649a0dd29b-1 | docs = self.text_splitter.create_documents([inputs[self.input_key]])
results = self.llm_chain.generate([{"text": d.page_content} for d in docs])
qa = [json.loads(res[0].text) for res in results.generations]
return {self.output_key: qa}
async def _acall(self, inputs: Dict[str, str]) -> Dict[s... | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html |
ce4b71509362-0 | Source code for langchain.chains.retrieval_qa.base
"""Chain for question-answering against a vector database."""
from __future__ import annotations
import warnings
from abc import abstractmethod
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.chains.base imp... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
ce4b71509362-1 | _output_keys = [self.output_key]
if self.return_source_documents:
_output_keys = _output_keys + ["source_documents"]
return _output_keys
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
prompt: Optional[PromptTemplate] = None,
**kwargs: Any,
... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
ce4b71509362-2 | def _call(self, inputs: Dict[str, str]) -> Dict[str, Any]:
"""Run get_relevant_text and llm on input query.
If chain has 'return_source_documents' as 'True', returns
the retrieved documents as well under the key 'source_documents'.
Example:
.. code-block:: python
res = in... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
ce4b71509362-3 | return {self.output_key: answer, "source_documents": docs}
else:
return {self.output_key: answer}
[docs]class RetrievalQA(BaseRetrievalQA):
"""Chain for question-answering against an index.
Example:
.. code-block:: python
from langchain.llms import OpenAI
from... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
ce4b71509362-4 | warnings.warn(
"`VectorDBQA` is deprecated - "
"please use `from langchain.chains import RetrievalQA`"
)
return values
@root_validator()
def validate_search_type(cls, values: Dict) -> Dict:
"""Validate search type."""
if "search_type" in values:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
75e6aa978a0b-0 | Source code for langchain.chains.api.base
"""Chain that makes API calls and summarizes the responses to answer a question."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Field, root_validator
from langchain.chains.api.prompt import API_RESPONSE_PROMPT, API_URL_PR... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
75e6aa978a0b-1 | )
return values
@root_validator(pre=True)
def validate_api_answer_prompt(cls, values: Dict) -> Dict:
"""Check that api answer prompt expects the right variables."""
input_vars = values["api_answer_chain"].prompt.input_variables
expected_vars = {"question", "api_docs", "api_url", ... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
75e6aa978a0b-2 | self.callback_manager.on_text(
api_response, color="yellow", end="\n", verbose=self.verbose
)
answer = await self.api_answer_chain.apredict(
question=question,
api_docs=self.api_docs,
api_url=api_url,
api_response=api_response,
)
... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
dfb66c88271a-0 | Source code for langchain.chains.api.openapi.chain
"""Chain that makes API calls and summarizes the responses to answer a question."""
from __future__ import annotations
import json
from typing import Any, Dict, List, NamedTuple, Optional, cast
from pydantic import BaseModel, Field
from requests import Response
from la... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
dfb66c88271a-1 | @property
def output_keys(self) -> List[str]:
"""Expect output key.
:meta private:
"""
if not self.return_intermediate_steps:
return [self.output_key]
else:
return [self.output_key, "intermediate_steps"]
def _construct_path(self, args: Dict[str, st... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
dfb66c88271a-2 | body_params = self._extract_body_params(args)
query_params = self._extract_query_params(args)
return {
"url": path,
"data": body_params,
"params": query_params,
}
def _get_output(self, output: str, intermediate_steps: dict) -> dict:
"""Return the o... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
dfb66c88271a-3 | response_text = (
f"{api_response.status_code}: {api_response.reason}"
+ f"\nFor {method_str.upper()} {request_args['url']}\n"
+ f"Called with args: {request_args['params']}"
)
else:
response_text = api_response.tex... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
dfb66c88271a-4 | operation,
requests=requests,
llm=llm,
return_intermediate_steps=return_intermediate_steps,
**kwargs,
)
[docs] @classmethod
def from_api_operation(
cls,
operation: APIOperation,
llm: BaseLLM,
requests: Optional[Requests] = No... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
440fc7a1e7cd-0 | Source code for langchain.chains.llm_checker.base
"""Chain for question-answering with self-verification."""
from typing import Dict, List
from pydantic import Extra
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.chains.llm_checker.prompt import (
CHECK_ASSERTIONS_P... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html |
440fc7a1e7cd-1 | def input_keys(self) -> List[str]:
"""Return the singular input key.
:meta private:
"""
return [self.input_key]
@property
def output_keys(self) -> List[str]:
"""Return the singular output key.
:meta private:
"""
return [self.output_key]
def _ca... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html |
440fc7a1e7cd-2 | return "llm_checker_chain"
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 25, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_checker/base.html |
92a2e7a9d43a-0 | Source code for langchain.chains.conversational_retrieval.base
"""Chain for chatting with a vector database."""
from __future__ import annotations
import warnings
from abc import abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from pydantic import Extra, Fiel... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
92a2e7a9d43a-1 | buffer += "\n" + "\n".join([human, ai])
else:
raise ValueError(
f"Unsupported chat history format: {type(dialogue_turn)}."
f" Full chat history: {chat_history} "
)
return buffer
class BaseConversationalRetrievalChain(Chain):
"""Chain for chatting w... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
92a2e7a9d43a-2 | if chat_history_str:
new_question = self.question_generator.run(
question=question, chat_history=chat_history_str
)
else:
new_question = question
docs = self._get_docs(new_question, inputs)
new_inputs = inputs.copy()
new_inputs["questio... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
92a2e7a9d43a-3 | def save(self, file_path: Union[Path, str]) -> None:
if self.get_chat_history:
raise ValueError("Chain not savable when `get_chat_history` is not None.")
super().save(file_path)
[docs]class ConversationalRetrievalChain(BaseConversationalRetrievalChain):
"""Chain for chatting with an inde... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
92a2e7a9d43a-4 | def from_llm(
cls,
llm: BaseLanguageModel,
retriever: BaseRetriever,
condense_question_prompt: BasePromptTemplate = CONDENSE_QUESTION_PROMPT,
chain_type: str = "stuff",
verbose: bool = False,
combine_docs_chain_kwargs: Optional[Dict] = None,
**kwargs: Any,... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
92a2e7a9d43a-5 | )
return values
def _get_docs(self, question: str, inputs: Dict[str, Any]) -> List[Document]:
vectordbkwargs = inputs.get("vectordbkwargs", {})
full_kwargs = {**self.search_kwargs, **vectordbkwargs}
return self.vectorstore.similarity_search(
question, k=self.top_k_docs_fo... | https://python.langchain.com/en/latest/_modules/langchain/chains/conversational_retrieval/base.html |
58f580e05f30-0 | Source code for langchain.chains.combine_documents.base
"""Base interface for chains combining documents."""
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Tuple
from pydantic import Field
from langchain.chains.base import Chain
from langchain.docstore.document import Document
from la... | https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html |
58f580e05f30-1 | """Return output key.
:meta private:
"""
return [self.output_key]
def prompt_length(self, docs: List[Document], **kwargs: Any) -> Optional[int]:
"""Return the prompt length given the documents passed in.
Returns None if the method does not depend on the prompt length.
... | https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html |
58f580e05f30-2 | """Chain that splits documents, then analyzes it in pieces."""
input_key: str = "input_document" #: :meta private:
text_splitter: TextSplitter = Field(default_factory=RecursiveCharacterTextSplitter)
combine_docs_chain: BaseCombineDocumentsChain
@property
def input_keys(self) -> List[str]:
"... | https://python.langchain.com/en/latest/_modules/langchain/chains/combine_documents/base.html |
de80aeed33f8-0 | Source code for langchain.chains.constitutional_ai.base
"""Chain for applying constitutional principles to the outputs of another chain."""
from typing import Any, Dict, List, Optional
from langchain.chains.base import Chain
from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple
from langchain.ch... | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
de80aeed33f8-1 | ) -> List[ConstitutionalPrinciple]:
if names is None:
return list(PRINCIPLES.values())
else:
return [PRINCIPLES[name] for name in names]
[docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
chain: LLMChain,
critique_prompt: BasePro... | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
de80aeed33f8-2 | input_prompt=input_prompt,
output_from_model=response,
critique_request=constitutional_principle.critique_request,
)
critique = self._parse_critique(
output_string=raw_critique,
).strip()
# Do revision
revision =... | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
0aee63e7f654-0 | Source code for langchain.chains.llm_math.base
"""Chain that interprets a prompt and executes python code to do math."""
import math
import re
from typing import Dict, List
import numexpr
from pydantic import Extra
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.chains.l... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
0aee63e7f654-1 | try:
local_dict = {"pi": math.pi, "e": math.e}
output = str(
numexpr.evaluate(
expression.strip(),
global_dict={}, # restrict access to globals
local_dict=local_dict, # add common mathematical functions
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
0aee63e7f654-2 | llm_output, color="green", verbose=self.verbose
)
else:
self.callback_manager.on_text(
llm_output, color="green", verbose=self.verbose
)
llm_output = llm_output.strip()
text_match = re.search(r"^```text(.*?)```", llm_output, re.DOTALL)
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
0aee63e7f654-3 | )
return self._process_llm_result(llm_output)
async def _acall(self, inputs: Dict[str, str]) -> Dict[str, str]:
llm_executor = LLMChain(
prompt=self.prompt, llm=self.llm, callback_manager=self.callback_manager
)
if self.callback_manager.is_async:
await self.ca... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
2f76397f83c5-0 | Source code for langchain.chains.llm_bash.base
"""Chain that interprets a prompt and executes bash code to perform bash operations."""
from typing import Dict, List
from pydantic import Extra
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.chains.llm_bash.prompt import P... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html |
2f76397f83c5-1 | bash_executor = BashProcess()
self.callback_manager.on_text(inputs[self.input_key], verbose=self.verbose)
t = llm_executor.predict(question=inputs[self.input_key])
self.callback_manager.on_text(t, color="green", verbose=self.verbose)
t = t.strip()
if t.startswith("```bash"):
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_bash/base.html |
43a4bce2b6b7-0 | Source code for langchain.chains.sql_database.base
"""Chain for interacting with SQL Database."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.chains.sql_... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
43a4bce2b6b7-1 | extra = Extra.forbid
arbitrary_types_allowed = True
@property
def input_keys(self) -> List[str]:
"""Return the singular input key.
:meta private:
"""
return [self.input_key]
@property
def output_keys(self) -> List[str]:
"""Return the singular output key.
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
43a4bce2b6b7-2 | self.callback_manager.on_text("\nSQLResult: ", verbose=self.verbose)
self.callback_manager.on_text(result, color="yellow", verbose=self.verbose)
# If return direct, we just set the final result equal to the sql query
if self.return_direct:
final_result = result
else:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
43a4bce2b6b7-3 | **kwargs: Any,
) -> SQLDatabaseSequentialChain:
"""Load the necessary chains."""
sql_chain = SQLDatabaseChain(
llm=llm, database=database, prompt=query_prompt, **kwargs
)
decider_chain = LLMChain(
llm=llm, prompt=decider_prompt, output_key="table_names"
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.