id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
e1bcbd876753-4 | }
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"model_id": self.model_id, "writer_org_id": self.writer_org_id},
**self._default_params,
}
@property
def _llm_type(self) -> str:
"""Re... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
e1bcbd876753-5 | Returns:
The string generated by the model.
Example:
.. code-block:: python
response = Writer("Tell me a joke.")
"""
if self.base_url is not None:
base_url = self.base_url
else:
base_url = (
"https://enterpri... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
e1bcbd876753-6 | )
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://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
90f4dc4d7eba-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
90f4dc4d7eba-1 | set with your API key.
Example:
.. code-block:: python
from langchain.llms import AI21
ai21 = AI21(model="j2-jumbo-instruct")
"""
model: str = "j2-jumbo-instruct"
"""Model name to use."""
temperature: float = 0.7
"""What sampling temperature to use."""
maxToke... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
90f4dc4d7eba-2 | """Penalizes repeated tokens."""
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 gene... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
90f4dc4d7eba-3 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key exists in environment."""
ai21_api_key = get_from_dict_or_env(values, "ai21_api_key", "AI21_API_KEY")
values["ai21_api_key"] = ai21_api_key
return values
@property
def _default_par... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
90f4dc4d7eba-4 | "numResults": self.numResults,
"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:
"""Ret... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
90f4dc4d7eba-5 | Returns:
The string generated by the model.
Example:
.. code-block:: python
response = ai21("Tell me a joke.")
"""
if self.stop is not None and stop is not None:
raise ValueError("`stop` found in both the input and default params.")
eli... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
90f4dc4d7eba-6 | 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("... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
5910ffa09fe2-0 | Source code for langchain.llms.clarifai
"""Wrapper around Clarifai's 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 import enfor... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
5910ffa09fe2-1 | .. code-block:: python
from langchain.llms import Clarifai
clarifai_llm = Clarifai(clarifai_pat_key=CLARIFAI_PAT_KEY, \
user_id=USER_ID, app_id=APP_ID, model_id=MODEL_ID)
"""
stub: Any #: :meta private:
metadata: Any
userDataObject: Any
model_id: Optional[str... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
5910ffa09fe2-2 | 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 we have all required info to access Clarifai
platform and python package e... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
5910ffa09fe2-3 | if app_id is None:
raise ValueError("Please provide a app_id.")
if model_id is None:
raise ValueError("Please provide a model_id.")
return values
@property
def _default_params(self) -> Dict[str, Any]:
"""Get the default parameters for calling Cohere API."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
5910ffa09fe2-4 | **kwargs: Any
) -> str:
"""Call out to Clarfai's PostModelOutputs 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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
5910ffa09fe2-5 | "Please install it with `pip install clarifai`."
)
auth = ClarifaiAuthHelper(
user_id=self.user_id,
app_id=self.app_id,
pat=self.clarifai_pat_key,
base=self.api_base,
)
self.userDataObject = auth.get_user_app_id_proto()
self.stu... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
5910ffa09fe2-6 | post_model_outputs_request = service_pb2.PostModelOutputsRequest(
user_app_id=self.userDataObject,
model_id=self.model_id,
version_id=self.model_version_id,
inputs=[
resources_pb2.Input(
data=resources_pb2.Data(text=resources_pb2.Text(r... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
5910ffa09fe2-7 | if stop is not None or self.stop is not None:
text = enforce_stop_tokens(text, params["stop_sequences"])
return text | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
6ec956560c8b-0 | Source code for langchain.llms.human
from typing import Any, Callable, List, Mapping, Optional
from pydantic import Field
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
def _display_prompt(prompt: str) -> None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/human.html |
6ec956560c8b-1 | break
# Combine all lines into a single string
multi_line_input = separator.join(lines)
return multi_line_input
[docs]class HumanInputLLM(LLM):
"""
A LLM wrapper which returns user input as the response.
"""
input_func: Callable = Field(default_factory=lambda: _collect_user_input)
prompt... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/human.html |
6ec956560c8b-2 | """Returns the type of LLM."""
return "human-input"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""
Displays the prompt to the user and returns the... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/human.html |
6ec956560c8b-3 | )
if stop is not None:
# I believe this is required since the stop tokens
# are not enforced by the human themselves
user_input = enforce_stop_tokens(user_input, stop)
return user_input | https://api.python.langchain.com/en/latest/_modules/langchain/llms/human.html |
81264850e84e-0 | Source code for langchain.llms.replicate
"""Wrapper around Replicate API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.utils im... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
81264850e84e-1 | .. code-block:: python
from langchain.llms import Replicate
replicate = Replicate(model="stability-ai/stable-diffusion: \
27b93a2413e7f36cd83da926f365628\
0b2931564ff050bf9575f1fdf9bcd7478",
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
81264850e84e-2 | """Build extra kwargs from additional params that were passed in."""
all_required_field_names = {field.alias for field in cls.__fields__.values()}
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
81264850e84e-3 | values, "REPLICATE_API_TOKEN", "REPLICATE_API_TOKEN"
)
values["replicate_api_token"] = replicate_api_token
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
"model": self.model,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
81264850e84e-4 | import replicate as replicate_python
except ImportError:
raise ImportError(
"Could not import replicate python package. "
"Please install it with `pip install replicate`."
)
# get the model and version
model_str, version_str = self.model.sp... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
81264850e84e-5 | return "".join([output for output in iterator]) | https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
94544d8ffb78-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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/fake.html |
94544d8ffb78-1 | """Return next response"""
response = self.responses[self.i]
self.i += 1
return response
async def _acall(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/fake.html |
f32655426181-0 | Source code for langchain.llms.stochasticai
"""Wrapper around StochasticAI APIs."""
import logging
import time
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
f32655426181-1 | """
api_url: str = ""
"""Model name to use."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not
explicitly specified."""
stochasticai_api_key: Optional[str] = None
class Config:
"""Configuration for this pydantic obj... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
f32655426181-2 | 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 what you intended."""
)
extra[f... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
f32655426181-3 | """Get the identifying parameters."""
return {
**{"endpoint_url": self.api_url},
**{"model_kwargs": self.model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "stochasticai"
def _call(
self,
prompt: str... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
f32655426181-4 | .. code-block:: python
response = StochasticAI("Tell me a joke.")
"""
params = self.model_kwargs or {}
params = {**params, **kwargs}
response_post = requests.post(
url=self.api_url,
json={"prompt": prompt, "params": params},
headers={
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
f32655426181-5 | "Content-Type": "application/json",
},
)
response_get.raise_for_status()
response_get_json = response_get.json()["data"]
text = response_get_json.get("completion")
completed = text is not None
time.sleep(0.5)
text = text[0]
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
f69fd1ab19a8-0 | Source code for langchain.llms.gpt4all
"""Wrapper for the GPT4All model."""
from functools import partial
from typing import Any, Dict, List, Mapping, Optional, Set
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
f69fd1ab19a8-1 | # Simplest invocation
response = model("Once upon a time, ")
"""
model: str
"""Path to the pre-trained GPT4All model file."""
backend: Optional[str] = Field(None, alias="backend")
n_ctx: int = Field(512, alias="n_ctx")
"""Token context window."""
n_parts: int = Field(-1, alias="n... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
f69fd1ab19a8-2 | """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."""
embedding: bool = Field(False, alias="embedding")
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
f69fd1ab19a8-3 | """The top-k value to use for sampling."""
echo: Optional[bool] = False
"""Whether to echo the prompt."""
stop: Optional[List[str]] = []
"""A list of strings to stop generation when encountered."""
repeat_last_n: Optional[int] = 64
"Last n tokens to penalize"
repeat_penalty: Optional[float] ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
f69fd1ab19a8-4 | 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
def _model_param_names() -> Set[str]:
return {
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
f69fd1ab19a8-5 | "top_p": self.top_p,
"temp": self.temp,
"n_batch": self.n_batch,
"repeat_penalty": self.repeat_penalty,
"repeat_last_n": self.repeat_last_n,
"context_erase": self.context_erase,
}
@root_validator()
def validate_environment(cls, values: Dict) ->... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
f69fd1ab19a8-6 | model_path += delimiter
values["client"] = GPT4AllModel(
model_name,
model_path=model_path or None,
model_type=values["backend"],
allow_download=values["allow_download"],
)
if values["n_threads"] is not None:
# set n_threads
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
f69fd1ab19a8-7 | **self._default_params(),
**{
k: v for k, v in self.__dict__.items() if k in self._model_param_names()
},
}
@property
def _llm_type(self) -> str:
"""Return the type of llm."""
return "gpt4all"
def _call(
self,
prompt: str,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
f69fd1ab19a8-8 | 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, verbose=self.verbose)
text = ""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
2c0ba3ce4a80-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.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
2c0ba3ce4a80-1 | in, even if not explicitly saved on this class.
Example:
.. code-block:: python
from langchain.llms import CerebriumAI
cerebrium = CerebriumAI(endpoint_url="")
"""
endpoint_url: str = ""
"""model endpoint to use"""
model_kwargs: Dict[str, Any] = Field(default_factory=... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
2c0ba3ce4a80-2 | 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 field_name in extra:
raise ValueError(f"Found {field_name... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
2c0ba3ce4a80-3 | values, "cerebriumai_api_key", "CEREBRIUMAI_API_KEY"
)
values["cerebriumai_api_key"] = cerebriumai_api_key
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"endpoint_url": self.endpoi... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
2c0ba3ce4a80-4 | ) -> str:
"""Call to CerebriumAI endpoint."""
try:
from cerebrium import model_api_request
except ImportError:
raise ValueError(
"Could not import cerebrium python package. "
"Please install it with `pip install cerebrium`."
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
d8acc41385e8-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.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
d8acc41385e8-1 | Example using from_model_id:
.. code-block:: python
from langchain.llms import HuggingFacePipeline
hf = HuggingFacePipeline.from_model_id(
model_id="gpt2",
task="text-generation",
pipeline_kwargs={"max_new_tokens": 10},
)
Ex... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
d8acc41385e8-2 | """
pipeline: Any #: :meta private:
model_id: str = DEFAULT_MODEL_ID
"""Model name to use."""
model_kwargs: Optional[dict] = None
"""Key word arguments passed to the model."""
pipeline_kwargs: Optional[dict] = None
"""Key word arguments passed to the pipeline."""
class Config:
"... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
d8acc41385e8-3 | try:
from transformers import (
AutoModelForCausalLM,
AutoModelForSeq2SeqLM,
AutoTokenizer,
)
from transformers import pipeline as hf_pipeline
except ImportError:
raise ValueError(
"Could not import t... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
d8acc41385e8-4 | else:
raise ValueError(
f"Got invalid task {task}, "
f"currently only {VALID_TASKS} are supported"
)
except ImportError as e:
raise ValueError(
f"Could not load the {task} model due to missing dependencies."
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
d8acc41385e8-5 | "Provide device={deviceId} to `from_model_id` to use available"
"GPUs for execution. deviceId is -1 (default) for CPU and "
"can be a positive integer associated with CUDA device id.",
cuda_device_count,
)
if "trust_remote_code" in _mod... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
d8acc41385e8-6 | f"currently only {VALID_TASKS} are supported"
)
return cls(
pipeline=pipeline,
model_id=model_id,
model_kwargs=_model_kwargs,
pipeline_kwargs=_pipeline_kwargs,
**kwargs,
)
@property
def _identifying_params(self) -> Mapping[s... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
d8acc41385e8-7 | **kwargs: Any,
) -> str:
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":
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
d8acc41385e8-8 | return text | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
ac1774410b1b-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://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-1 | from langchain.utils import get_from_dict_or_env
logger = logging.getLogger(__name__)
def update_token_usage(
keys: Set[str], response: Dict[str, Any], token_usage: Dict[str, Any]
) -> None:
"""Update token usage."""
_keys_to_use = keys.intersection(response["usage"])
for _key in _keys_to_use:
i... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-2 | "finish_reason"
]
response["choices"][0]["logprobs"] = stream_response["choices"][0]["logprobs"]
def _streaming_response_template() -> Dict[str, Any]:
return {
"choices": [
{
"text": "",
"finish_reason": None,
"logprobs": None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-3 | wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
retry=(
retry_if_exception_type(openai.error.Timeout)
| retry_if_exception_type(openai.error.APIError)
| retry_if_exception_type(openai.error.APIConnectionError)
| retry_if_exception_type(opena... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-4 | return llm.client.create(**kwargs)
return _completion_with_retry(**kwargs)
async def acompletion_with_retry(
llm: Union[BaseOpenAI, OpenAIChat], **kwargs: Any
) -> Any:
"""Use tenacity to retry the async completion call."""
retry_decorator = _create_retry_decorator(llm)
@retry_decorator
async de... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-5 | @property
def lc_serializable(self) -> bool:
return True
client: Any #: :meta private:
model_name: str = Field("text-davinci-003", alias="model")
"""Model name to use."""
temperature: float = 0.7
"""What sampling temperature to use."""
max_tokens: int = 256
"""The maximum number... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-6 | n: int = 1
"""How many completions to generate for each prompt."""
best_of: int = 1
"""Generates best_of completions server-side and returns the "best"."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-7 | logit_bias: Optional[Dict[str, float]] = Field(default_factory=dict)
"""Adjust the probability of specific tokens being generated."""
max_retries: int = 6
"""Maximum number of retries to make when generating."""
streaming: bool = False
"""Whether to stream the results or not."""
allowed_special:... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-8 | be the same as the embedding model name. However, there are some cases
where you may want to use this Embedding class with a model name not
supported by tiktoken. This can include when using Azure embeddings or
when using one of the many model providers that expose an OpenAI-like
API but with differ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-9 | warnings.warn(
"You are trying to use a chat model. This way of initializing it is "
"no longer supported. Instead, please use: "
"`from langchain.chat_models import ChatOpenAI`"
)
return OpenAIChat(**data)
return super().__new__(cls)
c... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-10 | if field_name not in all_required_field_names:
logger.warning(
f"""WARNING! {field_name} is not default parameter.
{field_name} was transferred to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-11 | values, "openai_api_key", "OPENAI_API_KEY"
)
values["openai_api_base"] = get_from_dict_or_env(
values,
"openai_api_base",
"OPENAI_API_BASE",
default="",
)
values["openai_proxy"] = get_from_dict_or_env(
values,
"opena... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-12 | )
if values["streaming"] and values["n"] > 1:
raise ValueError("Cannot stream results when n > 1.")
if values["streaming"] and values["best_of"] > 1:
raise ValueError("Cannot stream results when best_of > 1.")
return values
@property
def _default_params(self) -> D... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-13 | }
# 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_params, **self.model_kwargs}
def _generate(
self,
prompts: List[str],
stop: Optional[Lis... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-14 | .. code-block:: python
response = openai.generate(["Tell me a joke."])
"""
# TODO: write a unit test for this
params = self._invocation_params
params = {**params, **kwargs}
sub_prompts = self.get_sub_prompts(params, prompts, stop)
choices = []
toke... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-15 | for stream_resp in completion_with_retry(
self, prompt=_prompts, **params
):
if run_manager:
run_manager.on_llm_new_token(
stream_resp["choices"][0]["text"],
verbose=self.verbose,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-16 | run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
"""Call out to OpenAI's endpoint async with k unique prompts."""
params = self._invocation_params
params = {**params, **kwargs}
sub_prompts = self.get_sub_prompts(params, prompts, stop... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-17 | params["stream"] = True
response = _streaming_response_template()
async for stream_resp in await acompletion_with_retry(
self, prompt=_prompts, **params
):
if run_manager:
await run_manager.on_llm_new_token(
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-18 | 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 llm call."""
if stop is not None:
if "stop" in params:
raise ValueError("`stop` found ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-19 | ]
return sub_prompts
def create_llm_result(
self, choices: Any, prompts: List[str], token_usage: Dict[str, int]
) -> LLMResult:
"""Create the LLMResult from the choices and prompts."""
generations = []
for i, _ in enumerate(prompts):
sub_choices = choices[i * ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-20 | return LLMResult(generations=generations, llm_output=llm_output)
def stream(self, prompt: str, stop: Optional[List[str]] = None) -> Generator:
"""Call OpenAI with streaming flag and return the resulting generator.
BETA: this is a beta feature while we figure out the right abstraction.
Once t... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-21 | return generator
def prep_streaming_params(self, stop: Optional[List[str]] = None) -> Dict[str, Any]:
"""Prepare the params for streaming."""
params = self._invocation_params
if "best_of" in params and params["best_of"] != 1:
raise ValueError("OpenAI only supports best_of == 1 fo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-22 | "api_base": self.openai_api_base,
"organization": self.openai_organization,
}
if self.openai_proxy:
import openai
openai.proxy = {"http": self.openai_proxy, "https": self.openai_proxy} # type: ignore[assignment] # noqa: E501
return {**openai_creds, **self._d... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-23 | # 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 ImportError(
"Could not import tiktoken python package. "
"This is needed i... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-24 | allowed_special=self.allowed_special,
disallowed_special=self.disallowed_special,
)
@staticmethod
def modelname_to_contextsize(modelname: str) -> int:
"""Calculate the maximum number of tokens possible to generate for a model.
Args:
modelname: The modelname we wan... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-25 | "gpt-4-32k-0314": 32768,
"gpt-4-32k-0613": 32768,
"gpt-3.5-turbo": 4096,
"gpt-3.5-turbo-0301": 4096,
"gpt-3.5-turbo-0613": 4096,
"gpt-3.5-turbo-16k": 16385,
"gpt-3.5-turbo-16k-0613": 16385,
"text-ada-001": 2049,
"ada": 2049,... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-26 | "curie": 2049,
"davinci": 2049,
"text-davinci-003": 4097,
"text-davinci-002": 4097,
"code-davinci-002": 8001,
"code-davinci-001": 8001,
"code-cushman-002": 2048,
"code-cushman-001": 2048,
}
# handling finetuned models
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-27 | )
return context_size
@property
def max_context_size(self) -> int:
"""Get max context size for this model."""
return self.modelname_to_contextsize(self.model_name)
def max_tokens_for_prompt(self, prompt: str) -> int:
"""Calculate the maximum number of tokens possible to gener... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-28 | 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 on this class.
Example:
.. code-block:: pyth... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-29 | 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 on this class.
Example:
.. code-block:: python
from langchain.llms import AzureOpenAI
openai = Az... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-30 | )
values["openai_api_type"] = get_from_dict_or_env(
values,
"openai_api_type",
"OPENAI_API_TYPE",
)
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
return {
**{"deployment_name": self.deployment_name},
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-31 | """Return type of llm."""
return "azure"
[docs]class OpenAIChat(BaseLLM):
"""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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-32 | """Model name to use."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
openai_api_key: Optional[str] = None
openai_api_base: Optional[str] = None
# to support explicit proxy for OpenAI
openai_proxy: O... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-33 | """Set of special tokens that are not allowed。"""
@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()}
e... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-34 | values, "openai_api_key", "OPENAI_API_KEY"
)
openai_api_base = get_from_dict_or_env(
values,
"openai_api_base",
"OPENAI_API_BASE",
default="",
)
openai_proxy = get_from_dict_or_env(
values,
"openai_proxy",
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-35 | if openai_proxy:
openai.proxy = {"http": openai_proxy, "https": openai_proxy} # type: ignore[assignment] # noqa: E501
except ImportError:
raise ImportError(
"Could not import openai python package. "
"Please install it with `pip install openai`."
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-36 | "`from langchain.chat_models import ChatOpenAI`"
)
return values
@property
def _default_params(self) -> Dict[str, Any]:
"""Get the default parameters for calling OpenAI API."""
return self.model_kwargs
def _get_chat_params(
self, prompts: List[str], stop: Optional[Lis... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-37 | if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
if params.get("max_tokens") == -1:
# for ChatGPT api, omitting max_tokens is equivalent to having no limit
del params["max_tokens"]
return... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-38 | params["stream"] = True
for stream_resp in completion_with_retry(self, messages=messages, **params):
token = stream_resp["choices"][0]["delta"].get("content", "")
response += token
if run_manager:
run_manager.on_llm_new_token(
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-39 | self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
messages, params = self._get_chat_params(prompts, stop)
params = {**params, **kwargs}
if self.streaming:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
ac1774410b1b-40 | )
else:
full_response = await acompletion_with_retry(
self, messages=messages, **params
)
llm_output = {
"token_usage": full_response["usage"],
"model_name": self.model_name,
}
return LLMResult(
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.