id stringlengths 14 16 | text stringlengths 44 2.73k | source stringlengths 49 115 |
|---|---|---|
0ebce49197db-5 | return result["choices"][0]["text"]
[docs] def stream(
self, prompt: str, stop: Optional[List[str]] = None
) -> Generator[Dict, None, None]:
"""Yields results objects as they are generated in real time.
BETA: this is a beta feature while we figure out the right abstraction:
Once t... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
0ebce49197db-6 | token=token, verbose=self.verbose, log_probs=log_probs
)
yield chunk
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
7f2e80afc38e-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.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
logger = logging.getLogger(... | https://python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
7f2e80afc38e-1 | Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
values["model_kwargs"] = extra
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
... | https://python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
c15c17382cb4-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.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dict_or_env
[d... | https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
c15c17382cb4-1 | 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 whether presence penalty or frequency penalty are
updated from the pr... | https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
c15c17382cb4-2 | sequence_penalty: float = 0.0
sequence_penalty_min_length: int = 2
use_multiplicative_sequence_penalty: bool = False
completion_bias_inclusion: Optional[Sequence[str]] = None
completion_bias_inclusion_first_token_only: bool = False
completion_bias_exclusion: Optional[Sequence[str]] = None
comple... | https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
c15c17382cb4-3 | values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY"
)
try:
import aleph_alpha_client
values["client"] = aleph_alpha_client.Client(token=aleph_alpha_api_key)
except ImportError:
raise ValueError(
"Could not import aleph_alpha_client python pack... | https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
c15c17382cb4-4 | "sequence_penalty": self.sequence_penalty,
"sequence_penalty_min_length": self.sequence_penalty_min_length,
"use_multiplicative_sequence_penalty": self.use_multiplicative_sequence_penalty, # noqa: E501
"completion_bias_inclusion": self.completion_bias_inclusion,
"complet... | https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
c15c17382cb4-5 | from aleph_alpha_client import CompletionRequest, Prompt
params = self._default_params
if self.stop_sequences is not None and stop is not None:
raise ValueError(
"stop sequences found in both the input and default params."
)
elif self.stop_sequences is not... | https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
cadd7ab433a2-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.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dict_or_env... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
cadd7ab433a2-1 | @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, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
)
try:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
cadd7ab433a2-2 | 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 = hf("Tell me a joke.")
"""
_mod... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
35f0d3099095-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 |
35f0d3099095-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 |
35f0d3099095-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 |
35f0d3099095-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 |
854828554a54-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.llms.base import LLM
from langchain.utils import get_from_dict_or_env
logger = logging.getLogger(__name__)
[docs]... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
854828554a54-1 | """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[str, float]] = Field(default_fac... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
854828554a54-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 ValueError(
"Could not import openai python package. "
... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
854828554a54-3 | params["stop"] = stop
response = self.client.create(engine=self.model_name, prompt=prompt, **params)
text = response.choices[0].text
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
d7ea02e50014-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.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_d... | https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
d7ea02e50014-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://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
d7ea02e50014-2 | "prompt": prompt,
**params,
}
response = banana.run(api_key, model_key, model_inputs)
try:
text = response["modelOutputs"][0]["output"]
except (KeyError, TypeError):
returned = response["modelOutputs"][0]
raise ValueError(
"... | https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
6834867e8d14-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 |
6834867e8d14-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 |
6834867e8d14-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 |
6834867e8d14-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 |
5ffc98239a56-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 |
5ffc98239a56-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 |
5ffc98239a56-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 |
5ffc98239a56-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 |
ddcfd83b3210-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.llms.base import LLM
from langchain.utils import get_from_dict_or_env
logger = logging.getLogger(__name__)
[d... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
ddcfd83b3210-1 | """Build extra kwargs from additional params that were passed in."""
all_required_field_names = {field.alias for field in cls.__fields__.values()}
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if ... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
ddcfd83b3210-2 | )
# get the model and version
model_str, version_str = self.model.split(":")
model = replicate_python.models.get(model_str)
version = model.versions.get(version_str)
# sort through the openapi schema to get the name of the first input
input_properties = sorted(
... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
548d62ed0e10-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.llms.self_hosted import SelfHostedPipeline... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
548d62ed0e10-1 | 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 returns a pipeline for the task.
"""
from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokeni... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
548d62ed0e10-2 | "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 with CUDA device id.",
cuda_device_count,
)
pipeline = hf_pipeline(
task=task,
model=mod... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
548d62ed0e10-3 | .. code-block:: python
from langchain.llms import SelfHostedHuggingFaceLLM
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import runhouse as rh
def get_pipeline():
model_id = "gpt2"
tokenizer = AutoTokenizer.from_pre... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
548d62ed0e10-4 | extra = Extra.forbid
def __init__(self, **kwargs: Any):
"""Construct the pipeline remotely using an auxiliary function.
The load function needs to be importable to be imported
and run on the server, i.e. in a module and not a REPL or closure.
Then, initialize the remote inference fun... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
86729ca7f067-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.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
... | https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
86729ca7f067-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://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
86729ca7f067-2 | json={"prompt": prompt, "params": params},
headers={
"apiKey": f"{self.stochasticai_api_key}",
"Accept": "application/json",
"Content-Type": "application/json",
},
)
response_post.raise_for_status()
response_post_json = resp... | https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
085f352972ed-0 | Source code for langchain.llms.forefrontai
"""Wrapper around ForefrontAI 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... | https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
085f352972ed-1 | """Validate that api key exists in environment."""
forefrontai_api_key = get_from_dict_or_env(
values, "forefrontai_api_key", "FOREFRONTAI_API_KEY"
)
values["forefrontai_api_key"] = forefrontai_api_key
return values
@property
def _default_params(self) -> Mapping[str, ... | https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
085f352972ed-2 | },
json={"text": prompt, **self._default_params},
)
response_json = response.json()
text = response_json["result"][0]["completion"]
if stop is not None:
# I believe this is required since the stop tokens
# are not enforced by the model parameters
... | https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
8f12e65b4c6d-0 | Source code for langchain.llms.openai
"""Wrapper around OpenAI APIs."""
from __future__ import annotations
import logging
import sys
import warnings
from typing import (
AbstractSet,
Any,
Callable,
Collection,
Dict,
Generator,
List,
Literal,
Mapping,
Optional,
Set,
Tuple,... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-1 | def _streaming_response_template() -> Dict[str, Any]:
return {
"choices": [
{
"text": "",
"finish_reason": None,
"logprobs": None,
}
]
}
def _create_retry_decorator(llm: Union[BaseOpenAI, OpenAIChat]) -> Callable[[Any], Any]... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-2 | ) -> Any:
"""Use tenacity to retry the async completion call."""
retry_decorator = _create_retry_decorator(llm)
@retry_decorator
async def _completion_with_retry(**kwargs: Any) -> Any:
# Use OpenAI's async api https://github.com/openai/openai-python#async-api
return await llm.client.acre... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-3 | openai_organization: Optional[str] = None
batch_size: int = 20
"""Batch size to use when passing multiple documents to generate."""
request_timeout: Optional[Union[float, Tuple[float, float]]] = None
"""Timeout for requests to OpenAI completion API. Default is 600 seconds."""
logit_bias: Optional[Di... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-4 | extra = Extra.ignore
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra kwargs from additional params that were passed in."""
all_required_field_names = {field.alias for field in cls.__fields__.values()}
extra = values.get("model_kwar... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-5 | if openai_organization:
openai.organization = openai_organization
values["client"] = openai.Completion
except ImportError:
raise ValueError(
"Could not import openai python package. "
"Please install it with `pip install openai`."
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-6 | stop: Optional list of stop words to use when generating.
Returns:
The full LLM output.
Example:
.. code-block:: python
response = openai.generate(["Tell me a joke."])
"""
# TODO: write a unit test for this
params = self._invocation_params
... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-7 | self, prompts: List[str], stop: Optional[List[str]] = None
) -> LLMResult:
"""Call out to OpenAI's endpoint async with k unique prompts."""
params = self._invocation_params
sub_prompts = self.get_sub_prompts(params, prompts, stop)
choices = []
token_usage: Dict[str, int] = {}... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-8 | update_token_usage(_keys, response, token_usage)
return self.create_llm_result(choices, prompts, token_usage)
def get_sub_prompts(
self,
params: Dict[str, Any],
prompts: List[str],
stop: Optional[List[str]] = None,
) -> List[List[str]]:
"""Get the sub prompts for ... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-9 | ),
)
for choice in sub_choices
]
)
llm_output = {"token_usage": token_usage, "model_name": self.model_name}
return LLMResult(generations=generations, llm_output=llm_output)
def stream(self, prompt: str, stop: Optional[List[str]] = N... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-10 | """Get the parameters used to invoke the model."""
return self._default_params
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {**{"model_name": self.model_name}, **self._default_params}
@property
def _llm_type(self) -> s... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-11 | """
model_token_mapping = {
"gpt-4": 8192,
"gpt-4-0314": 8192,
"gpt-4-32k": 32768,
"gpt-4-32k-0314": 32768,
"gpt-3.5-turbo": 4096,
"gpt-3.5-turbo-0301": 4096,
"text-ada-001": 2049,
"ada": 2049,
"text-babb... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-12 | Args:
prompt: The prompt to pass into the model.
Returns:
The maximum number of tokens to generate for a prompt.
Example:
.. code-block:: python
max_tokens = openai.max_token_for_prompt("Tell me a joke.")
"""
num_tokens = self.get_num_t... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-13 | .. code-block:: python
from langchain.llms import AzureOpenAI
openai = AzureOpenAI(model_name="text-davinci-003")
"""
deployment_name: str = ""
"""Deployment name to use."""
@property
def _identifying_params(self) -> Mapping[str, Any]:
return {
**{"deploym... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-14 | """Maximum number of retries to make when generating."""
prefix_messages: List = Field(default_factory=list)
"""Series of messages for Chat input."""
streaming: bool = False
"""Whether to stream the results or not."""
allowed_special: Union[Literal["all"], AbstractSet[str]] = set()
"""Set of spe... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-15 | default="",
)
openai_organization = get_from_dict_or_env(
values, "openai_organization", "OPENAI_ORGANIZATION", default=""
)
try:
import openai
openai.api_key = openai_api_key
if openai_api_base:
openai.api_base = openai_api... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-16 | params: Dict[str, Any] = {**{"model": self.model_name}, **self._default_params}
if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
if params.get("max_tokens") == -1:
# ... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-17 | ) -> LLMResult:
messages, params = self._get_chat_params(prompts, stop)
if self.streaming:
response = ""
params["stream"] = True
async for stream_resp in await acompletion_with_retry(
self, messages=messages, **params
):
tok... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
8f12e65b4c6d-18 | # tiktoken NOT supported for Python < 3.8
if sys.version_info[1] < 8:
return super().get_num_tokens(text)
try:
import tiktoken
except ImportError:
raise ValueError(
"Could not import tiktoken python package. "
"This is needed in... | https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
3fa4469d4cf6-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 |
3fa4469d4cf6-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 |
3fa4469d4cf6-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 |
3fa4469d4cf6-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 |
3fa4469d4cf6-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 |
610b5502a1b5-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.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_... | https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
610b5502a1b5-1 | values["client"] = pg.Client(token=token)
except ImportError:
raise ValueError(
"Could not import predictionguard python package. "
"Please install it with `pip install predictionguard`."
)
return values
@property
def _default_params(self) ... | https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
610b5502a1b5-2 | "temperature": params["temperature"],
},
)
text = response["text"]
# If stop tokens are provided, Prediction Guard's endpoint returns them.
# In order to make this consistent with other endpoints, we strip them.
if stop is not None or self.stop is not None:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
6e7c6e5d2fe1-0 | Source code for langchain.llms.huggingface_pipeline
"""Wrapper around HuggingFace Pipeline APIs."""
import importlib.util
import logging
from typing import Any, List, Mapping, Optional
from pydantic import Extra
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
DEFAULT_MODEL_ID = ... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
6e7c6e5d2fe1-1 | """Key word arguments to pass to the model."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
[docs] @classmethod
def from_model_id(
cls,
model_id: str,
task: str,
device: int = -1,
model_kwargs: Optional[dict] = None,
... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
6e7c6e5d2fe1-2 | import torch
cuda_device_count = torch.cuda.device_count()
if device < -1 or (device >= cuda_device_count):
raise ValueError(
f"Got device=={device}, "
f"device is required to be within [-1, {cuda_device_count})"
)
... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
6e7c6e5d2fe1-3 | response = self.pipeline(prompt)
if self.pipeline.task == "text-generation":
# Text generation return includes the starter text.
text = response[0]["generated_text"][len(prompt) :]
elif self.pipeline.task == "text2text-generation":
text = response[0]["generated_text"]... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
8d72005cebb1-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 |
8d72005cebb1-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 |
8d72005cebb1-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 |
8d72005cebb1-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 |
8d72005cebb1-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 |
f7ffae5a9b63-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.llms.base import LLM
from langchain.llms.utils impo... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
f7ffae5a9b63-1 | 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 the format specified in the content_type
request header.
"""
@abstrac... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
f7ffae5a9b63-2 | )
se = SagemakerEndpoint(
endpoint_name=endpoint_name,
region_name=region_name,
credentials_profile_name=credentials_profile_name
)
"""
client: Any #: :meta private:
endpoint_name: str = ""
"""The name of the endpoint from the depl... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
f7ffae5a9b63-3 | 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[Dict] = None
"""Optional attributes passed to the invoke_endpoint
... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
f7ffae5a9b63-4 | """Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {
**{"endpoint_name": self.endpoint_name},
**{"model_kwargs": _model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "sagemaker_e... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
f7ffae5a9b63-5 | text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
6161ce8c1580-0 | Source code for langchain.llms.cerebriumai
"""Wrapper around CerebriumAI 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... | https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
6161ce8c1580-1 | extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if field_name in extra:
raise ValueError(f"Found {field_name} supplied twice.")
logger.warning(
f"""{field_nam... | https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
6161ce8c1580-2 | "Please install it with `pip install cerebrium`."
)
params = self.model_kwargs or {}
response = model_api_request(
self.endpoint_url, {"prompt": prompt, **params}, self.cerebriumai_api_key
)
text = response["data"]["result"]
if stop is not None:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
65604b3dc668-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 |
65604b3dc668-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 |
42adfa90a8f1-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 |
42adfa90a8f1-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 |
42adfa90a8f1-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 |
42adfa90a8f1-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 |
384088897b87-0 | Source code for langchain.llms.anthropic
"""Wrapper around Anthropic APIs."""
import re
import warnings
from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple, Union
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM
from langchain.utils import get_from_... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
384088897b87-1 | )
try:
import anthropic
values["client"] = anthropic.Client(
api_key=anthropic_api_key,
default_request_timeout=values["default_request_timeout"],
)
values["HUMAN_PROMPT"] = anthropic.HUMAN_PROMPT
values["AI_PROMPT"] = a... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
384088897b87-2 | stop.extend([self.HUMAN_PROMPT])
return stop
def get_num_tokens(self, text: str) -> int:
"""Calculate number of tokens."""
if not self.count_tokens:
raise NameError("Please ensure the anthropic package is loaded")
return self.count_tokens(text)
[docs]class Anthropic(LLM, ... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.