id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 59 127 |
|---|---|---|
bec8d20e826f-6 | "n": self.n,
"request_timeout": self.request_timeout,
"logit_bias": self.logit_bias,
}
# Azure gpt-35-turbo doesn't support best_of
# don't specify best_of if it is 1
if self.best_of > 1:
normal_params["best_of"] = self.best_of
return {**normal... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-7 | raise ValueError("Cannot stream results with multiple prompts.")
params["stream"] = True
response = _streaming_response_template()
for stream_resp in completion_with_retry(
self, prompt=_prompts, **params
):
if run_m... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-8 | for _prompts in sub_prompts:
if self.streaming:
if len(_prompts) > 1:
raise ValueError("Cannot stream results with multiple prompts.")
params["stream"] = True
response = _streaming_response_template()
async for stream_resp i... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-9 | params["max_tokens"] = self.max_tokens_for_prompt(prompts[0])
sub_prompts = [
prompts[i : i + self.batch_size]
for i in range(0, len(prompts), self.batch_size)
]
return sub_prompts
def create_llm_result(
self, choices: Any, prompts: List[str], token_usage: Dic... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-10 | .. code-block:: python
generator = openai.stream("Tell me a joke.")
for token in generator:
yield token
"""
params = self.prep_streaming_params(stop)
generator = self.client.create(prompt=prompt, **params)
return generator
def prep_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-11 | @property
def _llm_type(self) -> str:
"""Return type of llm."""
return "openai"
def get_token_ids(self, text: str) -> List[int]:
"""Get the token IDs using the tiktoken package."""
# tiktoken NOT supported for Python < 3.8
if sys.version_info[1] < 8:
return su... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-12 | "gpt-3.5-turbo": 4096,
"gpt-3.5-turbo-0301": 4096,
"text-ada-001": 2049,
"ada": 2049,
"text-babbage-001": 2040,
"babbage": 2049,
"text-curie-001": 2049,
"curie": 2049,
"davinci": 2049,
"text-davinci-003": 4097,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-13 | max_tokens = openai.max_token_for_prompt("Tell me a joke.")
"""
num_tokens = self.get_num_tokens(prompt)
# get max context size for model by name
max_size = self.modelname_to_contextsize(self.model_name)
return max_size - num_tokens
[docs]class OpenAI(BaseOpenAI):
"""Wrapper ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-14 | """Deployment name to use."""
openai_api_type: str = "azure"
openai_api_version: str = ""
@root_validator()
def validate_azure_settings(cls, values: Dict) -> Dict:
values["openai_api_version"] = get_from_dict_or_env(
values,
"openai_api_version",
"OPENAI_API_V... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-15 | Example:
.. code-block:: python
from langchain.llms import OpenAIChat
openaichat = OpenAIChat(model_name="gpt-3.5-turbo")
"""
client: Any #: :meta private:
model_name: str = "gpt-3.5-turbo"
"""Model name to use."""
model_kwargs: Dict[str, Any] = Field(default_factory... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-16 | 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.")
extra[field_name] = values.pop(field_name)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-17 | )
try:
values["client"] = openai.ChatCompletion
except AttributeError:
raise ValueError(
"`openai` has no `ChatCompletion` attribute, this is likely "
"due to an old version of the openai package. Try upgrading it "
"with `pip insta... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-18 | def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
messages, params = self._get_chat_params(prompts, stop)
params = {**params, **kwargs}
if s... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-19 | if self.streaming:
response = ""
params["stream"] = True
async for stream_resp in await acompletion_with_retry(
self, messages=messages, **params
):
token = stream_resp["choices"][0]["delta"].get("content", "")
response += t... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bec8d20e826f-20 | raise ImportError(
"Could not import tiktoken python package. "
"This is needed in order to calculate get_num_tokens. "
"Please install it with `pip install tiktoken`."
)
enc = tiktoken.encoding_for_model(self.model_name)
return enc.encode(
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
a2e65d203a8d-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_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/cohere.html |
a2e65d203a8d-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/cohere.html |
a2e65d203a8d-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/cohere.html |
a2e65d203a8d-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/cohere.html |
8d8b840157db-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openlm.html |
c2bbbd9b85b3-0 | Source code for langchain.llms.bedrock
import json
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 enforce_stop_tokens
class LLMInputOutp... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/bedrock.html |
c2bbbd9b85b3-1 | else:
return response_body.get("results")[0].get("outputText")
[docs]class Bedrock(LLM):
"""LLM provider to invoke Bedrock models.
To authenticate, the AWS client uses the following methods to
automatically load credentials:
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/crede... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/bedrock.html |
c2bbbd9b85b3-2 | equivalent to the modelId property in the list-foundation-models api"""
model_kwargs: Optional[Dict] = None
"""Key word arguments to pass to the model."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/bedrock.html |
c2bbbd9b85b3-3 | """Return type of llm."""
return "amazon_bedrock"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call out to Bedrock service model.
Args:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/bedrock.html |
0d24196d7a7a-0 | Source code for langchain.llms.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import Any, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms import OpenAI, OpenAIChat
from langchain.schema import LLMR... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html |
0d24196d7a7a-1 | """Call OpenAI generate and then call PromptLayer API to log the request."""
from promptlayer.utils import get_api_key, promptlayer_api_request
request_start_time = datetime.datetime.now().timestamp()
generated_responses = super()._generate(prompts, stop, run_manager)
request_end_time = ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html |
0d24196d7a7a-2 | generated_responses = await super()._agenerate(prompts, stop, run_manager)
request_end_time = datetime.datetime.now().timestamp()
for i in range(len(prompts)):
prompt = prompts[i]
generation = generated_responses.generations[i][0]
resp = {
"text": gene... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html |
0d24196d7a7a-3 | parameters:
``pl_tags``: List of strings to tag the request with.
``return_pl_id``: If True, the PromptLayer request ID will be
returned in the ``generation_info`` field of the
``Generation`` object.
Example:
.. code-block:: python
from langchain.llms impo... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html |
0d24196d7a7a-4 | resp,
request_start_time,
request_end_time,
get_api_key(),
return_pl_id=self.return_pl_id,
)
if self.return_pl_id:
if generation.generation_info is None or not isinstance(
generation.generation_in... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html |
0d24196d7a7a-5 | generation.generation_info, dict
):
generation.generation_info = {}
generation.generation_info["pl_request_id"] = pl_request_id
return generated_responses
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/promptlayer_openai.html |
c3e716902663-0 | Source code for langchain.llms.vertexai
"""Wrapper around Google VertexAI models."""
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from pydantic import BaseModel, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils i... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/vertexai.html |
c3e716902663-1 | "The default custom credentials (google.auth.credentials.Credentials) to use "
"when making API calls. If not provided, credentials will be ascertained from "
"the environment."
@property
def _default_params(self) -> Dict[str, Any]:
base_params = {
"temperature": self.temperature,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/vertexai.html |
c3e716902663-2 | tuned_model_name: Optional[str] = None
"The name of a tuned model, if it's provided, model_name is ignored."
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that the python package exists in environment."""
cls._try_init_vertexai(values)
try:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/vertexai.html |
34a39efd0be0-0 | Source code for langchain.llms.fake
"""Fake LLM wrapper for testing purposes."""
from typing import Any, List, Mapping, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms.base import LLM
[docs]class FakeListLLM(LLM):
"""Fake LLM ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/fake.html |
602f869be811-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
602f869be811-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."""
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
602f869be811-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
602f869be811-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
602f869be811-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
602f869be811-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
602f869be811-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/llamacpp.html |
471e13cf6a29-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.... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/modal.html |
471e13cf6a29-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/modal.html |
471e13cf6a29-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/modal.html |
509740dbdcc7-0 | Source code for langchain.llms.aviary
"""Wrapper around Aviary"""
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.llms.utils import ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/aviary.html |
509740dbdcc7-1 | """Validate that api key and python package exists in environment."""
aviary_url = get_from_dict_or_env(values, "aviary_url", "AVIARY_URL")
if not aviary_url.endswith("/"):
aviary_url += "/"
values["aviary_url"] = aviary_url
aviary_token = get_from_dict_or_env(
va... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/aviary.html |
509740dbdcc7-2 | prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call out to Aviary
Args:
prompt: The prompt to pass into the model.
Returns:
The string generated by the model.
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/aviary.html |
3920b7a2a743-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 ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/bananadev.html |
3920b7a2a743-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 ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/bananadev.html |
3920b7a2a743-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_key, model... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/bananadev.html |
6a2cbdc5de40-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/predictionguard.html |
6a2cbdc5de40-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 ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/predictionguard.html |
6a2cbdc5de40-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 ... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/predictionguard.html |
abfa2f4f45bb-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/nlpcloud.html |
abfa2f4f45bb-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/nlpcloud.html |
abfa2f4f45bb-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_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/nlpcloud.html |
abfa2f4f45bb-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."
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/nlpcloud.html |
b57e34660cee-0 | Source code for langchain.llms.anyscale
"""Wrapper around Anyscale"""
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 enf... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/anyscale.html |
b57e34660cee-1 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
anyscale_service_url = get_from_dict_or_env(
values, "anyscale_service_url", "ANYSCALE_SERVICE_URL"
)
anyscale_service_route = get_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/anyscale.html |
b57e34660cee-2 | **kwargs: Any,
) -> str:
"""Call out to Anyscale Service 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-b... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/anyscale.html |
91a00fbecf30-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/gpt4all.html |
91a00fbecf30-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."""
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/gpt4all.html |
91a00fbecf30-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
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/gpt4all.html |
91a00fbecf30-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
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/gpt4all.html |
91a00fbecf30-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/gpt4all.html |
f24d818efe06-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/gooseai.html |
f24d818efe06-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[... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/gooseai.html |
f24d818efe06-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. "
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/gooseai.html |
f24d818efe06-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/gooseai.html |
7185e517c68d-0 | Source code for langchain.llms.ctransformers
"""Wrapper around the C Transformers library."""
from typing import Any, Dict, Optional, Sequence
from pydantic import root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
[docs]class CTransformers(LLM):
"""W... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/ctransformers.html |
7185e517c68d-1 | "config": self.config,
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "ctransformers"
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that ``ctransformers`` package is installed."""
try:
from... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/ctransformers.html |
7185e517c68d-2 | text.append(chunk)
_run_manager.on_llm_new_token(chunk, verbose=self.verbose)
return "".join(text)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/ctransformers.html |
840c8da72c30-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.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.utils import get_from... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/ai21.html |
840c8da72c30-1 | countPenalty: AI21PenaltyData = AI21PenaltyData()
"""Penalizes repeated tokens according to count."""
frequencyPenalty: AI21PenaltyData = AI21PenaltyData()
"""Penalizes repeated tokens according to frequency."""
numResults: int = 1
"""How many completions to generate for each prompt."""
logitBia... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/ai21.html |
840c8da72c30-2 | "logitBias": self.logitBias,
}
@property
def _identifying_params(self) -> Dict[str, Any]:
"""Get the identifying parameters."""
return {**{"model": self.model}, **self._default_params}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "ai21"
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/ai21.html |
840c8da72c30-3 | response = requests.post(
url=f"{base_url}/{self.model}/complete",
headers={"Authorization": f"Bearer {self.ai21_api_key}"},
json={"prompt": prompt, "stopSequences": stop, **params},
)
if response.status_code != 200:
optional_detail = response.json().get("... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/ai21.html |
81f7ca11d674-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.callbacks.manager import (
AsyncCallbackManagerForLLMR... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/anthropic.html |
81f7ca11d674-1 | anthropic_api_key = get_from_dict_or_env(
values, "anthropic_api_key", "ANTHROPIC_API_KEY"
)
try:
import anthropic
values["client"] = anthropic.Client(
api_key=anthropic_api_key,
default_request_timeout=values["default_request_timeout"]... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/anthropic.html |
81f7ca11d674-2 | if stop is None:
stop = []
# Never want model to invent new turns of Human / Assistant dialog.
stop.extend([self.HUMAN_PROMPT])
return stop
[docs]class Anthropic(LLM, _AnthropicCommon):
r"""Wrapper around Anthropic's large language models.
To use, you should have the ``anthro... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/anthropic.html |
81f7ca11d674-3 | extra = Extra.forbid
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "anthropic-llm"
def _wrap_prompt(self, prompt: str) -> str:
if not self.HUMAN_PROMPT or not self.AI_PROMPT:
raise NameError("Please ensure the anthropic package is loaded")
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/anthropic.html |
81f7ca11d674-4 | params = {**self._default_params, **kwargs}
if self.streaming:
stream_resp = self.client.completion_stream(
prompt=self._wrap_prompt(prompt),
stop_sequences=stop,
**params,
)
current_completion = ""
for data in strea... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/anthropic.html |
81f7ca11d674-5 | stop_sequences=stop,
**params,
)
return response["completion"]
[docs] def stream(self, prompt: str, stop: Optional[List[str]] = None) -> Generator:
r"""Call Anthropic completion_stream and return the resulting generator.
BETA: this is a beta feature while we figure out the... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/anthropic.html |
35ccd7ed226e-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.callbacks.manager import CallbackManagerForLLMRun
from langchain.llm... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted.html |
35ccd7ed226e-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 ass... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted.html |
35ccd7ed226e-2 | llm = SelfHostedPipeline(
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.ll... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted.html |
35ccd7ed226e-3 | load_fn_kwargs: Optional[dict] = None
"""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
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted.html |
35ccd7ed226e-4 | if not isinstance(pipeline, str):
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 th... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted.html |
b7804a05e6da-0 | Source code for langchain.llms.databricks
import os
from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Optional
import requests
from pydantic import BaseModel, Extra, Field, PrivateAttr, root_validator, validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langch... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html |
b7804a05e6da-1 | return values
def post(self, request: Any) -> Any:
# See https://docs.databricks.com/machine-learning/model-serving/score-model-serving-endpoints.html
wrapped_request = {"dataframe_records": [request]}
response = self.post_raw(wrapped_request)["predictions"]
# For a single-record que... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html |
b7804a05e6da-2 | """Gets the default Databricks workspace hostname.
Raises an error if the hostname cannot be automatically determined.
"""
host = os.getenv("DATABRICKS_HOST")
if not host:
try:
host = get_repl_context().browserHostName
if not host:
raise ValueError("contex... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html |
b7804a05e6da-3 | We assume that an LLM was registered and deployed to a serving endpoint.
To wrap it as an LLM you must have "Can Query" permission to the endpoint.
Set ``endpoint_name`` accordingly and do not set ``cluster_id`` and
``cluster_driver_port``.
The expected model signature is:
* inputs::
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html |
b7804a05e6da-4 | you can use `transform_input_fn` and `transform_output_fn` to apply necessary
transformations before and after the query.
"""
host: str = Field(default_factory=get_default_host)
"""Databricks workspace hostname.
If not provided, the default value is determined by
* the ``DATABRICKS_HOST`` enviro... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html |
b7804a05e6da-5 | """
cluster_driver_port: Optional[str] = None
"""The port number used by the HTTP server running on the cluster driver node.
The server should listen on the driver IP address or simply ``0.0.0.0`` to connect.
We recommend the server using a port number between ``[3000, 8000]``.
"""
model_kwargs:... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html |
b7804a05e6da-6 | "And the cluster_id cannot be automatically determined. Received"
f" error: {e}"
)
@validator("cluster_driver_port", always=True)
def set_cluster_driver_port(cls, v: Any, values: Dict[str, Any]) -> Optional[str]:
if v and values["endpoint_name"]:
raise Val... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html |
b7804a05e6da-7 | )
else:
raise ValueError(
"Must specify either endpoint_name or cluster_id/cluster_driver_port."
)
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "databricks"
def _call(
self,
prompt: str,
stop: O... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/databricks.html |
e67de62f4d69-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.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.util... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/forefrontai.html |
e67de62f4d69-1 | @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_api_key", "FOREFRONTAI_API_KEY"
)
values["forefrontai_api_key"] = forefrontai_api_key... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/forefrontai.html |
e67de62f4d69-2 | """
response = requests.post(
url=self.endpoint_url,
headers={
"Authorization": f"Bearer {self.forefrontai_api_key}",
"Content-Type": "application/json",
},
json={"text": prompt, **self._default_params, **kwargs},
)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/forefrontai.html |
bb2b8267c137-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/aleph_alpha.html |
bb2b8267c137-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/aleph_alpha.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.