id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
9305743edd50-22 | raise ImportError(
"Could not import tiktoken python package. "
"This is needed in order to calculate get_num_tokens. "
"Please install it with `pip install tiktoken`."
)
enc = tiktoken.encoding_for_model(self.model_name)
return enc.encode(
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
66db28aa039b-0 | Source code for langchain.llms.ai21
from typing import Any, Dict, List, Optional
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.utils import get_from_dict_or_env
[docs]class AI21Pen... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
66db28aa039b-1 | countPenalty: AI21PenaltyData = AI21PenaltyData()
"""Penalizes repeated tokens according to count."""
frequencyPenalty: AI21PenaltyData = AI21PenaltyData()
"""Penalizes repeated tokens according to frequency."""
numResults: int = 1
"""How many completions to generate for each prompt."""
logitBia... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
66db28aa039b-2 | "logitBias": self.logitBias,
}
@property
def _identifying_params(self) -> Dict[str, Any]:
"""Get the identifying parameters."""
return {**{"model": self.model}, **self._default_params}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "ai21"
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
66db28aa039b-3 | response = requests.post(
url=f"{base_url}/{self.model}/complete",
headers={"Authorization": f"Bearer {self.ai21_api_key}"},
json={"prompt": prompt, "stopSequences": stop, **params},
)
if response.status_code != 200:
optional_detail = response.json().get("... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
53b6373a74dc-0 | Source code for langchain.llms.fireworks
"""Wrapper around Fireworks APIs"""
import json
import logging
from typing import (
Any,
Dict,
List,
Optional,
Set,
Tuple,
Union,
)
import requests
from pydantic import Field, root_validator
from langchain.callbacks.manager import (
AsyncCallbackM... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html |
53b6373a74dc-1 | """Maximum number of retries to make when generating."""
@property
def lc_secrets(self) -> Dict[str, str]:
return {"fireworks_api_key": "FIREWORKS_API_KEY"}
@property
def lc_serializable(self) -> bool:
return True
def __new__(cls, **data: Any) -> Any:
"""Initialize the Firewo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html |
53b6373a74dc-2 | choices = []
token_usage: Dict[str, int] = {}
_keys = {"completion_tokens", "prompt_tokens", "total_tokens"}
for _prompts in sub_prompts:
response = completion_with_retry(self, prompt=prompts, **params)
choices.extend(response)
update_token_usage(_keys, respon... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html |
53b6373a74dc-3 | if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
sub_prompts = [
prompts[i : i + self.batch_size]
for i in range(0, len(prompts), self.batch_size)
]
return sub_prompts
[docs] de... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html |
53b6373a74dc-4 | .. code-block:: python
from langchain.llms import FireworksChat
fireworkschat = FireworksChat(model_id=""fireworks-llama-v2-13b-chat"")
"""
model_id: str = "accounts/fireworks/models/fireworks-llama-v2-7b-chat"
"""Model name to use."""
temperature: float = 0.7
"""What samplin... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html |
53b6373a74dc-5 | )
messages = self.prefix_messages + [{"role": "user", "content": prompts[0]}]
params: Dict[str, Any] = {**{"model": self.model_id}}
if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
return messages... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html |
53b6373a74dc-6 | llm_output=llm_output,
)
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "fireworks-chat"
[docs]class Fireworks(BaseFireworks):
"""Wrapper around Fireworks large language models.
To use, you should have the ``fireworks`` python package installed, and the
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html |
53b6373a74dc-7 | requestBody = {
"model": model,
"prompt": prompt,
"max_tokens": max_tokens,
"temperature": temperature,
"top_p": top_p,
}
requestHeaders = {
"Authorization": f"Bearer {api_key}",
"Accept": "application/json",
"Content-Type": "application/json",
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html |
53b6373a74dc-8 | llm: Union[BaseFireworks, FireworksChat], **kwargs: Any
) -> Any:
"""Use tenacity to retry the async completion call."""
if "prompt" not in kwargs.keys():
answers = []
for i in range(len(kwargs["messages"])):
result = kwargs["messages"][i]["content"]
result = execute(
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/fireworks.html |
2541c43e3951-0 | Source code for langchain.llms.utils
"""Common utility functions for LLM APIs."""
import re
from typing import List
[docs]def enforce_stop_tokens(text: str, stop: List[str]) -> str:
"""Cut off the text as soon as any stop words occur."""
return re.split("|".join(stop), text)[0] | https://api.python.langchain.com/en/latest/_modules/langchain/llms/utils.html |
cb56d2a0f698-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://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
cb56d2a0f698-1 | """Will always return text key.
: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:... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
9a3fb5ec9d73-0 | Source code for langchain.chains.base
"""Base interface that all chains should implement."""
import inspect
import json
import logging
import warnings
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import yaml
from pydantic import Field, root_validator, ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-1 | execute a Chain. This takes inputs as a dictionary and returns a
dictionary output.
- `run`: A convenience method that takes inputs as args/kwargs and returns the
output as a string or object. This method can only be used for a subset of
chains and cannot return as rich of an... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-2 | Each custom chain can optionally call additional callback methods, see Callback docs
for full details."""
callback_manager: Optional[BaseCallbackManager] = Field(default=None, exclude=True)
"""Deprecated, use `callbacks` instead."""
verbose: bool = Field(default_factory=_get_verbosity)
"""Whether or... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-3 | )
values["callbacks"] = values.pop("callback_manager", None)
return values
@validator("verbose", pre=True, always=True)
def set_verbose(cls, verbose: Optional[bool]) -> bool:
"""Set the chain verbosity.
Defaults to the global setting if not specified by the user.
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-4 | inputs: A dict of named inputs to the chain. Assumed to contain all inputs
specified in `Chain.input_keys`, including any inputs added by memory.
run_manager: The callbacks manager that contains the callback handlers for
this run of the chain.
Returns:
A d... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-5 | ) -> Dict[str, Any]:
"""Execute the chain.
Args:
inputs: Dictionary of inputs, or single input if chain expects
only one param. Should contain all inputs specified in
`Chain.input_keys` except for inputs that will be set by the chain's
memory.
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-6 | outputs = (
self._call(inputs, run_manager=run_manager)
if new_arg_supported
else self._call(inputs)
)
except (KeyboardInterrupt, Exception) as e:
run_manager.on_chain_error(e)
raise e
run_manager.on_chain_end(outputs)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-7 | these runtime callbacks will propagate to calls to other objects.
tags: List of string tags to pass to all callbacks. These will be passed in
addition to tags passed to the chain during construction, but only
these runtime tags will propagate to calls to other objects.
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-8 | outputs: Dict[str, str],
return_only_outputs: bool = False,
) -> Dict[str, str]:
"""Validate and prepare chain outputs, and save info about this run to memory.
Args:
inputs: Dictionary of chain inputs, including any inputs added by chain
memory.
output... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-9 | if len(_input_keys) != 1:
raise ValueError(
f"A single string input was passed in, but this chain expects "
f"multiple inputs ({_input_keys}). When a chain expects "
f"multiple inputs, please call it by passing in a dictionary, "
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-10 | callbacks: Callbacks to use for this chain run. These will be called in
addition to callbacks passed to the chain during construction, but only
these runtime callbacks will propagate to calls to other objects.
tags: List of string tags to pass to all callbacks. These will be ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-11 | ]
if not kwargs and not args:
raise ValueError(
"`run` supported with either positional arguments or keyword arguments,"
" but none were provided."
)
else:
raise ValueError(
f"`run` supported with either positional argum... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-12 | The chain output.
Example:
.. code-block:: python
# Suppose we have a single-input chain that takes a 'question' string:
await chain.arun("What's the temperature in Boise, Idaho?")
# -> "The temperature in Boise is..."
# Suppose we have... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-13 | """Dictionary representation of chain.
Expects `Chain._chain_type` property to be implemented and for memory to be
null.
Args:
**kwargs: Keyword arguments passed to default `pydantic.BaseModel.dict`
method.
Returns:
A dictionary representation ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
9a3fb5ec9d73-14 | with open(file_path, "w") as f:
yaml.dump(chain_dict, f, default_flow_style=False)
else:
raise ValueError(f"{save_path} must be json or yaml")
[docs] def apply(
self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None
) -> List[Dict[str, str]]:
"""Ca... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html |
7a3c4ae0a861-0 | Source code for langchain.chains.prompt_selector
from abc import ABC, abstractmethod
from typing import Callable, List, Tuple
from pydantic import BaseModel, Field
from langchain.chat_models.base import BaseChatModel
from langchain.llms.base import BaseLLM
from langchain.schema import BasePromptTemplate
from langchain.... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/prompt_selector.html |
7a3c4ae0a861-1 | True if the language model is a BaseLLM model, False otherwise.
"""
return isinstance(llm, BaseLLM)
[docs]def is_chat_model(llm: BaseLanguageModel) -> bool:
"""Check if the language model is a chat model.
Args:
llm: Language model to check.
Returns:
True if the language model is a Ba... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/prompt_selector.html |
46a052fe2388-0 | Source code for langchain.chains.example_generator
from typing import List
from langchain.chains.llm import LLMChain
from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplate
from langchain.schema.language_model import BaseLanguageModel
TEST_GEN_TEMPLATE_SUFFIX = "... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/example_generator.html |
d2c80c29cd9e-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://api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
d2c80c29cd9e-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://api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
d2c80c29cd9e-2 | _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
for i, chain in enumerate(self.chains):
callbacks = _run_manager.get_child()
outputs = chain(known_values, return_only_outputs=True, callbacks=callbacks)
known_values.update(outputs)
return {k... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
d2c80c29cd9e-3 | """Return output key.
:meta private:
"""
return [self.output_key]
@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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
d2c80c29cd9e-4 | run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
_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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
d5d666a78ed0-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://api.python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
d5d666a78ed0-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://api.python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
e4b11c0c766a-0 | Source code for langchain.chains.transform
"""Chain that runs an arbitrary python function."""
import functools
import logging
from typing import Any, Awaitable, Callable, Dict, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/transform.html |
e4b11c0c766a-1 | def _call(
self,
inputs: Dict[str, str],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, str]:
return self.transform(inputs)
async def _acall(
self,
inputs: Dict[str, Any],
run_manager: Optional[AsyncCallbackManagerForChainRun] = N... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/transform.html |
7c8d2fe2b282-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 import ReduceDocumentsChain
from langchain.chains.api.base import APIChain
from langchain.chains.base import Chain
from langchain.chains.c... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-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://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-2 | )
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 config:
llm_chain = load_chain(config.pop("llm_chain_p... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-3 | if not isinstance(llm_chain, LLMChain):
raise ValueError(f"Expected LLMChain, got {llm_chain}")
if "reduce_documents_chain" in config:
reduce_documents_chain = load_chain_from_config(
config.pop("reduce_documents_chain")
)
elif "reduce_documents_chain_path" in config:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-4 | collapse_documents_chain = None
else:
collapse_documents_chain = load_chain_from_config(
collapse_document_chain_config
)
elif "collapse_documents_chain_path" in config:
collapse_documents_chain = load_chain(
config.pop("collapse_documents_chain_pa... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-5 | # 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 = config.pop("prompt")
prompt = load_prompt_from_config(prompt... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-6 | 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_... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-7 | llm_chain = load_chain(config.pop("llm_chain_path"))
# 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,
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-8 | return MapRerankDocumentsChain(llm_chain=llm_chain, **config)
def _load_pal_chain(config: dict, **kwargs: Any) -> Any:
from langchain_experimental.pal_chain import PALChain
if "llm_chain" in config:
llm_chain_config = config.pop("llm_chain")
llm_chain = load_chain_from_config(llm_chain_config)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-9 | else:
raise ValueError(
"One of `refine_llm_chain` or `refine_llm_chain_config` must be present."
)
if "document_prompt" in config:
prompt_config = config.pop("document_prompt")
document_prompt = load_prompt_from_config(prompt_config)
elif "document_prompt_path" in co... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-10 | 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)
else:
prompt = None
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-11 | else:
raise ValueError("`retriever` 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 co... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-12 | graph = kwargs.pop("graph")
else:
raise ValueError("`graph` must be present.")
if "cypher_generation_chain" in config:
cypher_generation_chain_config = config.pop("cypher_generation_chain")
cypher_generation_chain = load_chain_from_config(cypher_generation_chain_config)
else:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-13 | else:
raise ValueError(
"One of `api_answer_chain` or `api_answer_chain_path` must be present."
)
if "requests_wrapper" in kwargs:
requests_wrapper = kwargs.pop("requests_wrapper")
else:
raise ValueError("`requests_wrapper` must be present.")
return APIChain(
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-14 | "llm_math_chain": _load_llm_math_chain,
"llm_requests_chain": _load_llm_requests_chain,
"pal_chain": _load_pal_chain,
"qa_with_sources_chain": _load_qa_with_sources_chain,
"stuff_documents_chain": _load_stuff_documents_chain,
"map_reduce_documents_chain": _load_map_reduce_documents_chain,
"reduc... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
7c8d2fe2b282-15 | 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... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
9263e91b110f-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, Mapping, Optional
from pydantic import Extra
from langchain.cal... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
9263e91b110f-1 | **kwargs: Any,
) -> MapReduceChain:
"""Construct a map-reduce chain that uses the chain for map and reduce."""
llm_chain = LLMChain(llm=llm, prompt=prompt, callbacks=callbacks)
stuff_chain = StuffDocumentsChain(
llm_chain=llm_chain,
callbacks=callbacks,
**... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
9263e91b110f-2 | # Split the larger text into smaller chunks.
doc_text = inputs.pop(self.input_key)
texts = self.text_splitter.split_text(doc_text)
docs = [Document(page_content=text) for text in texts]
_inputs: Dict[str, Any] = {
**inputs,
self.combine_documents_chain.input_key: ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
d0576b010a84-0 | Source code for langchain.chains.llm
"""Chain that just formats a prompt and calls an LLM."""
from __future__ import annotations
import warnings
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
from pydantic import Extra, Field
from langchain.callbacks.manager import (
AsyncCallbackManager,
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
d0576b010a84-1 | """Output parser to use.
Defaults to one that takes the most likely string but does not change it
otherwise."""
return_final_only: bool = True
"""Whether to return only the final parsed result. Defaults to True.
If false, will return a bunch of extra information about the generation."""
llm_kwa... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
d0576b010a84-2 | stop,
callbacks=run_manager.get_child() if run_manager else None,
**self.llm_kwargs,
)
[docs] async def agenerate(
self,
input_list: List[Dict[str, Any]],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> LLMResult:
"""Generate LLM... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
d0576b010a84-3 | )
prompts.append(prompt)
return prompts, stop
[docs] async def aprep_prompts(
self,
input_list: List[Dict[str, Any]],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Tuple[List[PromptValue], Optional[List[str]]]:
"""Prepare prompts from inpu... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
d0576b010a84-4 | try:
response = self.generate(input_list, run_manager=run_manager)
except (KeyboardInterrupt, Exception) as e:
run_manager.on_chain_error(e)
raise e
outputs = self.create_outputs(response)
run_manager.on_chain_end({"outputs": outputs})
return outputs
[... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
d0576b010a84-5 | return result
async def _acall(
self,
inputs: Dict[str, Any],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, str]:
response = await self.agenerate([inputs], run_manager=run_manager)
return self.create_outputs(response)[0]
[docs] def predi... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
d0576b010a84-6 | warnings.warn(
"The predict_and_parse method is deprecated, "
"instead pass an output parser directly to LLMChain."
)
result = self.predict(callbacks=callbacks, **kwargs)
if self.prompt.output_parser is not None:
return self.prompt.output_parser.parse(result)
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
d0576b010a84-7 | self.prompt.output_parser.parse(res[self.output_key])
for res in generation
]
else:
return generation
[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://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
a987d46ca8b1-0 | Source code for langchain.chains.natbot.base
"""Implement an LLM driven browser."""
from __future__ import annotations
import warnings
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base imp... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html |
a987d46ca8b1-1 | "Directly instantiating an NatBotChain with an llm is deprecated. "
"Please instantiate with llm_chain argument or using the from_llm "
"class method."
)
if "llm_chain" not in values and values["llm"] is not None:
values["llm_chain"] = LLMChain(llm... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html |
a987d46ca8b1-2 | ) -> Dict[str, str]:
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
url = inputs[self.input_url_key]
browser_content = inputs[self.input_browser_content_key]
llm_cmd = self.llm_chain.predict(
objective=self.objective,
url=url[:100],
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/base.html |
3b34f7f34877-0 | Source code for langchain.chains.natbot.crawler
# flake8: noqa
import time
from sys import platform
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Optional,
Set,
Tuple,
TypedDict,
Union,
)
if TYPE_CHECKING:
from playwright.sync_api import Browser, CDPSession, ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html |
3b34f7f34877-1 | )
self.page: Page = self.browser.new_page()
self.page.set_viewport_size({"width": 1280, "height": 1080})
self.page_element_buffer: Dict[int, ElementInViewPort]
self.client: CDPSession
[docs] def go_to_page(self, url: str) -> None:
self.page.goto(url=url if "://" in url else "h... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html |
3b34f7f34877-2 | else:
print("Could not find element")
[docs] def type(self, id: Union[str, int], text: str) -> None:
self.click(id)
self.page.keyboard.type(text)
[docs] def enter(self) -> None:
self.page.keyboard.press("Enter")
[docs] def crawl(self) -> List[str]:
page = self.page
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html |
3b34f7f34877-3 | ),
}
)
tree = self.client.send(
"DOMSnapshot.captureSnapshot",
{"computedStyles": [], "includeDOMRects": True, "includePaintOrder": True},
)
strings: Dict[int, str] = tree["strings"]
document: Dict[str, Any] = tree["documents"][0]
nodes... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html |
3b34f7f34877-4 | node_name: Optional[str], has_click_handler: Optional[bool]
) -> str:
if node_name == "a":
return "link"
if node_name == "input":
return "input"
if node_name == "img":
return "img"
if (
node_name == "... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html |
3b34f7f34877-5 | )
is_parent_desc_anchor, anchor_id = hash_tree[parent_id_str]
# even if the anchor is nested in another anchor, we set the "root" for all descendants to be ::Self
if node_name == tag:
value: Tuple[bool, Optional[int]] = (True, node_id)
elif (
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html |
3b34f7f34877-6 | elem_left_bound = x
elem_top_bound = y
elem_right_bound = x + width
elem_lower_bound = y + height
partially_is_in_viewport = (
elem_left_bound < win_right_bound
and elem_right_bound >= win_left_bound
and elem_top_bound < win... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html |
3b34f7f34877-7 | if ancestor_exception and ancestor_node:
ancestor_node.append(
{
"type": "attribute",
"key": key,
"value": element_attributes[key],
}
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html |
3b34f7f34877-8 | elements_of_interest = []
id_counter = 0
for element in elements_in_view_port:
node_index = element.get("node_index")
node_name = element.get("node_name")
element_node_value = element.get("node_value")
node_is_clickable = element.get("is_clickable")
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html |
3b34f7f34877-9 | if inner_text != "":
elements_of_interest.append(
f"""<{converted_node_name} id={id_counter}{meta}>{inner_text}</{converted_node_name}>"""
)
else:
elements_of_interest.append(
f"""<{converted_node_name} id={id_counter}{m... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/natbot/crawler.html |
eec181bd6983-0 | Source code for langchain.chains.router.base
"""Base classes for chain routing."""
from __future__ import annotations
from abc import ABC
from typing import Any, Dict, List, Mapping, NamedTuple, Optional
from pydantic import Extra
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
Callba... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/base.html |
eec181bd6983-1 | """Chains that return final answer to inputs."""
default_chain: Chain
"""Default chain to use when none of the destination chains are suitable."""
silent_errors: bool = False
"""If True, use default_chain when an invalid destination name is provided.
Defaults to False."""
class Config:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/base.html |
eec181bd6983-2 | f"Received invalid destination chain name '{route.destination}'"
)
async def _acall(
self,
inputs: Dict[str, Any],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
_run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noo... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/base.html |
6c3503967a06-0 | Source code for langchain.chains.router.embedding_router
from __future__ import annotations
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type
from pydantic import Extra
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.router.base import RouterChain
from langchai... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/embedding_router.html |
6c3503967a06-1 | """Convenience constructor."""
documents = []
for name, descriptions in names_and_descriptions:
for description in descriptions:
documents.append(
Document(page_content=description, metadata={"name": name})
)
vectorstore = vectorsto... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/embedding_router.html |
dafe770a58ad-0 | Source code for langchain.chains.router.multi_retrieval_qa
"""Use a single chain to route an input to one of multiple retrieval qa chains."""
from __future__ import annotations
from typing import Any, Dict, List, Mapping, Optional
from langchain.chains import ConversationChain
from langchain.chains.base import Chain
fr... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_retrieval_qa.html |
dafe770a58ad-1 | default_retriever: Optional[BaseRetriever] = None,
default_prompt: Optional[PromptTemplate] = None,
default_chain: Optional[Chain] = None,
**kwargs: Any,
) -> MultiRetrievalQAChain:
if default_prompt and not default_retriever:
raise ValueError(
"`default_r... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_retrieval_qa.html |
dafe770a58ad-2 | prompt = PromptTemplate(
template=prompt_template, input_variables=["history", "query"]
)
_default_chain = ConversationChain(
llm=ChatOpenAI(), prompt=prompt, input_key="query", output_key="result"
)
return cls(
router_chain=router_... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_retrieval_qa.html |
3960885e03ea-0 | Source code for langchain.chains.router.multi_prompt
"""Use a single chain to route an input to one of multiple llm chains."""
from __future__ import annotations
from typing import Any, Dict, List, Mapping, Optional
from langchain.chains import ConversationChain
from langchain.chains.llm import LLMChain
from langchain.... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_prompt.html |
3960885e03ea-1 | destinations_str = "\n".join(destinations)
router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(
destinations=destinations_str
)
router_prompt = PromptTemplate(
template=router_template,
input_variables=["input"],
output_parser=RouterOutputParser(... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/multi_prompt.html |
49445972fd6a-0 | Source code for langchain.chains.router.llm_router
"""Base classes for LLM-powered router chains."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Type, cast
from pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
Callback... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/llm_router.html |
49445972fd6a-1 | raise ValueError
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
callbacks = _run_manager.get_child()
output = cast(... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/llm_router.html |
49445972fd6a-2 | [docs] def parse(self, text: str) -> Dict[str, Any]:
try:
expected_keys = ["destination", "next_inputs"]
parsed = parse_and_check_json_markdown(text, expected_keys)
if not isinstance(parsed["destination"], str):
raise ValueError("Expected 'destination' to b... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/router/llm_router.html |
586f36c69ead-0 | Source code for langchain.chains.qa_with_sources.base
"""Question answering with sources over documents."""
from __future__ import annotations
import inspect
import re
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.man... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
586f36c69ead-1 | [docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
document_prompt: BasePromptTemplate = EXAMPLE_PROMPT,
question_prompt: BasePromptTemplate = QUESTION_PROMPT,
combine_prompt: BasePromptTemplate = COMBINE_PROMPT,
**kwargs: Any,
) -> BaseQAWithSource... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
586f36c69ead-2 | )
return cls(combine_documents_chain=combine_documents_chain, **kwargs)
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@property
def input_keys(self) -> List[str]:
"""Expect input key.
:meta priv... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/qa_with_sources/base.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.