id stringlengths 14 16 | text stringlengths 31 3.14k | source stringlengths 58 124 |
|---|---|---|
8287855dad66-3 | n_ctx = values["n_ctx"]
n_parts = values["n_parts"]
seed = values["seed"]
f16_kv = values["f16_kv"]
logits_all = values["logits_all"]
vocab_only = values["vocab_only"]
use_mlock = values["use_mlock"]
n_threads = values["n_threads"]
n_batch = values["n_batc... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
8287855dad66-4 | )
except Exception:
raise NameError(f"Could not load Llama model from path: {model_path}")
return values
@property
def _default_params(self) -> Dict[str, Any]:
"""Get the default parameters for calling llama_cpp."""
return {
"suffix": self.suffix,
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
8287855dad66-5 | 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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
8287855dad66-6 | else:
params = self._get_parameters(stop)
result = self.client(prompt=prompt, **params)
return result["choices"][0]["text"]
[docs] def stream(
self, prompt: str, stop: Optional[List[str]] = None
) -> Generator[Dict, None, None]:
"""Yields results objects as the... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
8287855dad66-7 | """
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)
self.callback_manager.on_llm_new_token(
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
98b6ad15b4a4-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
98b6ad15b4a4-1 | temperature: float = 0.0
"""A non-negative float that tunes the degree of randomness in generation."""
top_k: int = 0
"""Number of most likely tokens to consider at each step."""
top_p: float = 0.0
"""Total probability mass of tokens to consider at each step."""
presence_penalty: float = 0.0
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
98b6ad15b4a4-2 | (highest log probability per token)
"""
n: int = 1
"""How many completions to generate for each prompt."""
logit_bias: Optional[Dict[int, float]] = None
"""The logit bias allows to influence the likelihood of generating tokens."""
log_probs: Optional[int] = None
"""Number of top log probabil... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
98b6ad15b4a4-3 | contextual_control_threshold: Optional[float] = None
"""If set to None, attention control parameters only apply to those tokens that have
explicitly been set in the request.
If set to a non-None value, control parameters are also applied to similar tokens.
"""
control_log_additive: Optional[bool] = ... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
98b6ad15b4a4-4 | )
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 package. "
"Please install it with `pip install a... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
98b6ad15b4a4-5 | "best_of": self.best_of,
"logit_bias": self.logit_bias,
"log_probs": self.log_probs,
"tokens": self.tokens,
"disable_optimizations": self.disable_optimizations,
"minimum_tokens": self.minimum_tokens,
"echo": self.echo,
"use_multiplicati... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
98b6ad15b4a4-6 | "contextual_control_threshold": self.contextual_control_threshold,
"control_log_additive": self.control_log_additive,
"repetition_penalties_include_completion": self.repetition_penalties_include_completion, # noqa: E501
"raw_completion": self.raw_completion,
}
@property
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
98b6ad15b4a4-7 | )
elif self.stop_sequences is not None:
params["stop_sequences"] = self.stop_sequences
else:
params["stop_sequences"] = stop
request = CompletionRequest(prompt=Prompt.from_text(prompt), **params)
response = self.client.complete(model=self.model, request=request)
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
f2df98df83b6-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_... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
f2df98df83b6-1 | extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that the access token and python package exists in environment."""
token = get_from_dict_or_env(values, "token", "PREDICTIONGUARD_TOKEN")
try:
import predictionguard as pg
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
f2df98df83b6-2 | The string generated by the model.
Example:
.. code-block:: python
response = pgllm("Tell me a joke.")
"""
params = self._default_params
if self.stop is not None and stop is not None:
raise ValueError("`stop` found in both the input and default par... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html |
3eb2453c76c6-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
3eb2453c76c6-1 | return response_json[0]["generated_text"]
"""
content_type: Optional[str] = "text/plain"
"""The MIME type of the input data passed to endpoint"""
accepts: Optional[str] = "text/plain"
"""The MIME type of the response data returned from endpoint"""
@abstractmethod
def transform_input(self, pr... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
3eb2453c76c6-2 | If a specific credential profile should be used, you must pass
the name of the profile from the ~/.aws/credentials file that is to be used.
Make sure the credentials / roles used have the required policies to
access the Sagemaker endpoint.
See: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_pol... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
3eb2453c76c6-3 | credentials from IMDS will be used.
See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
"""
content_handler: LLMContentHandler
"""The content handler class that provides an input and
output transform functions to handle formats between LLM
and the endpoint.
""... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
3eb2453c76c6-4 | """
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
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
3eb2453c76c6-5 | """Return type of llm."""
return "sagemaker_endpoint"
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
"""Call out to Sagemaker inference endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when gen... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
b74196913ec8-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
b74196913ec8-1 | model_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model."""
huggingfacehub_api_token: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
b74196913ec8-2 | _model_kwargs = self.model_kwargs or {}
return {
**{"repo_id": self.repo_id, "task": self.task},
**{"model_kwargs": _model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "huggingface_hub"
def _call(self, prompt: str, ... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
b74196913ec8-3 | f"Got invalid task {self.client.task}, "
f"currently only {VALID_TASKS} are supported"
)
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 huggingface_hub.
text = enforce_s... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
a65ffb303310-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
a65ffb303310-1 | random_seed: int = 0
"""The model generates random results.
Changing the random seed alone will produce a different response
with similar characteristics. It is possible to reproduce results
by fixing the random seed (assuming all other hyperparameters
are also fixed)"""
beam_search_diversity_ra... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
a65ffb303310-2 | writer_api_key = get_from_dict_or_env(
values, "writer_api_key", "WRITER_API_KEY"
)
values["writer_api_key"] = writer_api_key
return values
@property
def _default_params(self) -> Mapping[str, Any]:
"""Get the default parameters for calling Writer API."""
retur... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
a65ffb303310-3 | """Call out to Writer's complete 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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
f2e99c20b819-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
f2e99c20b819-1 | raise ValueError(
f"Got device=={device}, "
f"device is required to be within [-1, {cuda_device_count})"
)
if device < 0 and cuda_device_count > 0:
logger.warning(
"Device has %d GPUs available. "
"Provide device={deviceId} ... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
f2e99c20b819-2 | return pipeline(
"text-generation", model=model, tokenizer=tokenizer,
max_new_tokens=10
)
def inference_fn(pipeline, prompt, stop = None):
return pipeline(prompt)[0]["generated_text"]
gpu = rh.cluster(name="rh-a10x", instanc... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
f2e99c20b819-3 | pipeline="models/pipeline.pkl",
hardware=gpu,
model_reqs=["./", "torch", "transformers"],
)
"""
pipeline_ref: Any #: :meta private:
client: Any #: :meta private:
inference_fn: Callable = _generate_text #: :meta private:
"""Inference function to send to ... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
f2e99c20b819-4 | self.hardware, reqs=self.model_reqs
)
_load_fn_kwargs = self.load_fn_kwargs or {}
self.pipeline_ref = remote_load_fn.remote(**_load_fn_kwargs)
self.client = rh.function(fn=self.inference_fn).to(
self.hardware, reqs=self.model_reqs
)
[docs] @classmethod
def from... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
f2e99c20b819-5 | def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"hardware": self.hardware},
}
@property
def _llm_type(self) -> str:
return "self_hosted_llm"
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
25ebb0dde0fd-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 ... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
25ebb0dde0fd-1 | presencePenalty: AI21PenaltyData = AI21PenaltyData()
"""Penalizes repeated tokens."""
countPenalty: AI21PenaltyData = AI21PenaltyData()
"""Penalizes repeated tokens according to count."""
frequencyPenalty: AI21PenaltyData = AI21PenaltyData()
"""Penalizes repeated tokens according to frequency."""
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
25ebb0dde0fd-2 | """Get the default parameters for calling AI21 API."""
return {
"temperature": self.temperature,
"maxTokens": self.maxTokens,
"minTokens": self.minTokens,
"topP": self.topP,
"presencePenalty": self.presencePenalty.dict(),
"countPenalty": se... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
25ebb0dde0fd-3 | elif self.stop is not None:
stop = self.stop
elif stop is None:
stop = []
if self.base_url is not None:
base_url = self.base_url
else:
if self.model in ("j1-grande-instruct",):
base_url = "https://api.ai21.com/studio/v1/experimental... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
772a0b3a4d28-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
772a0b3a4d28-1 | replicate_api_token: Optional[str] = None
class Config:
"""Configuration for this pydantic config."""
extra = Extra.forbid
@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."""
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
772a0b3a4d28-2 | return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"model_kwargs": self.model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of model."""
return "replicate"
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
772a0b3a4d28-3 | return outputs[0]
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
203eefee5f86-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 ... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
203eefee5f86-1 | frequency_penalty: float = 0.0
"""Penalizes repeated tokens according to frequency. Between 0 and 1."""
presence_penalty: float = 0.0
"""Penalizes repeated tokens. Between 0 and 1."""
truncate: Optional[str] = None
"""Specify how the client handles inputs longer than the maximum token
length: Tr... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
203eefee5f86-2 | "k": self.k,
"p": self.p,
"frequency_penalty": self.frequency_penalty,
"presence_penalty": self.presence_penalty,
"truncate": self.truncate,
}
@property
def _identifying_params(self) -> Dict[str, Any]:
"""Get the identifying parameters."""
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
203eefee5f86-3 | text = response.generations[0].text
# If stop tokens are provided, Cohere'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:
text = enforce_stop_tokens(text, params["stop_sequences"])
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
db76613f6b67-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
db76613f6b67-1 | temperature: float = 1.0
"""The temperature to use for sampling."""
top_p: float = 0.5
"""The top-p value to use for sampling."""
penalty_alpha_frequency: float = 0.4
"""Positive values penalize new tokens based on their existing frequency
in the text so far, decreasing the model's likelihood to... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
db76613f6b67-2 | "temperature": self.temperature,
"penalty_alpha_frequency": self.penalty_alpha_frequency,
"penalty_alpha_presence": self.penalty_alpha_presence,
"CHUNK_LEN": self.CHUNK_LEN,
"max_tokens_per_generation": self.max_tokens_per_generation,
}
@staticmethod
def _... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
db76613f6b67-3 | values["client"] = RWKVMODEL(
values["model"], strategy=values["strategy"], **model_kwargs
)
values["pipeline"] = PIPELINE(values["client"], values["tokens_path"])
except ImportError:
raise ValueError(
"Could not import rwkv python package. "
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
db76613f6b67-4 | out: Any = None
while len(tokens) > 0:
out, self.model_state = self.client.forward(
tokens[: self.CHUNK_LEN], self.model_state
)
tokens = tokens[self.CHUNK_LEN :]
END_OF_LINE = 187
out[END_OF_LINE] += newline_adj # adjust \n probability
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
db76613f6b67-5 | logits = self.run_rnn([token])
xxx = self.tokenizer.decode(self.model_tokens[out_last:])
if "\ufffd" not in xxx: # avoid utf-8 display issues
decoded += xxx
out_last = begin + i + 1
if i >= self.max_tokens_per_generation - 100:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
74ae835e2027-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,... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-1 | """Update response from the stream response."""
response["choices"][0]["text"] += stream_response["choices"][0]["text"]
response["choices"][0]["finish_reason"] = stream_response["choices"][0][
"finish_reason"
]
response["choices"][0]["logprobs"] = stream_response["choices"][0]["logprobs"]
def _s... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-2 | | retry_if_exception_type(openai.error.RateLimitError)
| retry_if_exception_type(openai.error.ServiceUnavailableError)
),
before_sleep=before_sleep_log(logger, logging.WARNING),
)
def completion_with_retry(llm: Union[BaseOpenAI, OpenAIChat], **kwargs: Any) -> Any:
"""Use tenacity to ... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-3 | class BaseOpenAI(BaseLLM):
"""Wrapper around OpenAI large language models."""
client: Any #: :meta private:
model_name: str = "text-davinci-003"
"""Model name to use."""
temperature: float = 0.7
"""What sampling temperature to use."""
max_tokens: int = 256
"""The maximum number of token... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-4 | """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[Dict[str, float]] = Field(default_factory=dict)
"""Adjust the probabi... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-5 | )
return OpenAIChat(**data)
return super().__new__(cls)
class Config:
"""Configuration for this pydantic object."""
extra = Extra.ignore
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra kwargs from additional... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-6 | openai_api_base = get_from_dict_or_env(
values,
"openai_api_base",
"OPENAI_API_BASE",
default="",
)
openai_organization = get_from_dict_or_env(
values,
"openai_organization",
"OPENAI_ORGANIZATION",
default=""... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-7 | "n": self.n,
"best_of": self.best_of,
"request_timeout": self.request_timeout,
"logit_bias": self.logit_bias,
}
return {**normal_params, **self.model_kwargs}
def _generate(
self, prompts: List[str], stop: Optional[List[str]] = None
) -> LLMResult:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-8 | for stream_resp in completion_with_retry(
self, prompt=_prompts, **params
):
self.callback_manager.on_llm_new_token(
stream_resp["choices"][0]["text"],
verbose=self.verbose,
logprobs=stream_re... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-9 | # Includes prompt, completion, and total tokens used.
_keys = {"completion_tokens", "prompt_tokens", "total_tokens"}
for _prompts in sub_prompts:
if self.streaming:
if len(_prompts) > 1:
raise ValueError("Cannot stream results with multiple prompts.")
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-10 | if not self.streaming:
# Can't update token usage if streaming
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],
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-11 | generations = []
for i, _ in enumerate(prompts):
sub_choices = choices[i * self.n : (i + 1) * self.n]
generations.append(
[
Generation(
text=choice["text"],
generation_info=dict(
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-12 | """Prepare the params for streaming."""
params = self._invocation_params
if params["best_of"] != 1:
raise ValueError("OpenAI only supports best_of == 1 for streaming")
if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the inp... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-13 | "Please install it with `pip install tiktoken`."
)
enc = tiktoken.encoding_for_model(self.model_name)
tokenized_text = enc.encode(
text,
allowed_special=self.allowed_special,
disallowed_special=self.disallowed_special,
)
# calculate the num... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-14 | "code-davinci-001": 8001,
"code-cushman-002": 2048,
"code-cushman-001": 2048,
}
context_size = model_token_mapping.get(modelname, None)
if context_size is None:
raise ValueError(
f"Unknown model: {modelname}. Please provide a valid OpenAI model... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-15 | Example:
.. code-block:: python
from langchain.llms import OpenAI
openai = OpenAI(model_name="text-davinci-003")
"""
@property
def _invocation_params(self) -> Dict[str, Any]:
return {**{"model": self.model_name}, **super()._invocation_params}
[docs]class AzureOpenAI(B... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-16 | """Wrapper around OpenAI Chat large language models.
To use, you should have the ``openai`` python package installed, and the
environment variable ``OPENAI_API_KEY`` set with your API key.
Any parameters that are valid to be passed to the openai.create call can be passed
in, even if not explicitly saved... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-17 | """Set of special tokens that are not allowed。"""
class Config:
"""Configuration for this pydantic object."""
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 i... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-18 | )
try:
import openai
openai.api_key = openai_api_key
if openai_api_base:
openai.api_base = openai_api_base
if openai_organization:
openai.organization = openai_organization
except ImportError:
raise ValueError(
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-19 | 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:
# ... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-20 | }
return LLMResult(
generations=[
[Generation(text=full_response["choices"][0]["message"]["content"])]
],
llm_output=llm_output,
)
async def _agenerate(
self, prompts: List[str], stop: Optional[List[str]] = None
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-21 | }
return LLMResult(
generations=[
[Generation(text=full_response["choices"][0]["message"]["content"])]
],
llm_output=llm_output,
)
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identify... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
74ae835e2027-22 | disallowed_special=self.disallowed_special,
)
# calculate the number of tokens in the encoded text
return len(tokenized_text)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
82ae45670c26-0 | Source code for langchain.llms.huggingface_endpoint
"""Wrapper around HuggingFace APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
82ae45670c26-1 | model_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model."""
huggingfacehub_api_token: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
82ae45670c26-2 | **{"model_kwargs": _model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "huggingface_endpoint"
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
82ae45670c26-3 | )
if self.task == "text-generation":
# Text generation return includes the starter text.
text = generated_text[0]["generated_text"][len(prompt) :]
elif self.task == "text2text-generation":
text = generated_text[0]["generated_text"]
else:
raise Valu... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
7d2947ec3dcd-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
7d2947ec3dcd-1 | """Validate that api key and python package exists in environment."""
deepinfra_api_token = get_from_dict_or_env(
values, "deepinfra_api_token", "DEEPINFRA_API_TOKEN"
)
values["deepinfra_api_token"] = deepinfra_api_token
return values
@property
def _identifying_params... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
7d2947ec3dcd-2 | "Content-Type": "application/json",
},
json={"input": prompt, **_model_kwargs},
)
if res.status_code != 200:
raise ValueError("Error raised by inference API")
text = res.json()[0]["generated_text"]
if stop is not None:
# I believe this is r... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
5f233327267b-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
5f233327267b-1 | f"Got invalid task {pipeline.task}, "
f"currently only {VALID_TASKS} are supported"
)
if stop is not None:
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_kwar... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
5f233327267b-2 | ) from e
if importlib.util.find_spec("torch") is not None:
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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
5f233327267b-3 | by IP address and SSH credentials (such as on-prem, or another cloud
like Paperspace, Coreweave, etc.).
To use, you should have the ``runhouse`` python package installed.
Only supports `text-generation` and `text2text-generation` for now.
Example using from_model_id:
.. code-block:: python
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
5f233327267b-4 | """Hugging Face model_id to load the model."""
task: str = DEFAULT_TASK
"""Hugging Face task (either "text-generation" or "text2text-generation")."""
device: int = 0
"""Device to use for inference. -1 for CPU, 0 for GPU, 1 for second GPU, etc."""
model_kwargs: Optional[dict] = None
"""Key word a... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
5f233327267b-5 | "task": kwargs.get("task", DEFAULT_TASK),
"device": kwargs.get("device", 0),
"model_kwargs": kwargs.get("model_kwargs", None),
}
super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs)
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the iden... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
6ed5c823f05f-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... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
6ed5c823f05f-1 | class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key exists in environment."""
forefrontai_api_key = get_from_dict_or_env(
values, "forefrontai_... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
6ed5c823f05f-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 = ForefrontAI("Tell me a joke.")
"""
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
cc0243e010d3-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 = ... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
cc0243e010d3-1 | pipe = pipeline(
"text-generation", model=model, tokenizer=tokenizer, max_new_tokens=10
)
hf = HuggingFacePipeline(pipeline=pipe)
"""
pipeline: Any #: :meta private:
model_id: str = DEFAULT_MODEL_ID
"""Model name to use."""
model_kwargs: Optional[dict] = None... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
cc0243e010d3-2 | elif task == "text2text-generation":
model = AutoModelForSeq2SeqLM.from_pretrained(model_id, **_model_kwargs)
else:
raise ValueError(
f"Got invalid task {task}, "
f"currently only {VALID_TASKS} are supported"
)
e... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
cc0243e010d3-3 | f"Got invalid task {pipeline.task}, "
f"currently only {VALID_TASKS} are supported"
)
return cls(
pipeline=pipeline,
model_id=model_id,
model_kwargs=_model_kwargs,
**kwargs,
)
@property
def _identifying_params(self) -> M... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
cc0243e010d3-4 | text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
68b59c6bd761-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
... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
68b59c6bd761-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 ... | /content/https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.