id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 53 121 |
|---|---|---|
a60ce9173993-4 | """Save the prompt.
Args:
file_path: Path to directory to save prompt to.
Example:
.. code-block:: python
prompt.save(file_path="path/prompt.yaml")
"""
if self.partial_variables:
raise ValueError("Cannot save prompt with partial variables.")
... | https://api.python.langchain.com/en/stable/_modules/langchain/prompts/base.html |
0f30ba1ef8b0-0 | Source code for langchain.prompts.example_selector.semantic_similarity
"""Example selector that selects examples based on SemanticSimilarity."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseModel, Extra
from langchain.embeddings.base import Embeddings
fr... | https://api.python.langchain.com/en/stable/_modules/langchain/prompts/example_selector/semantic_similarity.html |
0f30ba1ef8b0-1 | return ids[0]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use based on semantic similarity."""
# Get the docs with the highest similarity.
if self.input_keys:
input_variables = {key: input_variables[key] for key in s... | https://api.python.langchain.com/en/stable/_modules/langchain/prompts/example_selector/semantic_similarity.html |
0f30ba1ef8b0-2 | instead of all variables.
vectorstore_cls_kwargs: optional kwargs containing url for vector store
Returns:
The ExampleSelector instantiated, backed by a vector store.
"""
if input_keys:
string_examples = [
" ".join(sorted_values({k: eg[k] for k... | https://api.python.langchain.com/en/stable/_modules/langchain/prompts/example_selector/semantic_similarity.html |
0f30ba1ef8b0-3 | examples = [dict(e.metadata) for e in example_docs]
# If example keys are provided, filter examples to those keys.
if self.example_keys:
examples = [{k: eg[k] for k in self.example_keys} for eg in examples]
return examples
[docs] @classmethod
def from_examples(
cls,
... | https://api.python.langchain.com/en/stable/_modules/langchain/prompts/example_selector/semantic_similarity.html |
0f30ba1ef8b0-4 | )
return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys) | https://api.python.langchain.com/en/stable/_modules/langchain/prompts/example_selector/semantic_similarity.html |
c8660bcafc74-0 | Source code for langchain.prompts.example_selector.ngram_overlap
"""Select and order examples based on ngram overlap score (sentence_bleu score).
https://www.nltk.org/_modules/nltk/translate/bleu_score.html
https://aclanthology.org/P02-1040.pdf
"""
from typing import Dict, List
import numpy as np
from pydantic import B... | https://api.python.langchain.com/en/stable/_modules/langchain/prompts/example_selector/ngram_overlap.html |
c8660bcafc74-1 | """
examples: List[dict]
"""A list of the examples that the prompt template expects."""
example_prompt: PromptTemplate
"""Prompt template used to format the examples."""
threshold: float = -1.0
"""Threshold at which algorithm stops. Set to -1.0 by default.
For negative threshold:
select_... | https://api.python.langchain.com/en/stable/_modules/langchain/prompts/example_selector/ngram_overlap.html |
c8660bcafc74-2 | k = len(self.examples)
score = [0.0] * k
first_prompt_template_key = self.example_prompt.input_variables[0]
for i in range(k):
score[i] = ngram_overlap_score(
inputs, [self.examples[i][first_prompt_template_key]]
)
while True:
arg_max =... | https://api.python.langchain.com/en/stable/_modules/langchain/prompts/example_selector/ngram_overlap.html |
1501a2fdc4e8-0 | Source code for langchain.prompts.example_selector.length_based
"""Select examples based on length."""
import re
from typing import Callable, Dict, List
from pydantic import BaseModel, validator
from langchain.prompts.example_selector.base import BaseExampleSelector
from langchain.prompts.prompt import PromptTemplate
d... | https://api.python.langchain.com/en/stable/_modules/langchain/prompts/example_selector/length_based.html |
1501a2fdc4e8-1 | get_text_length = values["get_text_length"]
string_examples = [example_prompt.format(**eg) for eg in values["examples"]]
return [get_text_length(eg) for eg in string_examples]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use base... | https://api.python.langchain.com/en/stable/_modules/langchain/prompts/example_selector/length_based.html |
459bacb50b1f-0 | Source code for langchain.llms.llamacpp
"""Wrapper around llama.cpp."""
import logging
from typing import Any, Dict, Generator, List, Optional
from pydantic import Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
logger = logging.getLogger(__name... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
459bacb50b1f-1 | f16_kv: bool = Field(True, alias="f16_kv")
"""Use half-precision for key/value cache."""
logits_all: bool = Field(False, alias="logits_all")
"""Return logits for all tokens, not just the last token."""
vocab_only: bool = Field(False, alias="vocab_only")
"""Only load the vocabulary, no weights."""
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
459bacb50b1f-2 | """Whether to echo the prompt."""
stop: Optional[List[str]] = []
"""A list of strings to stop generation when encountered."""
repeat_penalty: Optional[float] = 1.1
"""The penalty to apply to repeated tokens."""
top_k: Optional[int] = 40
"""The top-k value to use for sampling."""
last_n_token... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
459bacb50b1f-3 | except ImportError:
raise ModuleNotFoundError(
"Could not import llama-cpp-python library. "
"Please install the llama-cpp-python library to "
"use this embedding model: pip install llama-cpp-python"
)
except Exception as e:
rai... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
459bacb50b1f-4 | Returns:
Dictionary containing the combined parameters.
"""
# Raise error if stop sequences are in both input and default params
if self.stop and stop is not None:
raise ValueError("`stop` found in both the input and default params.")
params = self._default_params... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
459bacb50b1f-5 | return combined_text_output
else:
params = self._get_parameters(stop)
params = {**params, **kwargs}
result = self.client(prompt=prompt, **params)
return result["choices"][0]["text"]
[docs] def stream(
self,
prompt: str,
stop: Optional[Li... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
459bacb50b1f-6 | """
params = self._get_parameters(stop)
result = self.client(prompt=prompt, stream=True, **params)
for chunk in result:
token = chunk["choices"][0]["text"]
log_probs = chunk["choices"][0].get("logprobs", None)
if run_manager:
run_manager.on_llm... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
c55a578dbcf0-0 | Source code for langchain.llms.aleph_alpha
"""Wrapper around Aleph Alpha APIs."""
from typing import Any, Dict, List, Optional, Sequence
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforc... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/aleph_alpha.html |
c55a578dbcf0-1 | """Total probability mass of tokens to consider at each step."""
presence_penalty: float = 0.0
"""Penalizes repeated tokens."""
frequency_penalty: float = 0.0
"""Penalizes repeated tokens according to frequency."""
repetition_penalties_include_prompt: Optional[bool] = False
"""Flag deciding whet... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/aleph_alpha.html |
c55a578dbcf0-2 | echo: bool = False
"""Echo the prompt in the completion."""
use_multiplicative_frequency_penalty: bool = False
sequence_penalty: float = 0.0
sequence_penalty_min_length: int = 2
use_multiplicative_sequence_penalty: bool = False
completion_bias_inclusion: Optional[Sequence[str]] = None
comple... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/aleph_alpha.html |
c55a578dbcf0-3 | """Validate that api key and python package exists in environment."""
aleph_alpha_api_key = get_from_dict_or_env(
values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY"
)
try:
import aleph_alpha_client
values["client"] = aleph_alpha_client.Client(token=aleph_alp... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/aleph_alpha.html |
c55a578dbcf0-4 | "minimum_tokens": self.minimum_tokens,
"echo": self.echo,
"use_multiplicative_frequency_penalty": self.use_multiplicative_frequency_penalty, # noqa: E501
"sequence_penalty": self.sequence_penalty,
"sequence_penalty_min_length": self.sequence_penalty_min_length,
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/aleph_alpha.html |
c55a578dbcf0-5 | 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 = aleph_alpha("Tell me a joke.")
"""
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/aleph_alpha.html |
83543ed1924d-0 | Source code for langchain.llms.baseten
"""Wrapper around Baseten deployed model API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Field
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
logger = logging.getLogger(__name__... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/baseten.html |
83543ed1924d-1 | """Return type of model."""
return "baseten"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call to Baseten deployed model endpoint."""
try:
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/baseten.html |
0ac18dbc0d7f-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://api.python.langchain.com/en/stable/_modules/langchain/llms/google_palm.html |
0ac18dbc0d7f-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://api.python.langchain.com/en/stable/_modules/langchain/llms/google_palm.html |
0ac18dbc0d7f-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://api.python.langchain.com/en/stable/_modules/langchain/llms/google_palm.html |
0ac18dbc0d7f-3 | return values
def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
generations = []
for prompt in prompts:
completion = generate_with_r... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/google_palm.html |
a4096d1a64b7-0 | Source code for langchain.llms.stochasticai
"""Wrapper around StochasticAI APIs."""
import logging
import time
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/stochasticai.html |
a4096d1a64b7-1 | raise ValueError(f"Found {field_name} supplied twice.")
logger.warning(
f"""{field_name} was transfered to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/stochasticai.html |
a4096d1a64b7-2 | response = StochasticAI("Tell me a joke.")
"""
params = self.model_kwargs or {}
params = {**params, **kwargs}
response_post = requests.post(
url=self.api_url,
json={"prompt": prompt, "params": params},
headers={
"apiKey": f"{self.stocha... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/stochasticai.html |
a5eb6eb3dd42-0 | Source code for langchain.llms.cohere
"""Wrapper around Cohere APIs."""
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
from pydantic import Extra, root_validator
from tenacity import (
before_sleep_log,
retry,
retry_if_exception_type,
stop_after_... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/cohere.html |
a5eb6eb3dd42-1 | """Wrapper around Cohere large language models.
To use, you should have the ``cohere`` python package installed, and the
environment variable ``COHERE_API_KEY`` set with your API key, or pass
it as a named parameter to the constructor.
Example:
.. code-block:: python
from langchain.l... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/cohere.html |
a5eb6eb3dd42-2 | extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
cohere_api_key = get_from_dict_or_env(
values, "cohere_api_key", "COHERE_API_KEY"
)
try:
impor... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/cohere.html |
a5eb6eb3dd42-3 | """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.
Returns:
The string generated by the model.
Example:
.. code-block:: python
respon... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/cohere.html |
c3901ee268dd-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://api.python.langchain.com/en/stable/_modules/langchain/llms/openlm.html |
46807d7501fe-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://api.python.langchain.com/en/stable/_modules/langchain/llms/replicate.html |
46807d7501fe-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://api.python.langchain.com/en/stable/_modules/langchain/llms/replicate.html |
46807d7501fe-2 | try:
import replicate as replicate_python
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_st... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/replicate.html |
3649d7557b8c-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://api.python.langchain.com/en/stable/_modules/langchain/llms/predictionguard.html |
3649d7557b8c-1 | """Your Prediction Guard access token."""
stop: Optional[List[str]] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that the access token and python package ... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/predictionguard.html |
3649d7557b8c-2 | Returns:
The string generated by the model.
Example:
.. code-block:: python
response = pgllm("Tell me a joke.")
"""
import predictionguard as pg
params = self._default_params
if self.stop is not None and stop is not None:
raise ... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/predictionguard.html |
90edc622ea12-0 | Source code for langchain.llms.manifest
"""Wrapper around HazyResearch's Manifest library."""
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
[docs]class ManifestWrapper(... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/manifest.html |
90edc622ea12-1 | if stop is not None and len(stop) != 1:
raise NotImplementedError(
f"Manifest currently only supports a single stop token, got {stop}"
)
params = self.llm_kwargs or {}
params = {**params, **kwargs}
if stop is not None:
params["stop_token"] = st... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/manifest.html |
23b6877a5bd3-0 | Source code for langchain.llms.sagemaker_endpoint
"""Wrapper around Sagemaker InvokeEndpoint API."""
from abc import abstractmethod
from typing import Any, Dict, Generic, List, Mapping, Optional, TypeVar, Union
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
f... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html |
23b6877a5bd3-1 | """The MIME type of the response data returned from endpoint"""
@abstractmethod
def transform_input(self, prompt: INPUT_TYPE, model_kwargs: Dict) -> bytes:
"""Transforms the input to a format that model can accept
as the request Body. Should return bytes or seekable file
like object in t... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html |
23b6877a5bd3-2 | )
credentials_profile_name = (
"default"
)
se = SagemakerEndpoint(
endpoint_name=endpoint_name,
region_name=region_name,
credentials_profile_name=credentials_profile_name
)
"""
client: Any #: :meta p... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html |
23b6877a5bd3-3 | def transform_output(self, output: bytes) -> str:
response_json = json.loads(output.read().decode("utf-8"))
return response_json[0]["generated_text"]
"""
model_kwargs: Optional[Dict] = None
"""Key word arguments to pass to the model."""
endpoint_kwargs: Optional[D... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html |
23b6877a5bd3-4 | @property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {
**{"endpoint_name": self.endpoint_name},
**{"model_kwargs": _model_kwargs},
}
@property
def _llm_type(s... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html |
23b6877a5bd3-5 | text = self.content_handler.transform_output(response["Body"])
if stop is not None:
# This is a bit hacky, but I can't figure out a better way to enforce
# stop tokens when making calls to the sagemaker endpoint.
text = enforce_stop_tokens(text, stop)
return text | https://api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html |
5d2411d9ff03-0 | Source code for langchain.llms.gooseai
"""Wrapper around GooseAI 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 import... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/gooseai.html |
5d2411d9ff03-1 | presence_penalty: float = 0
"""Penalizes repeated tokens."""
n: int = 1
"""How many completions to generate for each prompt."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
logit_bias: Optional[Dict[... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/gooseai.html |
5d2411d9ff03-2 | )
try:
import openai
openai.api_key = gooseai_api_key
openai.api_base = "https://api.goose.ai/v1"
values["client"] = openai.Completion
except ImportError:
raise ImportError(
"Could not import openai python package. "
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/gooseai.html |
5d2411d9ff03-3 | if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
params = {**params, **kwargs}
response = self.client.create(engine=self.model_name, prompt=prompt, **params)
text = respo... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/gooseai.html |
fd190dadca59-0 | Source code for langchain.llms.textgen
"""Wrapper around text-generation-webui."""
import logging
from typing import Any, Dict, List, Optional
import requests
from pydantic import Field
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
logger = logging.getLogger(__name... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/textgen.html |
fd190dadca59-1 | number. Higher value = higher range of possible random results."""
typical_p: Optional[float] = 1
"""If not set to 1, select only tokens that are at least this much more likely to
appear than random tokens, given the prior text."""
epsilon_cutoff: Optional[float] = 0 # In units of 1e-4
"""Epsilon c... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/textgen.html |
fd190dadca59-2 | """Seed (-1 for random)"""
add_bos_token: bool = Field(True, alias="add_bos_token")
"""Add the bos_token to the beginning of prompts.
Disabling this can make the replies more creative."""
truncation_length: Optional[int] = 2048
"""Truncate the prompt up to this length. The leftmost tokens are remove... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/textgen.html |
fd190dadca59-3 | "num_beams": self.num_beams,
"penalty_alpha": self.penalty_alpha,
"length_penalty": self.length_penalty,
"early_stopping": self.early_stopping,
"seed": self.seed,
"add_bos_token": self.add_bos_token,
"truncation_length": self.truncation_length,
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/textgen.html |
fd190dadca59-4 | return params
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call the textgen web API and return the output.
Args:
prompt: The prompt to use fo... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/textgen.html |
74fc194f94c3-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.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.utils import get_from_dict_or_e... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/nlpcloud.html |
74fc194f94c3-1 | """Total probability mass of tokens to consider at each step."""
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 t... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/nlpcloud.html |
74fc194f94c3-2 | @property
def _default_params(self) -> Mapping[str, Any]:
"""Get the default parameters for calling NLPCloud API."""
return {
"temperature": self.temperature,
"min_length": self.min_length,
"max_length": self.max_length,
"length_no_input": self.length_... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/nlpcloud.html |
74fc194f94c3-3 | Returns:
The string generated by the model.
Example:
.. code-block:: python
response = nlpcloud("Tell me a joke.")
"""
if stop and len(stop) > 1:
raise ValueError(
"NLPCloud only supports a single stop sequence per generation."
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/nlpcloud.html |
c89ab3aa6510-0 | Source code for langchain.llms.bananadev
"""Wrapper around Banana 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.llms.utils ... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/bananadev.html |
c89ab3aa6510-1 | if field_name not in all_required_field_names:
if field_name in extra:
raise ValueError(f"Found {field_name} supplied twice.")
logger.warning(
f"""{field_name} was transfered to model_kwargs.
Please confirm that {field_name} is ... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/bananadev.html |
c89ab3aa6510-2 | )
params = self.model_kwargs or {}
params = {**params, **kwargs}
api_key = self.banana_api_key
model_key = self.model_key
model_inputs = {
# a json specific to your model.
"prompt": prompt,
**params,
}
response = banana.run(api_... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/bananadev.html |
8148e406ff9b-0 | Source code for langchain.llms.beam
"""Wrapper around Beam API."""
import base64
import json
import logging
import subprocess
import textwrap
import time
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import Callba... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html |
8148e406ff9b-1 | max_length=50)
llm._deploy()
call_result = llm._call(input)
"""
model_name: str = ""
name: str = ""
cpu: str = ""
memory: str = ""
gpu: str = ""
python_version: str = ""
python_packages: List[str] = []
max_length: str = ""
url: str = ""
"""model endpoi... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html |
8148e406ff9b-2 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
beam_client_id = get_from_dict_or_env(
values, "beam_client_id", "BEAM_CLIENT_ID"
)
beam_client_secret = get_from_dict_or_env(
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html |
8148e406ff9b-3 | python_packages={python_packages},
)
app.Trigger.RestAPI(
inputs={{"prompt": beam.Types.String(), "max_length": beam.Types.String()}},
outputs={{"text": beam.Types.String()}},
handler="run.py:beam_langchain",
)
"""
)
script_name = "app.... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html |
8148e406ff9b-4 | file.write(script.format(model_name=self.model_name))
def _deploy(self) -> str:
"""Call to Beam."""
try:
import beam # type: ignore
if beam.__path__ == "":
raise ImportError
except ImportError:
raise ImportError(
"Could not... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html |
8148e406ff9b-5 | self,
prompt: str,
stop: Optional[list] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call to Beam."""
url = "https://apps.beam.cloud/" + self.app_id if self.app_id else self.url
payload = {"prompt": prompt, "max_l... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html |
8945179c5c08-0 | Source code for langchain.llms.gpt4all
"""Wrapper for the GPT4All model."""
from functools import partial
from typing import Any, Dict, List, Mapping, Optional, Set
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/gpt4all.html |
8945179c5c08-1 | logits_all: bool = Field(False, alias="logits_all")
"""Return logits for all tokens, not just the last token."""
vocab_only: bool = Field(False, alias="vocab_only")
"""Only load the vocabulary, no weights."""
use_mlock: bool = Field(False, alias="use_mlock")
"""Force system to keep model in RAM."""
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/gpt4all.html |
8945179c5c08-2 | starting from beginning if the context has run out."""
allow_download: bool = False
"""If model does not exist in ~/.cache/gpt4all/, download it."""
client: Any = None #: :meta private:
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@staticmethod
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/gpt4all.html |
8945179c5c08-3 | model_path += delimiter
values["client"] = GPT4AllModel(
model_name,
model_path=model_path or None,
model_type=values["backend"],
allow_download=values["allow_download"],
)
if values["n_threads"] is not None:
# set n_threads
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/gpt4all.html |
8945179c5c08-4 | The string generated by the model.
Example:
.. code-block:: python
prompt = "Once upon a time, "
response = model(prompt, n_predict=55)
"""
text_callback = None
if run_manager:
text_callback = partial(run_manager.on_llm_new_token, v... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/gpt4all.html |
605d7c6152e7-0 | Source code for langchain.llms.mosaicml
"""Wrapper around MosaicML 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.llms.utils impo... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/mosaicml.html |
605d7c6152e7-1 | )
"""
endpoint_url: str = (
"https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict"
)
"""Endpoint URL to use."""
inject_instruction_format: bool = False
"""Whether to inject the instruction format into the prompt."""
model_kwargs: Optional[dict] = None
"""Key word ... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/mosaicml.html |
605d7c6152e7-2 | instruction=prompt,
)
return prompt
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
is_retry: bool = False,
**kwargs: Any,
) -> str:
"""Call out to a MosaicML LLM i... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/mosaicml.html |
605d7c6152e7-3 | raise ValueError(
f"Error raised by inference API: {parsed_response['error']}"
)
# The inference API has changed a couple of times, so we add some handling
# to be robust to multiple response formats.
if isinstance(parsed_response, dict):
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/mosaicml.html |
eee368c406df-0 | Source code for langchain.llms.self_hosted_hugging_face
"""Wrapper around HuggingFace Pipeline API to run on self-hosted remote hardware."""
import importlib.util
import logging
from typing import Any, Callable, List, Mapping, Optional
from pydantic import Extra
from langchain.callbacks.manager import CallbackManagerFo... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted_hugging_face.html |
eee368c406df-1 | text = enforce_stop_tokens(text, stop)
return text
def _load_transformer(
model_id: str = DEFAULT_MODEL_ID,
task: str = DEFAULT_TASK,
device: int = 0,
model_kwargs: Optional[dict] = None,
) -> Any:
"""Inference function to send to the remote hardware.
Accepts a huggingface model_id and retur... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted_hugging_face.html |
eee368c406df-2 | )
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 ass... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted_hugging_face.html |
eee368c406df-3 | hf = SelfHostedHuggingFaceLLM(
model_id="google/flan-t5-large", task="text2text-generation",
hardware=gpu
)
Example passing fn that generates a pipeline (bc the pipeline is not serializable):
.. code-block:: python
from langchain.llms import SelfHosted... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted_hugging_face.html |
eee368c406df-4 | """Function to load the model remotely on the server."""
inference_fn: Callable = _generate_text #: :meta private:
"""Inference function to send to the remote hardware."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
def __init__(self, **kwargs: Any):... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted_hugging_face.html |
d0f04c1e0da2-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.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import e... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/writer.html |
d0f04c1e0da2-1 | logprobs: bool = False
"""Whether to return log probabilities."""
n: Optional[int] = None
"""How many completions to generate."""
writer_api_key: Optional[str] = None
"""Writer API key."""
base_url: Optional[str] = None
"""Base url to use, if None decides based on model name."""
class Co... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/writer.html |
d0f04c1e0da2-2 | """Get the identifying parameters."""
return {
**{"model_id": self.model_id, "writer_org_id": self.writer_org_id},
**self._default_params,
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "writer"
def _call(
self,
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/writer.html |
d0f04c1e0da2-3 | # are not enforced by the model parameters
text = enforce_stop_tokens(text, stop)
return text | https://api.python.langchain.com/en/stable/_modules/langchain/llms/writer.html |
3668e65b91b2-0 | Source code for langchain.llms.modal
"""Wrapper around Modal API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/modal.html |
3668e65b91b2-1 | logger.warning(
f"""{field_name} was transfered to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
values["model_kwargs"] = extra
return values
@property
d... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/modal.html |
a3163e17a119-0 | Source code for langchain.llms.huggingface_hub
"""Wrapper around HuggingFace APIs."""
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enf... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_hub.html |
a3163e17a119-1 | """Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
huggingfacehub_api_token = get_from_dict_or_env(
values, "huggingfac... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_hub.html |
a3163e17a119-2 | prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_hub.html |
04608db2e52c-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.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils im... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/deepinfra.html |
04608db2e52c-1 | return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"model_id": self.model_id},
**{"model_kwargs": self.model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type ... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/deepinfra.html |
04608db2e52c-2 | if res.status_code != 200:
raise ValueError(
"Error raised by inference API HTTP code: %s, %s"
% (res.status_code, res.text)
)
try:
t = res.json()
text = t["results"][0]["generated_text"]
except requests.exceptions.JSONDecod... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/deepinfra.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.