id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
a163ec0668ee-0 | Source code for langchain.llms.google_palm
"""Wrapper arround Google's PaLM Text APIs."""
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
from pydantic import BaseModel, root_validator
from tenacity import (
before_sleep_log,
retry,
retry_if_exception... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
a163ec0668ee-1 | ),
before_sleep=before_sleep_log(logger, logging.WARNING),
)
def generate_with_retry(llm: GooglePalm, **kwargs: Any) -> Any:
"""Use tenacity to retry the completion call."""
retry_decorator = _create_retry_decorator()
@retry_decorator
def _generate_with_retry(**kwargs: Any) -> Any:
r... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
a163ec0668ee-2 | Must be positive."""
max_output_tokens: Optional[int] = None
"""Maximum number of tokens to include in a candidate. Must be greater than zero.
If unset, will default to 64."""
n: int = 1
"""Number of chat completions to generate for each prompt. Note that the API may
not return the full n ... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
a163ec0668ee-3 | return values
def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> LLMResult:
generations = []
for prompt in prompts:
completion = generate_with_retry(
s... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
af4d6b3d29ad-0 | Source code for langchain.llms.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms import OpenAI, OpenAIChat
from langchain.schema import LLMResult... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
af4d6b3d29ad-1 | """Call OpenAI generate and then call PromptLayer API to log the request."""
from promptlayer.utils import get_api_key, promptlayer_api_request
request_start_time = datetime.datetime.now().timestamp()
generated_responses = super()._generate(prompts, stop, run_manager)
request_end_time = ... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
af4d6b3d29ad-2 | for i in range(len(prompts)):
prompt = prompts[i]
generation = generated_responses.generations[i][0]
resp = {
"text": generation.text,
"llm_output": generated_responses.llm_output,
}
pl_request_id = await promptlayer_api_request... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
af4d6b3d29ad-3 | ``Generation`` object.
Example:
.. code-block:: python
from langchain.llms import PromptLayerOpenAIChat
openaichat = PromptLayerOpenAIChat(model_name="gpt-3.5-turbo")
"""
pl_tags: Optional[List[str]]
return_pl_id: Optional[bool] = False
def _generate(
self,
... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
af4d6b3d29ad-4 | generation.generation_info, dict
):
generation.generation_info = {}
generation.generation_info["pl_request_id"] = pl_request_id
return generated_responses
async def _agenerate(
self,
prompts: List[str],
stop: Optional[List[str]] = N... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
8381c5679e55-0 | Source code for langchain.llms.vertexai
"""Wrapper around Google VertexAI models."""
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from pydantic import BaseModel, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils i... | https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
8381c5679e55-1 | "credentials will be ascertained from the environment." ""
@property
def _default_params(self) -> Dict[str, Any]:
base_params = {
"temperature": self.temperature,
"max_output_tokens": self.max_output_tokens,
"top_k": self.top_p,
"top_p": self.top_k,
... | https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
8381c5679e55-2 | try:
from vertexai.preview.language_models import TextGenerationModel
except ImportError:
raise_vertex_import_error()
tuned_model_name = values.get("tuned_model_name")
if tuned_model_name:
values["client"] = TextGenerationModel.get_tuned_model(tuned_model_name... | https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
0c9149d78831-0 | Source code for langchain.llms.predictionguard
"""Wrapper around Prediction Guard APIs."""
import logging
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils... | https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
0c9149d78831-1 | try:
import predictionguard as pg
values["client"] = pg.Client(token=token)
except ImportError:
raise ImportError(
"Could not import predictionguard python package. "
"Please install it with `pip install predictionguard`."
)
... | https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
0c9149d78831-2 | response = self.client.predict(
name=self.name,
data={
"prompt": prompt,
"max_tokens": params["max_tokens"],
"temperature": params["temperature"],
},
)
text = response["text"]
# If stop tokens are provided, Predi... | https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
b4401b06e7d0-0 | Source code for langchain.llms.anthropic
"""Wrapper around Anthropic APIs."""
import re
import warnings
from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple, Union
from pydantic import BaseModel, Extra, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMR... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
b4401b06e7d0-1 | anthropic_api_key = get_from_dict_or_env(
values, "anthropic_api_key", "ANTHROPIC_API_KEY"
)
try:
import anthropic
values["client"] = anthropic.Client(
api_key=anthropic_api_key,
default_request_timeout=values["default_request_timeout"]... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
b4401b06e7d0-2 | if stop is None:
stop = []
# Never want model to invent new turns of Human / Assistant dialog.
stop.extend([self.HUMAN_PROMPT])
return stop
[docs]class Anthropic(LLM, _AnthropicCommon):
r"""Wrapper around Anthropic's large language models.
To use, you should have the ``anthro... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
b4401b06e7d0-3 | extra = Extra.forbid
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "anthropic-llm"
def _wrap_prompt(self, prompt: str) -> str:
if not self.HUMAN_PROMPT or not self.AI_PROMPT:
raise NameError("Please ensure the anthropic package is loaded")
... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
b4401b06e7d0-4 | if self.streaming:
stream_resp = self.client.completion_stream(
prompt=self._wrap_prompt(prompt),
stop_sequences=stop,
**self._default_params,
)
current_completion = ""
for data in stream_resp:
delta = data["... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
b4401b06e7d0-5 | **self._default_params,
)
return response["completion"]
[docs] def stream(self, prompt: str, stop: Optional[List[str]] = None) -> Generator:
r"""Call Anthropic completion_stream and return the resulting generator.
BETA: this is a beta feature while we figure out the right abstraction.... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
beed16652cf3-0 | Source code for langchain.llms.openai
"""Wrapper around OpenAI APIs."""
from __future__ import annotations
import logging
import sys
import warnings
from typing import (
AbstractSet,
Any,
Callable,
Collection,
Dict,
Generator,
List,
Literal,
Mapping,
Optional,
Set,
Tuple,... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-1 | "finish_reason"
]
response["choices"][0]["logprobs"] = stream_response["choices"][0]["logprobs"]
def _streaming_response_template() -> Dict[str, Any]:
return {
"choices": [
{
"text": "",
"finish_reason": None,
"logprobs": None,
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-2 | return llm.client.create(**kwargs)
return _completion_with_retry(**kwargs)
async def acompletion_with_retry(
llm: Union[BaseOpenAI, OpenAIChat], **kwargs: Any
) -> Any:
"""Use tenacity to retry the async completion call."""
retry_decorator = _create_retry_decorator(llm)
@retry_decorator
async de... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-3 | model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
openai_api_key: Optional[str] = None
openai_api_base: Optional[str] = None
openai_organization: Optional[str] = None
batch_size: int = 20
"""Batch size to... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-4 | )
return OpenAIChat(**data)
return super().__new__(cls)
class Config:
"""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]:... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-5 | "openai_api_base",
"OPENAI_API_BASE",
default="",
)
openai_organization = get_from_dict_or_env(
values,
"openai_organization",
"OPENAI_ORGANIZATION",
default="",
)
try:
import openai
openai.ap... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-6 | 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]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> LLMResult:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-7 | logprobs=stream_resp["choices"][0]["logprobs"],
)
_update_response(response, stream_resp)
choices.extend(response["choices"])
else:
response = completion_with_retry(self, prompt=_prompts, **params)
choices.extend(res... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-8 | stream_resp["choices"][0]["text"],
verbose=self.verbose,
logprobs=stream_resp["choices"][0]["logprobs"],
)
_update_response(response, stream_resp)
choices.extend(response["choices"])
else:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-9 | """Create the LLMResult from the choices and prompts."""
generations = []
for i, _ in enumerate(prompts):
sub_choices = choices[i * self.n : (i + 1) * self.n]
generations.append(
[
Generation(
text=choice["text"],
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-10 | """Prepare the params for streaming."""
params = self._invocation_params
if "best_of" in params and params["best_of"] != 1:
raise ValueError("OpenAI only supports best_of == 1 for streaming")
if stop is not None:
if "stop" in params:
raise ValueError("`sto... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-11 | allowed_special=self.allowed_special,
disallowed_special=self.disallowed_special,
)
def modelname_to_contextsize(self, modelname: str) -> int:
"""Calculate the maximum number of tokens possible to generate for a model.
Args:
modelname: The modelname we want to know th... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-12 | }
# handling finetuned models
if "ft-" in modelname:
modelname = modelname.split(":")[0]
context_size = model_token_mapping.get(modelname, None)
if context_size is None:
raise ValueError(
f"Unknown model: {modelname}. Please provide a valid OpenAI ... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-13 | @property
def _invocation_params(self) -> Dict[str, Any]:
return {**{"model": self.model_name}, **super()._invocation_params}
[docs]class AzureOpenAI(BaseOpenAI):
"""Wrapper around Azure-specific OpenAI large language models.
To use, you should have the ``openai`` python package installed, and the
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-14 | in, even if not explicitly saved on this class.
Example:
.. code-block:: python
from langchain.llms import OpenAIChat
openaichat = OpenAIChat(model_name="gpt-3.5-turbo")
"""
client: Any #: :meta private:
model_name: str = "gpt-3.5-turbo"
"""Model name to use."""
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-15 | 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} supplied twice.")
extra[field_name] = values.pop(field_name)
values["model_kwargs"] = extra
return ... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-16 | "with `pip install --upgrade openai`."
)
warnings.warn(
"You are trying to use a chat model. This way of initializing it is "
"no longer supported. Instead, please use: "
"`from langchain.chat_models import ChatOpenAI`"
)
return values
@propert... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-17 | if self.streaming:
response = ""
params["stream"] = True
for stream_resp in completion_with_retry(self, messages=messages, **params):
token = stream_resp["choices"][0]["delta"].get("content", "")
response += token
if run_manager:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beed16652cf3-18 | )
else:
full_response = await acompletion_with_retry(
self, messages=messages, **params
)
llm_output = {
"token_usage": full_response["usage"],
"model_name": self.model_name,
}
return LLMResult(
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
45faacad6ded-0 | 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.... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
45faacad6ded-1 | huggingfacehub_api_token: Optional[str] = None
class Config:
"""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."""
hugging... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
45faacad6ded-2 | return "huggingface_endpoint"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
prompt: The prompt to pass into t... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
45faacad6ded-3 | elif self.task == "summarization":
text = generated_text[0]["summary_text"]
else:
raise ValueError(
f"Got invalid task {self.task}, "
f"currently only {VALID_TASKS} are supported"
)
if stop is not None:
# This is a bit hacky... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
6abf18ec76fa-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/llms/openlm.html |
50a84cc7e653-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
50a84cc7e653-1 | """Positive values penalize new tokens based on their existing frequency
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 ... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
50a84cc7e653-2 | """Validate that the python package exists in the environment."""
try:
import tokenizers
except ImportError:
raise ImportError(
"Could not import tokenizers python package. "
"Please install it with `pip install tokenizers`."
)
... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
50a84cc7e653-3 | AVOID_REPEAT_TOKENS = []
AVOID_REPEAT = ",:?!"
for i in AVOID_REPEAT:
dd = self.pipeline.encode(i)
assert len(dd) == 1
AVOID_REPEAT_TOKENS += dd
tokens = [int(x) for x in _tokens]
self.model_tokens += tokens
out: Any = None
while len(to... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
50a84cc7e653-4 | occurrence[token] += 1
logits = self.run_rnn([token])
xxx = self.tokenizer.decode(self.model_tokens[out_last:])
if "\ufffd" not in xxx: # avoid utf-8 display issues
decoded += xxx
out_last = begin + i + 1
if i >= self.max_tokens_per_ge... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
5a6008f8ed31-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
5a6008f8ed31-1 | """Build extra kwargs from additional params that were passed in."""
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 ... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
5a6008f8ed31-2 | except ImportError:
raise ImportError(
"Could not import replicate python package. "
"Please install it with `pip install replicate`."
)
# get the model and version
model_str, version_str = self.model.split(":")
model = replicate_python.mod... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
beb3bff275a5-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 Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForChainRun
from langc... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
beb3bff275a5-1 | :meta private:
"""
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:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
cd83d6df55e4-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/chains/transform.html |
0e6b5c0a7940-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 Any, Dict, List, Optional
from pydantic import Extra
from langchain.base_languag... | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
0e6b5c0a7940-1 | reduce_chain = StuffDocumentsChain(llm_chain=llm_chain, callbacks=callbacks)
combine_documents_chain = MapReduceDocumentsChain(
llm_chain=llm_chain,
combine_document_chain=reduce_chain,
callbacks=callbacks,
)
return cls(
combine_documents_chain=com... | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
42e58087aeef-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.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
from langchain.utils import get_from_dic... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
42e58087aeef-1 | values,
"openai_organization",
"OPENAI_ORGANIZATION",
default="",
)
try:
import openai
openai.api_key = openai_api_key
if openai_organization:
openai.organization = openai_organization
values["client"] = ... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
18647f5f85ae-0 | 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,
)... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
18647f5f85ae-1 | overlapping_keys = set(input_variables) & set(memory_keys)
raise ValueError(
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."
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
18647f5f85ae-2 | callbacks = _run_manager.get_child()
outputs = chain(known_values, return_only_outputs=True, callbacks=callbacks)
known_values.update(outputs)
return {k: known_values[k] for k in self.output_variables}
async def _acall(
self,
inputs: Dict[str, Any],
run_manage... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
18647f5f85ae-3 | @root_validator()
def validate_chains(cls, values: Dict) -> Dict:
"""Validate that chains are all single input/output."""
for chain in values["chains"]:
if len(chain.input_keys) != 1:
raise ValueError(
"Chains used in SimplePipeline should all have one... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
18647f5f85ae-4 | _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()
callbacks = _run_manager.get_child()
_input = inputs[self.input_key]
color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))])
for i, chain in enumerate(self.chains):
_input = ... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
00834fe3b9ab-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.base_language import BaseLanguageModel
from langchain.callbacks.manager import (... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
00834fe3b9ab-1 | def output_keys(self) -> List[str]:
"""Will always return text key.
:meta private:
"""
return [self.output_key]
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, str]:
response = self.... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
00834fe3b9ab-2 | """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 = {k: inputs[k] for k in self.prompt.input_variables}
prompt = self.prompt.format_prompt(**se... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
00834fe3b9ab-3 | await run_manager.on_text(_text, end="\n", verbose=self.verbose)
if "stop" in inputs and inputs["stop"] != stop:
raise ValueError(
"If `stop` is present in any inputs, should be present in all."
)
prompts.append(prompt)
return prompts, ... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
00834fe3b9ab-4 | except (KeyboardInterrupt, Exception) as e:
await run_manager.on_chain_error(e)
raise e
outputs = self.create_outputs(response)
await run_manager.on_chain_end({"outputs": outputs})
return outputs
[docs] def create_outputs(self, response: LLMResult) -> List[Dict[str, st... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
00834fe3b9ab-5 | Returns:
Completion from LLM.
Example:
.. code-block:: python
completion = llm.predict(adjective="funny")
"""
return (await self.acall(kwargs, callbacks=callbacks))[self.output_key]
[docs] def predict_and_parse(
self, callbacks: Callbacks = None... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
00834fe3b9ab-6 | return [
self.prompt.output_parser.parse(res[self.output_key]) for res in result
]
else:
return result
[docs] async def aapply_and_parse(
self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None
) -> Sequence[Union[str, List[str], Dict[str, str]]... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
700f2901de3f-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 |
700f2901de3f-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 |
700f2901de3f-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 |
700f2901de3f-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 |
700f2901de3f-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 |
700f2901de3f-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 |
700f2901de3f-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 |
700f2901de3f-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 |
700f2901de3f-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 |
700f2901de3f-9 | else:
raise ValueError("`vectorstore` must be present.")
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 ... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
700f2901de3f-10 | api_request_chain_config = config.pop("api_request_chain")
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_r... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
700f2901de3f-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 |
700f2901de3f-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 |
700f2901de3f-13 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
709be11e44a7-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html |
709be11e44a7-1 | return list(np.array(embeddings).mean(axis=0))
[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 ... | https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html |
da22c33b4a4b-0 | 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... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
da22c33b4a4b-1 | return_intermediate_steps: bool = False
"""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 too... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
da22c33b4a4b-2 | :meta private:
"""
if not self.return_intermediate_steps:
return [self.output_key]
else:
return [self.output_key, INTERMEDIATE_STEPS_KEY]
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
da22c33b4a4b-3 | intermediate_steps.append(str(result)) # output: sql exec
else:
query_checker_prompt = self.query_checker_prompt or PromptTemplate(
template=QUERY_CHECKER, input_variables=["query", "dialect"]
)
query_checker_chain = LLMChain(
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
da22c33b4a4b-4 | intermediate_steps.append(llm_inputs) # input: final answer
final_result = self.llm_chain.predict(
callbacks=_run_manager.get_child(),
**llm_inputs,
).strip()
intermediate_steps.append(final_result) # output: final answer
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
da22c33b4a4b-5 | This is useful in cases where the number of tables in the database is large.
"""
decider_chain: LLMChain
sql_chain: SQLDatabaseChain
input_key: str = "query" #: :meta private:
output_key: str = "result" #: :meta private:
return_intermediate_steps: bool = False
[docs] @classmethod
def fr... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
da22c33b4a4b-6 | run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
_table_names = self.sql_chain.database.get_usable_table_names()
table_names = ", ".join(_table_names)
llm_inputs = {
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sql_database/base.html |
867dcf7f7e10-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.base_language i... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
867dcf7f7e10-1 | def output_keys(self) -> List[str]:
"""Return the output keys.
: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(
... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
867dcf7f7e10-2 | @abstractmethod
def _get_docs(self, question: str) -> List[Document]:
"""Get documents to do question answering over."""
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
"""Run get_relevant_text an... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
867dcf7f7e10-3 | the retrieved documents as well under the key 'source_documents'.
Example:
.. code-block:: python
res = indexqa({'query': 'This is my query'})
answer, docs = res['result'], res['source_documents']
"""
_run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
867dcf7f7e10-4 | [docs]class VectorDBQA(BaseRetrievalQA):
"""Chain for question-answering against a vector database."""
vectorstore: VectorStore = Field(exclude=True, alias="vectorstore")
"""Vector Database to connect to."""
k: int = 4
"""Number of documents to query for."""
search_type: str = "similarity"
"... | https://python.langchain.com/en/latest/_modules/langchain/chains/retrieval_qa/base.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.