id stringlengths 14 16 | source stringlengths 49 117 | text stringlengths 16 2.73k |
|---|---|---|
6070efcd4f4f-4 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | """Configuration for this pydantic object."""
extra = Extra.ignore
allow_population_by_field_name = True
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra kwargs from additional params that were passed in."""
all_required_fie... |
6070efcd4f4f-5 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | "openai_proxy",
"OPENAI_PROXY",
default="",
)
openai_organization = get_from_dict_or_env(
values,
"openai_organization",
"OPENAI_ORGANIZATION",
default="",
)
try:
import openai
openai.api_key ... |
6070efcd4f4f-6 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | # Azure gpt-35-turbo doesn't support best_of
# don't specify best_of if it is 1
if self.best_of > 1:
normal_params["best_of"] = self.best_of
return {**normal_params, **self.model_kwargs}
def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = ... |
6070efcd4f4f-7 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | stream_resp["choices"][0]["text"],
verbose=self.verbose,
logprobs=stream_resp["choices"][0]["logprobs"],
)
_update_response(response, stream_resp)
choices.extend(response["choices"])
else:
... |
6070efcd4f4f-8 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | verbose=self.verbose,
logprobs=stream_resp["choices"][0]["logprobs"],
)
_update_response(response, stream_resp)
choices.extend(response["choices"])
else:
response = await acompletion_with_retry(self, prom... |
6070efcd4f4f-9 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | sub_choices = choices[i * self.n : (i + 1) * self.n]
generations.append(
[
Generation(
text=choice["text"],
generation_info=dict(
finish_reason=choice.get("finish_reason"),
... |
6070efcd4f4f-10 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
params["stream"] = True
return params
@property
def _invocation_params(self) -> Dict[str, Any]:
"""Get the parameters used to invoke the model."""... |
6070efcd4f4f-11 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | Example:
.. code-block:: python
max_tokens = openai.modelname_to_contextsize("text-davinci-003")
"""
model_token_mapping = {
"gpt-4": 8192,
"gpt-4-0314": 8192,
"gpt-4-32k": 32768,
"gpt-4-32k-0314": 32768,
"gpt-3.5-tu... |
6070efcd4f4f-12 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | return context_size
def max_tokens_for_prompt(self, prompt: str) -> int:
"""Calculate the maximum number of tokens possible to generate for a prompt.
Args:
prompt: The prompt to pass into the model.
Returns:
The maximum number of tokens to generate for a prompt.
... |
6070efcd4f4f-13 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | in, even if not explicitly saved on this class.
Example:
.. code-block:: python
from langchain.llms import AzureOpenAI
openai = AzureOpenAI(model_name="text-davinci-003")
"""
deployment_name: str = ""
"""Deployment name to use."""
@property
def _identifying_params... |
6070efcd4f4f-14 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | openai_api_key: Optional[str] = None
openai_api_base: Optional[str] = None
# to support explicit proxy for OpenAI
openai_proxy: Optional[str] = None
max_retries: int = 6
"""Maximum number of retries to make when generating."""
prefix_messages: List = Field(default_factory=list)
"""Series of ... |
6070efcd4f4f-15 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | openai_api_base = get_from_dict_or_env(
values,
"openai_api_base",
"OPENAI_API_BASE",
default="",
)
openai_proxy = get_from_dict_or_env(
values,
"openai_proxy",
"OPENAI_PROXY",
default="",
)
o... |
6070efcd4f4f-16 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | """Get the default parameters for calling OpenAI API."""
return self.model_kwargs
def _get_chat_params(
self, prompts: List[str], stop: Optional[List[str]] = None
) -> Tuple:
if len(prompts) > 1:
raise ValueError(
f"OpenAIChat currently only supports single pr... |
6070efcd4f4f-17 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | full_response = completion_with_retry(self, messages=messages, **params)
llm_output = {
"token_usage": full_response["usage"],
"model_name": self.model_name,
}
return LLMResult(
generations=[
[Generation(text=full_re... |
6070efcd4f4f-18 | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html | """Get the identifying parameters."""
return {**{"model_name": self.model_name}, **self._default_params}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "openai-chat"
[docs] def get_token_ids(self, text: str) -> List[int]:
"""Get the token IDs using the ... |
6e16a6cab9c4-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html | Source code for langchain.llms.huggingface_endpoint
"""Wrapper around HuggingFace APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.... |
6e16a6cab9c4-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html | """Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
huggingfacehub_api_token = get_from_dict_or_env(
values, "huggingfac... |
6e16a6cab9c4-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html | run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated ... |
6e16a6cab9c4-3 | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html | f"currently only {VALID_TASKS} are supported"
)
if stop is not None:
# This is a bit hacky, but I can't figure out a better way to enforce
# stop tokens when making calls to huggingface_hub.
text = enforce_stop_tokens(text, stop)
return text
By Harrison Ch... |
b8d377507a32-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/openlm.html | Source code for langchain.llms.openlm
from typing import Any, Dict
from pydantic import root_validator
from langchain.llms.openai import BaseOpenAI
[docs]class OpenLM(BaseOpenAI):
@property
def _invocation_params(self) -> Dict[str, Any]:
return {**{"model": self.model_name}, **super()._invocation_params... |
581ef04eec57-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html | Source code for langchain.llms.rwkv
"""Wrapper for the RWKV model.
Based on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py
https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py
"""
from typing import Any, Dict, List, Mapping, Optional, Set
from pydantic import BaseModel, Extra, roo... |
581ef04eec57-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html | in the text so far, decreasing the model's likelihood to repeat the same
line verbatim.."""
penalty_alpha_presence: float = 0.4
"""Positive values penalize new tokens based on whether they appear
in the text so far, increasing the model's likelihood to talk about
new topics.."""
CHUNK_LEN: int =... |
581ef04eec57-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html | raise ImportError(
"Could not import tokenizers python package. "
"Please install it with `pip install tokenizers`."
)
try:
from rwkv.model import RWKV as RWKVMODEL
from rwkv.utils import PIPELINE
values["tokenizer"] = tokenizers.To... |
581ef04eec57-3 | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html | assert len(dd) == 1
AVOID_REPEAT_TOKENS += dd
tokens = [int(x) for x in _tokens]
self.model_tokens += tokens
out: Any = None
while len(tokens) > 0:
out, self.model_state = self.client.forward(
tokens[: self.CHUNK_LEN], self.model_state
... |
581ef04eec57-4 | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html | out_last = begin + i + 1
if i >= self.max_tokens_per_generation - 100:
break
return decoded
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
r"""RW... |
c561f10f0b2c-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html | Source code for langchain.llms.replicate
"""Wrapper around Replicate API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.utils im... |
c561f10f0b2c-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html | all_required_field_names = {field.alias for field in cls.__fields__.values()}
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if field_name in extra:
raise ValueError(f"Found {field_name... |
c561f10f0b2c-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html | # get the model and version
model_str, version_str = self.model.split(":")
model = replicate_python.models.get(model_str)
version = model.versions.get(version_str)
# sort through the openapi schema to get the name of the first input
input_properties = sorted(
version.... |
a569ef08b4f3-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html | 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 Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForChainRun
from langc... |
a569ef08b4f3-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html | @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(
"Could not import bs4 py... |
f8fb06dc52ce-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/transform.html | Source code for langchain.chains.transform
"""Chain that runs an arbitrary python function."""
from typing import Callable, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
[docs]class TransformChain(Chain):
"""Chain transform chain outp... |
5b9fd6752198-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html | 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 Any, Dict, List, Mapping, Optional
from pydantic import Extra
from langchain.bas... |
5b9fd6752198-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html | """Construct a map-reduce chain that uses the chain for map and reduce."""
llm_chain = LLMChain(llm=llm, prompt=prompt, callbacks=callbacks)
reduce_chain = StuffDocumentsChain(
llm_chain=llm_chain,
callbacks=callbacks,
**(reduce_chain_kwargs if reduce_chain_kwargs els... |
5b9fd6752198-2 | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html | _inputs: Dict[str, Any] = {
**inputs,
self.combine_documents_chain.input_key: docs,
}
outputs = self.combine_documents_chain.run(
_inputs, callbacks=_run_manager.get_child()
)
return {self.output_key: outputs}
By Harrison Chase
© Copyright 2... |
dce4eddb28e4-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html | 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.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
from langchain.utils import get_from_dic... |
dce4eddb28e4-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html | "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:
... |
a06008ef24a7-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html | Source code for langchain.chains.sequential
"""Chain pipeline where the outputs of one step feed directly into next."""
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)... |
a06008ef24a7-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html | f"The the input key(s) {''.join(overlapping_keys)} are found "
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:
... |
a06008ef24a7-2 | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html | known_values.update(outputs)
return {k: known_values[k] for k in self.output_variables}
async def _acall(
self,
inputs: Dict[str, Any],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
known_values = inputs.copy()
_run_manager = ... |
a06008ef24a7-3 | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html | if len(chain.input_keys) != 1:
raise ValueError(
"Chains used in SimplePipeline should all have one input, got "
f"{chain} with {len(chain.input_keys)} inputs."
)
if len(chain.output_keys) != 1:
raise ValueError(
... |
a06008ef24a7-4 | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html | for i, chain in enumerate(self.chains):
_input = await chain.arun(_input, callbacks=callbacks)
if self.strip_outputs:
_input = _input.strip()
await _run_manager.on_text(
_input, color=color_mapping[str(i)], end="\n", verbose=self.verbose
)
... |
4ff093bb742a-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html | 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.base_language import BaseLanguageModel
from langchain.callbacks.manager import (... |
4ff093bb742a-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html | :meta private:
"""
return [self.output_key]
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, str]:
response = self.generate([inputs], run_manager=run_manager)
return self.create_outputs(respo... |
4ff093bb742a-2 | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html | stop = input_list[0]["stop"]
prompts = []
for inputs in input_list:
selected_inputs = {k: inputs[k] for k in self.prompt.input_variables}
prompt = self.prompt.format_prompt(**selected_inputs)
_colored_text = get_colored_text(prompt.to_string(), "green")
_t... |
4ff093bb742a-3 | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html | "If `stop` is present in any inputs, should be present in all."
)
prompts.append(prompt)
return prompts, stop
[docs] def apply(
self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None
) -> List[Dict[str, str]]:
"""Utilize the LLM generate method for... |
4ff093bb742a-4 | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html | [docs] def create_outputs(self, response: LLMResult) -> List[Dict[str, str]]:
"""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 d... |
4ff093bb742a-5 | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html | self, callbacks: Callbacks = None, **kwargs: Any
) -> Union[str, List[str], Dict[str, Any]]:
"""Call predict and then parse the results."""
result = self.predict(callbacks=callbacks, **kwargs)
if self.prompt.output_parser is not None:
return self.prompt.output_parser.parse(result... |
4ff093bb742a-6 | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html | """Call apply and then parse the results."""
result = await self.aapply(input_list, callbacks=callbacks)
return self._parse_result(result)
@property
def _chain_type(self) -> str:
return "llm_chain"
[docs] @classmethod
def from_string(cls, llm: BaseLanguageModel, template: str) -> ... |
5be7a8616a81-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | 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... |
5be7a8616a81-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | 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 "prompt" in config:
prompt_config = config.pop("prompt")
pr... |
5be7a8616a81-2 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | 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 config:
llm_chain = load_chain(config.pop("llm_chain_path"))
else:
raise ValueError("One of `llm_chain` or `llm_chain_config` must be... |
5be7a8616a81-3 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | if "combine_document_chain" in config:
combine_document_chain_config = config.pop("combine_document_chain")
combine_document_chain = load_chain_from_config(combine_document_chain_config)
elif "combine_document_chain_path" in config:
combine_document_chain = load_chain(config.pop("combine_doc... |
5be7a8616a81-4 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | # llm_path attribute is deprecated in favor of llm_chain_path,
# its to support old configs
elif "llm_path" in config:
llm = load_llm(config.pop("llm_path"))
else:
raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.")
if "prompt" in config:
prompt_config = c... |
5be7a8616a81-5 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | list_assertions_prompt_config = config.pop("list_assertions_prompt")
list_assertions_prompt = load_prompt_from_config(list_assertions_prompt_config)
elif "list_assertions_prompt_path" in config:
list_assertions_prompt = load_prompt(config.pop("list_assertions_prompt_path"))
if "check_assertions_... |
5be7a8616a81-6 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | # llm attribute is deprecated in favor of llm_chain, here to support old configs
elif "llm" in config:
llm_config = config.pop("llm")
llm = load_llm_from_config(llm_config)
# llm_path attribute is deprecated in favor of llm_chain_path,
# its to support old configs
elif "llm_path" in conf... |
5be7a8616a81-7 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | def _load_pal_chain(config: dict, **kwargs: Any) -> PALChain:
llm_chain = None
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 config:
llm_chain = load_chain(config.pop("llm_chain_path"... |
5be7a8616a81-8 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | initial_llm_chain_config = config.pop("initial_llm_chain")
initial_llm_chain = load_chain_from_config(initial_llm_chain_config)
elif "initial_llm_chain_path" in config:
initial_llm_chain = load_chain(config.pop("initial_llm_chain_path"))
else:
raise ValueError(
"One of `initi... |
5be7a8616a81-9 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | combine_documents_chain = load_chain(config.pop("combine_documents_chain_path"))
else:
raise ValueError(
"One of `combine_documents_chain` or "
"`combine_documents_chain_path` must be present."
)
return QAWithSourcesChain(combine_documents_chain=combine_documents_chain, *... |
5be7a8616a81-10 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | combine_documents_chain = load_chain(config.pop("combine_documents_chain_path"))
else:
raise ValueError(
"One of `combine_documents_chain` or "
"`combine_documents_chain_path` must be present."
)
return VectorDBQAWithSourcesChain(
combine_documents_chain=combine_d... |
5be7a8616a81-11 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | "One of `api_request_chain` or `api_request_chain_path` must be present."
)
if "api_answer_chain" in config:
api_answer_chain_config = config.pop("api_answer_chain")
api_answer_chain = load_chain_from_config(api_answer_chain_config)
elif "api_answer_chain_path" in config:
api_ans... |
5be7a8616a81-12 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | type_to_loader_dict = {
"api_chain": _load_api_chain,
"hyde_chain": _load_hyde_chain,
"llm_chain": _load_llm_chain,
"llm_bash_chain": _load_llm_bash_chain,
"llm_checker_chain": _load_llm_checker_chain,
"llm_math_chain": _load_llm_math_chain,
"llm_requests_chain": _load_llm_requests_chain,
... |
5be7a8616a81-13 | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html | if hub_result := try_load_from_hub(
path, _load_chain_from_file, "chains", {"json", "yaml"}, **kwargs
):
return hub_result
else:
return _load_chain_from_file(path, **kwargs)
def _load_chain_from_file(file: Union[str, Path], **kwargs: Any) -> Chain:
"""Load chain from file."""
# C... |
f2b5ac5d22fe-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html | Source code for langchain.chains.hyde.base
"""Hypothetical Document Embeddings.
https://arxiv.org/abs/2212.10496
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
import numpy as np
from pydantic import Extra
from langchain.base_language import BaseLanguageModel
from langchain.callback... |
f2b5ac5d22fe-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html | [docs] def embed_query(self, text: str) -> List[float]:
"""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]]
em... |
c2da53f61cbb-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html | Source code for langchain.chains.sql_database.base
"""Chain for interacting with SQL Database."""
from __future__ import annotations
import warnings
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.base_language import BaseLanguageModel
from langchain.callbac... |
c2da53f61cbb-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html | """Whether or not to return the intermediate steps along with the final answer."""
return_direct: bool = False
"""Whether or not to return the result of querying the SQL table directly."""
use_query_checker: bool = False
"""Whether or not the query checker tool should be used to attempt
to fix the ... |
c2da53f61cbb-2 | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html | return [self.output_key, INTERMEDIATE_STEPS_KEY]
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
input_text = f"{inputs[self... |
c2da53f61cbb-3 | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html | template=QUERY_CHECKER, input_variables=["query", "dialect"]
)
query_checker_chain = LLMChain(
llm=self.llm_chain.llm, prompt=query_checker_prompt
)
query_checker_inputs = {
"query": sql_cmd,
"dia... |
c2da53f61cbb-4 | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html | intermediate_steps.append(final_result) # output: final answer
_run_manager.on_text(final_result, color="green", verbose=self.verbose)
chain_result: Dict[str, Any] = {self.output_key: final_result}
if self.return_intermediate_steps:
chain_result[INTERMEDIATE_STEP... |
c2da53f61cbb-5 | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html | output_key: str = "result" #: :meta private:
return_intermediate_steps: bool = False
[docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
database: SQLDatabase,
query_prompt: BasePromptTemplate = PROMPT,
decider_prompt: BasePromptTemplate = DECIDER_PROMPT,
... |
c2da53f61cbb-6 | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html | llm_inputs = {
"query": inputs[self.input_key],
"table_names": table_names,
}
_lowercased_table_names = [name.lower() for name in _table_names]
table_names_from_chain = self.decider_chain.predict_and_parse(**llm_inputs)
table_names_to_use = [
name
... |
ac4d5a84edaa-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html | 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.base_language i... |
ac4d5a84edaa-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html | :meta private:
"""
_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]... |
ac4d5a84edaa-2 | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html | inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> 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'.
... |
ac4d5a84edaa-3 | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html | _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()
question = inputs[self.input_key]
docs = await self._aget_docs(question)
answer = await self.combine_documents_chain.arun(
input_documents=docs, question=question, callbacks=_run_manager.get_child()
... |
ac4d5a84edaa-4 | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html | """Search type to use over vectorstore. `similarity` or `mmr`."""
search_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Extra search args."""
@root_validator()
def raise_deprecation(cls, values: Dict) -> Dict:
warnings.warn(
"`VectorDBQA` is deprecated - "
"pleas... |
ac4d5a84edaa-5 | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html | Last updated on Jun 04, 2023. |
6371c384703f-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html | Source code for langchain.chains.pal.base
"""Implements Program-Aided Language Models.
As in https://arxiv.org/pdf/2211.10435.pdf.
"""
from __future__ import annotations
import warnings
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.base_language import BaseLangua... |
6371c384703f-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html | "Please instantiate with llm_chain argument or using the one of "
"the class method constructors from_math_prompt, "
"from_colored_object_prompt."
)
if "llm_chain" not in values and values["llm"] is not None:
values["llm_chain"] = LLMChain(llm=valu... |
6371c384703f-2 | https://python.langchain.com/en/latest/_modules/langchain/chains/pal/base.html | def from_math_prompt(cls, llm: BaseLanguageModel, **kwargs: Any) -> PALChain:
"""Load PAL from math prompt."""
llm_chain = LLMChain(llm=llm, prompt=MATH_PROMPT)
return cls(
llm_chain=llm_chain,
stop="\n\n",
get_answer_expr="print(solution())",
**kw... |
841ffcf5fcbd-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/retrieval.html | Source code for langchain.chains.qa_with_sources.retrieval
"""Question-answering with sources over an index."""
from typing import Any, Dict, List
from pydantic import Field
from langchain.chains.combine_documents.stuff import StuffDocumentsChain
from langchain.chains.qa_with_sources.base import BaseQAWithSourcesChain
... |
841ffcf5fcbd-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/retrieval.html | return self._reduce_tokens_below_limit(docs)
async def _aget_docs(self, inputs: Dict[str, Any]) -> List[Document]:
question = inputs[self.question_key]
docs = await self.retriever.aget_relevant_documents(question)
return self._reduce_tokens_below_limit(docs)
By Harrison Chase
© Co... |
931a49bdbac1-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html | Source code for langchain.chains.qa_with_sources.base
"""Question answering with sources over documents."""
from __future__ import annotations
import re
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.base_language import BaseLan... |
931a49bdbac1-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html | question_prompt: BasePromptTemplate = QUESTION_PROMPT,
combine_prompt: BasePromptTemplate = COMBINE_PROMPT,
**kwargs: Any,
) -> BaseQAWithSourcesChain:
"""Construct the chain from an LLM."""
llm_question_chain = LLMChain(llm=llm, prompt=question_prompt)
llm_combine_chain = LL... |
931a49bdbac1-2 | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html | return [self.question_key]
@property
def output_keys(self) -> List[str]:
"""Return output key.
:meta private:
"""
_output_keys = [self.answer_key, self.sources_answer_key]
if self.return_source_documents:
_output_keys = _output_keys + ["source_documents"]
... |
931a49bdbac1-3 | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html | """Get docs to run questioning over."""
async def _acall(
self,
inputs: Dict[str, Any],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
_run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()
docs = await self._... |
931a49bdbac1-4 | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html | Last updated on Jun 04, 2023. |
4969c49038a6-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html | Source code for langchain.chains.qa_with_sources.vector_db
"""Question-answering with sources over a vector database."""
import warnings
from typing import Any, Dict, List
from pydantic import Field, root_validator
from langchain.chains.combine_documents.stuff import StuffDocumentsChain
from langchain.chains.qa_with_so... |
4969c49038a6-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/vector_db.html | return docs[:num_docs]
def _get_docs(self, inputs: Dict[str, Any]) -> List[Document]:
question = inputs[self.question_key]
docs = self.vectorstore.similarity_search(
question, k=self.k, **self.search_kwargs
)
return self._reduce_tokens_below_limit(docs)
async def _age... |
d1ffed48b939-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html | Source code for langchain.chains.graph_qa.base
"""Question answering over a graph."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import CallbackManagerForChainRun
from l... |
d1ffed48b939-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/base.html | 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, Any],
run_mana... |
57eb559e2eb0-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html | Source code for langchain.chains.graph_qa.cypher
"""Question answering over a graph."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import CallbackManagerForChainRun
from... |
57eb559e2eb0-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html | ) -> GraphCypherQAChain:
"""Initialize from LLM."""
qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
cypher_generation_chain = LLMChain(llm=llm, prompt=cypher_prompt)
return cls(
qa_chain=qa_chain,
cypher_generation_chain=cypher_generation_chain,
**kwarg... |
57eb559e2eb0-2 | https://python.langchain.com/en/latest/_modules/langchain/chains/graph_qa/cypher.html | Last updated on Jun 04, 2023. |
0e134576cecf-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html | 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.base_language import BaseLanguageModel
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base i... |
0e134576cecf-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/qa_generation/base.html | run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, List]:
docs = self.text_splitter.create_documents([inputs[self.input_key]])
results = self.llm_chain.generate(
[{"text": d.page_content} for d in docs], run_manager=run_manager
)
qa = [json.loads(res... |
d48d19006a07-0 | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html | 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.base_language import BaseLanguageModel
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain... |
d48d19006a07-1 | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html | revision_chain: LLMChain
return_intermediate_steps: bool = False
[docs] @classmethod
def get_principles(
cls, names: Optional[List[str]] = None
) -> List[ConstitutionalPrinciple]:
if names is None:
return list(PRINCIPLES.values())
else:
return [PRINCIPLES[n... |
d48d19006a07-2 | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html | _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
response = self.chain.run(
**inputs,
callbacks=_run_manager.get_child(),
)
initial_response = response
input_prompt = self.chain.prompt.format(**inputs)
_run_manager.on_text(
... |
d48d19006a07-3 | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html | color="green",
)
_run_manager.on_text(
text="Critique: " + critique + "\n\n",
verbose=self.verbose,
color="blue",
)
_run_manager.on_text(
text="Updated response: " + revision + "\n\n",
verbose... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.