id stringlengths 14 16 | text stringlengths 45 2.73k | source stringlengths 49 114 |
|---|---|---|
cbbcda269424-2 | [docs]class Anthropic(LLM, _AnthropicCommon):
r"""Wrapper around Anthropic's large language models.
To use, you should have the ``anthropic`` python package installed, and the
environment variable ``ANTHROPIC_API_KEY`` set with your API key, or pass
it as a named parameter to the constructor.
Exampl... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
cbbcda269424-3 | # Guard against common errors in specifying wrong number of newlines.
corrected_prompt, n_subs = re.subn(r"^\n*Human:", self.HUMAN_PROMPT, prompt)
if n_subs == 1:
return corrected_prompt
# As a last resort, wrap the prompt ourselves to emulate instruct-style.
return f"{self.H... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
cbbcda269424-4 | **self._default_params,
)
return response["completion"]
async def _acall(self, prompt: str, stop: Optional[List[str]] = None) -> str:
"""Call out to Anthropic's completion endpoint asynchronously."""
stop = self._get_anthropic_stop(stop)
if self.streaming:
stream_... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
cbbcda269424-5 | Example:
.. code-block:: python
prompt = "Write a poem about a stream."
prompt = f"\n\nHuman: {prompt}\n\nAssistant:"
generator = anthropic.stream(prompt)
for token in generator:
yield token
"""
stop = self._... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
ab08236abe9a-0 | Source code for langchain.llms.deepinfra
"""Wrapper around DeepInfra APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dic... | https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
ab08236abe9a-1 | """Get the identifying parameters."""
return {
**{"model_id": self.model_id},
**{"model_kwargs": self.model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "deepinfra"
def _call(self, prompt: str, stop: Optional[List[s... | https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
b5d3656661ee-0 | Source code for langchain.llms.cohere
"""Wrapper around Cohere APIs."""
import logging
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dict_or_env
logger ... | https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
b5d3656661ee-1 | truncate: Optional[str] = None
"""Specify how the client handles inputs longer than the maximum token
length: Truncate from START, END or NONE"""
cohere_api_key: Optional[str] = None
stop: Optional[List[str]] = None
class Config:
"""Configuration for this pydantic object."""
extra = ... | https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
b5d3656661ee-2 | """Return type of llm."""
return "cohere"
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
"""Call out to Cohere's generate endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
... | https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
f6781ceebfed-0 | Source code for langchain.llms.self_hosted
"""Run model inference on self-hosted remote hardware."""
import importlib.util
import logging
import pickle
from typing import Any, Callable, List, Mapping, Optional
from pydantic import Extra
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_t... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
f6781ceebfed-1 | if device < 0 and cuda_device_count > 0:
logger.warning(
"Device has %d GPUs available. "
"Provide device={deviceId} to `from_model_id` to use available"
"GPUs for execution. deviceId is -1 for CPU and "
"can be a positive integer associated wi... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
f6781ceebfed-2 | model_load_fn=load_pipeline,
hardware=gpu,
model_reqs=model_reqs, inference_fn=inference_fn
)
Example for <2GB model (can be serialized and sent directly to the server):
.. code-block:: python
from langchain.llms import SelfHostedPipeline
i... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
f6781ceebfed-3 | """Key word arguments to pass to the model load function."""
model_reqs: List[str] = ["./", "torch"]
"""Requirements to install on hardware to inference the model."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
def __init__(self, **kwargs: Any):
... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
f6781ceebfed-4 | logger.warning(
"Serializing pipeline to send to remote hardware. "
"Note, it can be quite slow"
"to serialize and send large models with each execution. "
"Consider sending the pipeline"
"to the cluster and passing the path to the pipeline... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
c36a40e67c05-0 | Source code for langchain.llms.ai21
"""Wrapper around AI21 APIs."""
from typing import Any, Dict, List, Optional
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM
from langchain.utils import get_from_dict_or_env
class AI21PenaltyData(BaseModel):
"""Parameters ... | https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
c36a40e67c05-1 | """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."""
logitBias: Optional[Dict[str, float]] = None
"""Adjust the... | https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
c36a40e67c05-2 | @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"
def _call(self, prompt: str, stop: Optio... | https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
c36a40e67c05-3 | optional_detail = response.json().get("error")
raise ValueError(
f"AI21 /complete call failed with status code {response.status_code}."
f" Details: {optional_detail}"
)
response_json = response.json()
return response_json["completions"][0]["data"][... | https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
a0c48aa968df-0 | Source code for langchain.llms.petals
"""Wrapper around Petals API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dict... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
a0c48aa968df-1 | max_length: Optional[int] = None
"""The maximum length of the sequence to be generated."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call
not explicitly specified."""
huggingface_api_key: Optional[str] = None
class Config:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
a0c48aa968df-2 | from transformers import BloomTokenizerFast
model_name = values["model_name"]
values["tokenizer"] = BloomTokenizerFast.from_pretrained(model_name)
values["client"] = DistributedBloomForCausalLM.from_pretrained(model_name)
values["huggingface_api_key"] = huggingface_api_ke... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
a0c48aa968df-3 | text = self.tokenizer.decode(outputs[0])
if stop is not None:
# I believe this is required since the stop tokens
# are not enforced by the model parameters
text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
d1ec8576d542-0 | Source code for langchain.llms.writer
"""Wrapper around Writer APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dict_or_e... | https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
d1ec8576d542-1 | by fixing the random seed (assuming all other hyperparameters
are also fixed)"""
beam_search_diversity_rate: float = 1.0
"""Only applies to beam search, i.e. when the beam width is >1.
A higher value encourages beam search to return a more diverse
set of candidates"""
beam_width: Optional[int] =... | https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
d1ec8576d542-2 | "temperature": self.temperature,
"top_p": self.top_p,
"top_k": self.top_k,
"repetition_penalty": self.repetition_penalty,
"random_seed": self.random_seed,
"beam_search_diversity_rate": self.beam_search_diversity_rate,
"beam_width": self.beam_width,... | https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
d1ec8576d542-3 | },
json={"prompt": prompt, **self._default_params},
)
text = response.text
if stop is not None:
# I believe this is required since the stop tokens
# are not enforced by the model parameters
text = enforce_stop_tokens(text, stop)
return text... | https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
cd1a44302203-0 | Source code for langchain.llms.sagemaker_endpoint
"""Wrapper around Sagemaker InvokeEndpoint API."""
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Mapping, Optional, Union
from pydantic import Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_st... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
cd1a44302203-1 | like object in the format specified in the content_type
request header.
"""
@abstractmethod
def transform_output(self, output: bytes) -> Any:
"""Transforms the output from the model to string that
the LLM class expects.
"""
[docs]class SagemakerEndpoint(LLM):
"""Wrapp... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
cd1a44302203-2 | Must be unique within an AWS Region."""
region_name: str = ""
"""The aws region where the Sagemaker model is deployed, eg. `us-west-2`."""
credentials_profile_name: Optional[str] = None
"""The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which
has either access keys or role ... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
cd1a44302203-3 | """
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that AWS credentials to and python package exists in environment."""
try:
import boto3
... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
cd1a44302203-4 | Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
response = se("Tell me a joke.")
"""
_mod... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
c5af9fd85ef5-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 |
c5af9fd85ef5-1 | 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 = 256
"""Batch size for prompt processing."""
max_tokens_per_generatio... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
c5af9fd85ef5-2 | raise ValueError(
"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.Tok... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
c5af9fd85ef5-3 | 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(tokens) > 0:
out, self.model_state = self.client.forw... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
c5af9fd85ef5-4 | 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_generation - 100:
break
return decoded
def _call... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
0b8645d984c1-0 | Source code for langchain.llms.nlpcloud
"""Wrapper around NLPCloud APIs."""
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, root_validator
from langchain.llms.base import LLM
from langchain.utils import get_from_dict_or_env
[docs]class NLPCloud(LLM):
"""Wrapper around NLPCloud larg... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
0b8645d984c1-1 | top_k: int = 50
"""The number of highest probability tokens to keep for top-k filtering."""
repetition_penalty: float = 1.0
"""Penalizes repeated tokens. 1.0 means no penalty."""
length_penalty: float = 1.0
"""Exponential penalty to the length."""
do_sample: bool = True
"""Whether to use sam... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
0b8645d984c1-2 | return {
"temperature": self.temperature,
"min_length": self.min_length,
"max_length": self.max_length,
"length_no_input": self.length_no_input,
"remove_input": self.remove_input,
"remove_end_sequence": self.remove_end_sequence,
"bad_wo... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
0b8645d984c1-3 | "Pass in a list of length 1."
)
elif stop and len(stop) == 1:
end_sequence = stop[0]
else:
end_sequence = None
response = self.client.generation(
prompt, end_sequence=end_sequence, **self._default_params
)
return response["generated... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
daa5f3a4bab7-0 | Source code for langchain.docstore.in_memory
"""Simple in memory docstore in the form of a dict."""
from typing import Dict, Union
from langchain.docstore.base import AddableMixin, Docstore
from langchain.docstore.document import Document
[docs]class InMemoryDocstore(Docstore, AddableMixin):
"""Simple in memory doc... | https://python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html |
9059e0e97d66-0 | Source code for langchain.docstore.wikipedia
"""Wrapper around wikipedia API."""
from typing import Union
from langchain.docstore.base import Docstore
from langchain.docstore.document import Document
[docs]class Wikipedia(Docstore):
"""Wrapper around wikipedia API."""
def __init__(self) -> None:
"""Chec... | https://python.langchain.com/en/latest/_modules/langchain/docstore/wikipedia.html |
f61445f0c2fb-0 | Source code for langchain.utilities.python
import sys
from io import StringIO
from typing import Dict, Optional
from pydantic import BaseModel, Field
[docs]class PythonREPL(BaseModel):
"""Simulates a standalone Python REPL."""
globals: Optional[Dict] = Field(default_factory=dict, alias="_globals")
locals: O... | https://python.langchain.com/en/latest/_modules/langchain/utilities/python.html |
08ca5ff35a13-0 | Source code for langchain.utilities.serpapi
"""Chain that calls SerpAPI.
Heavily borrowed from https://github.com/ofirpress/self-ask
"""
import os
import sys
from typing import Any, Dict, Optional, Tuple
import aiohttp
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.utils import get_from_dic... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
08ca5ff35a13-1 | aiosession: Optional[aiohttp.ClientSession] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python packag... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
08ca5ff35a13-2 | else:
async with self.aiosession.get(url, params=params) as response:
res = await response.json()
return self._process_response(res)
[docs] def run(self, query: str) -> str:
"""Run query through SerpAPI and parse result."""
return self._process_response(self.result... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
08ca5ff35a13-3 | ):
toret = res["answer_box"]["snippet_highlighted_words"][0]
elif (
"sports_results" in res.keys()
and "game_spotlight" in res["sports_results"].keys()
):
toret = res["sports_results"]["game_spotlight"]
elif (
"knowledge_graph" in res.k... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
d631815ce0d7-0 | Source code for langchain.utilities.searx_search
"""Utility for using SearxNG meta search API.
SearxNG is a privacy-friendly free metasearch engine that aggregates results from
`multiple search engines
<https://docs.searxng.org/admin/engines/configured_engines.html>`_ and databases and
supports the `OpenSearch
<https:... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
d631815ce0d7-1 | Other methods are are available for convenience.
:class:`SearxResults` is a convenience wrapper around the raw json result.
Example usage of the ``run`` method to make a search:
.. code-block:: python
s.run(query="what is the best search engine?")
Engine Parameters
-----------------
You can pass any `accept... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
d631815ce0d7-2 | .. code-block:: python
# select the github engine and pass the search suffix
s = SearchWrapper("langchain library", query_suffix="!gh")
s = SearchWrapper("langchain library")
# select github the conventional google search syntax
s.run("large language models", query_suffix="site:g... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
d631815ce0d7-3 | return {"language": "en", "format": "json"}
[docs]class SearxResults(dict):
"""Dict like wrapper around search api results."""
_data = ""
def __init__(self, data: str):
"""Take a raw result from Searx and make it into a dict like object."""
json_data = json.loads(data)
super().__init... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
d631815ce0d7-4 | .. code-block:: python
from langchain.utilities import SearxSearchWrapper
# note the unsecure parameter is not needed if you pass the url scheme as
# http
searx = SearxSearchWrapper(searx_host="http://localhost:8888",
un... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
d631815ce0d7-5 | if categories:
values["params"]["categories"] = ",".join(categories)
searx_host = get_from_dict_or_env(values, "searx_host", "SEARX_HOST")
if not searx_host.startswith("http"):
print(
f"Warning: missing the url scheme on host \
! assuming secure ht... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
d631815ce0d7-6 | ) as response:
if not response.ok:
raise ValueError("Searx API returned an error: ", response.text)
result = SearxResults(await response.text())
self._result = result
else:
async with self.aiosession.get(
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
d631815ce0d7-7 | searx.run("what is the weather in France ?", engine="qwant")
# the same result can be achieved using the `!` syntax of searx
# to select the engine using `query_suffix`
searx.run("what is the weather in France ?", query_suffix="!qwant")
"""
_params = {
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
d631815ce0d7-8 | ) -> str:
"""Asynchronously version of `run`."""
_params = {
"q": query,
}
params = {**self.params, **_params, **kwargs}
if self.query_suffix and len(self.query_suffix) > 0:
params["q"] += " " + self.query_suffix
if isinstance(query_suffix, str) an... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
d631815ce0d7-9 | categories: List of categories to use for the query.
**kwargs: extra parameters to pass to the searx API.
Returns:
Dict with the following keys:
{
snippet: The description of the result.
title: The title of the result.
link: T... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
d631815ce0d7-10 | self,
query: str,
num_results: int,
engines: Optional[List[str]] = None,
query_suffix: Optional[str] = "",
**kwargs: Any,
) -> List[Dict]:
"""Asynchronously query with json results.
Uses aiohttp. See `results` for more info.
"""
_params = {
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
1668fbd34c89-0 | Source code for langchain.chains.llm_requests
"""Chain that hits a URL and then uses an LLM to parse results."""
from __future__ import annotations
from typing import Dict, List
from pydantic import Extra, Field, root_validator
from langchain.chains import LLMChain
from langchain.chains.base import Chain
from langchain... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
1668fbd34c89-1 | """
return [self.output_key]
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
try:
from bs4 import BeautifulSoup # noqa: F401
except ImportError:
raise ValueError(... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
9ae9139cdd3a-0 | Source code for langchain.chains.llm
"""Chain that just formats a prompt and calls an LLM."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
from pydantic import Extra
from langchain.chains.base import Chain
from langchain.input import get_colored_text
from langc... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
9ae9139cdd3a-1 | return self.apply([inputs])[0]
[docs] def generate(self, input_list: List[Dict[str, Any]]) -> LLMResult:
"""Generate LLM result from inputs."""
prompts, stop = self.prep_prompts(input_list)
return self.llm.generate_prompt(prompts, stop)
[docs] async def agenerate(self, input_list: List[Dic... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
9ae9139cdd3a-2 | self, input_list: List[Dict[str, Any]]
) -> Tuple[List[PromptValue], Optional[List[str]]]:
"""Prepare prompts from inputs."""
stop = None
if "stop" in input_list[0]:
stop = input_list[0]["stop"]
prompts = []
for inputs in input_list:
selected_inputs = ... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
9ae9139cdd3a-3 | """Create outputs from response."""
return [
# Get the text of the top generated string.
{self.output_key: generation[0].text}
for generation in response.generations
]
async def _acall(self, inputs: Dict[str, Any]) -> Dict[str, str]:
return (await self.aap... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
9ae9139cdd3a-4 | ) -> Union[str, List[str], Dict[str, str]]:
"""Call apredict and then parse the results."""
result = await self.apredict(**kwargs)
if self.prompt.output_parser is not None:
return self.prompt.output_parser.parse(result)
else:
return result
[docs] def apply_and_... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
9ae9139cdd3a-5 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
513710abf2ef-0 | Source code for langchain.chains.moderation
"""Pass input through a moderation endpoint."""
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.chains.base import Chain
from langchain.utils import get_from_dict_or_env
[docs]class OpenAIModerationChain(Chain):
"""Pass inpu... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
513710abf2ef-1 | "OPENAI_ORGANIZATION",
default="",
)
try:
import openai
openai.api_key = openai_api_key
if openai_organization:
openai.organization = openai_organization
values["client"] = openai.Moderation
except ImportError:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
0d9818bdbfac-0 | Source code for langchain.chains.mapreduce
"""Map-reduce chain.
Splits up a document, sends the smaller parts to the LLM with one prompt,
then combines the results with another one.
"""
from __future__ import annotations
from typing import Dict, List
from pydantic import Extra
from langchain.chains.base import Chain
fr... | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
0d9818bdbfac-1 | )
return cls(
combine_documents_chain=combine_documents_chain, text_splitter=text_splitter
)
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@property
def input_keys(self) -> List[str]:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
00bd03e1353c-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 |
00bd03e1353c-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 |
00bd03e1353c-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 |
00bd03e1353c-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 |
00bd03e1353c-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 |
00bd03e1353c-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 |
00bd03e1353c-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 |
00bd03e1353c-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 |
00bd03e1353c-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 |
00bd03e1353c-9 | if "combine_documents_chain" in config:
combine_documents_chain_config = config.pop("combine_documents_chain")
combine_documents_chain = load_chain_from_config(combine_documents_chain_config)
elif "combine_documents_chain_path" in config:
combine_documents_chain = load_chain(config.pop("comb... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
00bd03e1353c-10 | api_request_chain = load_chain_from_config(api_request_chain_config)
elif "api_request_chain_path" in config:
api_request_chain = load_chain(config.pop("api_request_chain_path"))
else:
raise ValueError(
"One of `api_request_chain` or `api_request_chain_path` must be present."
... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
00bd03e1353c-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 |
00bd03e1353c-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 |
00bd03e1353c-13 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
a38900c2acc8-0 | Source code for langchain.chains.transform
"""Chain that runs an arbitrary python function."""
from typing import Callable, Dict, List
from langchain.chains.base import Chain
[docs]class TransformChain(Chain):
"""Chain transform chain output.
Example:
.. code-block:: python
from langchain im... | https://python.langchain.com/en/latest/_modules/langchain/chains/transform.html |
16434bc1d5b4-0 | Source code for langchain.chains.sequential
"""Chain pipeline where the outputs of one step feed directly into next."""
from typing import Dict, List
from pydantic import Extra, root_validator
from langchain.chains.base import Chain
from langchain.input import get_color_mapping
[docs]class SequentialChain(Chain):
"... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
16434bc1d5b4-1 | f"in the Memory keys ({memory_keys}) - please use input and "
f"memory keys that don't overlap."
)
known_variables = set(input_variables + memory_keys)
for chain in chains:
missing_vars = set(chain.input_keys).difference(known_variables)
if mis... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
16434bc1d5b4-2 | chains: List[Chain]
strip_outputs: bool = False
input_key: str = "input" #: :meta private:
output_key: str = "output" #: :meta private:
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@property
def input_ke... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
16434bc1d5b4-3 | if self.strip_outputs:
_input = _input.strip()
self.callback_manager.on_text(
_input, color=color_mapping[str(i)], end="\n", verbose=self.verbose
)
return {self.output_key: _input}
By Harrison Chase
© Copyright 2023, Harrison Chase.
Las... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
43462b196af2-0 | Source code for langchain.chains.constitutional_ai.base
"""Chain for applying constitutional principles to the outputs of another chain."""
from typing import Any, Dict, List, Optional
from langchain.chains.base import Chain
from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple
from langchain.ch... | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
43462b196af2-1 | ) -> List[ConstitutionalPrinciple]:
if names is None:
return list(PRINCIPLES.values())
else:
return [PRINCIPLES[name] for name in names]
[docs] @classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
chain: LLMChain,
critique_prompt: BasePro... | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
43462b196af2-2 | input_prompt=input_prompt,
output_from_model=response,
critique_request=constitutional_principle.critique_request,
)
critique = self._parse_critique(
output_string=raw_critique,
).strip()
# Do revision
revision =... | https://python.langchain.com/en/latest/_modules/langchain/chains/constitutional_ai/base.html |
a8feae3fedff-0 | Source code for langchain.chains.api.base
"""Chain that makes API calls and summarizes the responses to answer a question."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Field, root_validator
from langchain.chains.api.prompt import API_RESPONSE_PROMPT, API_URL_PR... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
a8feae3fedff-1 | )
return values
@root_validator(pre=True)
def validate_api_answer_prompt(cls, values: Dict) -> Dict:
"""Check that api answer prompt expects the right variables."""
input_vars = values["api_answer_chain"].prompt.input_variables
expected_vars = {"question", "api_docs", "api_url", ... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
a8feae3fedff-2 | self.callback_manager.on_text(
api_response, color="yellow", end="\n", verbose=self.verbose
)
answer = await self.api_answer_chain.apredict(
question=question,
api_docs=self.api_docs,
api_url=api_url,
api_response=api_response,
)
... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/base.html |
a881d104ed9e-0 | Source code for langchain.chains.api.openapi.chain
"""Chain that makes API calls and summarizes the responses to answer a question."""
from __future__ import annotations
import json
from typing import Any, Dict, List, NamedTuple, Optional, cast
from pydantic import BaseModel, Field
from requests import Response
from la... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
a881d104ed9e-1 | @property
def output_keys(self) -> List[str]:
"""Expect output key.
:meta private:
"""
if not self.return_intermediate_steps:
return [self.output_key]
else:
return [self.output_key, "intermediate_steps"]
def _construct_path(self, args: Dict[str, st... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
a881d104ed9e-2 | body_params = self._extract_body_params(args)
query_params = self._extract_query_params(args)
return {
"url": path,
"data": body_params,
"params": query_params,
}
def _get_output(self, output: str, intermediate_steps: dict) -> dict:
"""Return the o... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
a881d104ed9e-3 | response_text = (
f"{api_response.status_code}: {api_response.reason}"
+ f"\nFor {method_str.upper()} {request_args['url']}\n"
+ f"Called with args: {request_args['params']}"
)
else:
response_text = api_response.tex... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
a881d104ed9e-4 | operation,
requests=requests,
llm=llm,
return_intermediate_steps=return_intermediate_steps,
**kwargs,
)
[docs] @classmethod
def from_api_operation(
cls,
operation: APIOperation,
llm: BaseLLM,
requests: Optional[Requests] = No... | https://python.langchain.com/en/latest/_modules/langchain/chains/api/openapi/chain.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.