id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 54 121 |
|---|---|---|
368561eaf35f-3 | """Validate that api key and python package exists in environment."""
aleph_alpha_api_key = get_from_dict_or_env(
values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY"
)
try:
import aleph_alpha_client
values["client"] = aleph_alpha_client.Client(token=aleph_alp... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
368561eaf35f-4 | "minimum_tokens": self.minimum_tokens,
"echo": self.echo,
"use_multiplicative_frequency_penalty": self.use_multiplicative_frequency_penalty, # noqa: E501
"sequence_penalty": self.sequence_penalty,
"sequence_penalty_min_length": self.sequence_penalty_min_length,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
368561eaf35f-5 | Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
response = aleph_alpha("Tell me a joke.")
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
3503349f7721-0 | Source code for langchain.llms.baseten
"""Wrapper around Baseten deployed model API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Field
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
logger = logging.getLogger(__name__... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html |
3503349f7721-1 | """Return type of model."""
return "baseten"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call to Baseten deployed model endpoint."""
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html |
8383012c00d0-0 | Source code for langchain.llms.textgen
"""Wrapper around text-generation-webui."""
import logging
from typing import Any, Dict, List, Optional
import requests
from pydantic import Field
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
logger = logging.getLogger(__name... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
8383012c00d0-1 | number. Higher value = higher range of possible random results."""
typical_p: Optional[float] = 1
"""If not set to 1, select only tokens that are at least this much more likely to
appear than random tokens, given the prior text."""
epsilon_cutoff: Optional[float] = 0 # In units of 1e-4
"""Epsilon c... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
8383012c00d0-2 | """Seed (-1 for random)"""
add_bos_token: bool = Field(True, alias="add_bos_token")
"""Add the bos_token to the beginning of prompts.
Disabling this can make the replies more creative."""
truncation_length: Optional[int] = 2048
"""Truncate the prompt up to this length. The leftmost tokens are remove... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
8383012c00d0-3 | "num_beams": self.num_beams,
"penalty_alpha": self.penalty_alpha,
"length_penalty": self.length_penalty,
"early_stopping": self.early_stopping,
"seed": self.seed,
"add_bos_token": self.add_bos_token,
"truncation_length": self.truncation_length,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
8383012c00d0-4 | return params
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call the textgen web API and return the output.
Args:
prompt: The prompt to use fo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
70edbd616d16-0 | Source code for langchain.llms.gooseai
"""Wrapper around GooseAI API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.utils import... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
70edbd616d16-1 | presence_penalty: float = 0
"""Penalizes repeated tokens."""
n: int = 1
"""How many completions to generate for each prompt."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
logit_bias: Optional[Dict[... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
70edbd616d16-2 | )
try:
import openai
openai.api_key = gooseai_api_key
openai.api_base = "https://api.goose.ai/v1"
values["client"] = openai.Completion
except ImportError:
raise ImportError(
"Could not import openai python package. "
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
70edbd616d16-3 | if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
params = {**params, **kwargs}
response = self.client.create(engine=self.model_name, prompt=prompt, **params)
text = respo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
e98fd257b856-0 | Source code for langchain.llms.rwkv
"""Wrapper for the RWKV model.
Based on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py
https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py
"""
from typing import Any, Dict, List, Mapping, Optional, Set
from pydantic import BaseModel, Extra, roo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
e98fd257b856-1 | """Positive values penalize new tokens based on their existing frequency
in the text so far, decreasing the model's likelihood to repeat the same
line verbatim.."""
penalty_alpha_presence: float = 0.4
"""Positive values penalize new tokens based on whether they appear
in the text so far, increasing ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
e98fd257b856-2 | """Validate that the python package exists in the environment."""
try:
import tokenizers
except ImportError:
raise ImportError(
"Could not import tokenizers python package. "
"Please install it with `pip install tokenizers`."
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
e98fd257b856-3 | AVOID_REPEAT_TOKENS = []
AVOID_REPEAT = ",:?!"
for i in AVOID_REPEAT:
dd = self.pipeline.encode(i)
assert len(dd) == 1
AVOID_REPEAT_TOKENS += dd
tokens = [int(x) for x in _tokens]
self.model_tokens += tokens
out: Any = None
while len(to... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
e98fd257b856-4 | occurrence[token] += 1
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_ge... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
dbcbb4ae085d-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
dbcbb4ae085d-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
dbcbb4ae085d-2 | text.append(chunk)
_run_manager.on_llm_new_token(chunk, verbose=self.verbose)
return "".join(text) | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
953950b19c41-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.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
953950b19c41-1 | 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:
"""Validate that api key and python package exists in environment."""
hugging... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
953950b19c41-2 | return "huggingface_endpoint"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
prompt: Th... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
953950b19c41-3 | elif self.task == "text2text-generation":
text = generated_text[0]["generated_text"]
elif self.task == "summarization":
text = generated_text[0]["summary_text"]
else:
raise ValueError(
f"Got invalid task {self.task}, "
f"currently only ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
eccfa8283ddc-0 | Source code for langchain.llms.aviary
"""Wrapper around Aviary"""
import dataclasses
import os
from typing import Any, Dict, List, Mapping, Optional, Union, cast
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LL... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html |
eccfa8283ddc-1 | ) from e
result = sorted(
[k.lstrip("/").replace("--", "/") for k in result.keys() if "--" in k]
)
return result
def get_completions(
model: str,
prompt: str,
use_prompt_format: bool = True,
version: str = "",
) -> Dict[str, Union[str, float, int]]:
"""Get completions from Aviary... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html |
eccfa8283ddc-2 | os.environ["AVIARY_TOKEN"] = "<TOKEN>"
light = Aviary(model='amazon/LightGPT')
output = light('How do you make fried rice?')
"""
model: str = "amazon/LightGPT"
aviary_url: Optional[str] = None
aviary_token: Optional[str] = None
# If True the prompt template for the model will... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html |
eccfa8283ddc-3 | "aviary_url": self.aviary_url,
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return f"aviary-{self.model.replace('/', '-')}"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLM... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html |
bf2cf988e4d3-0 | Source code for langchain.llms.writer
"""Wrapper around Writer APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import e... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
bf2cf988e4d3-1 | logprobs: bool = False
"""Whether to return log probabilities."""
n: Optional[int] = None
"""How many completions to generate."""
writer_api_key: Optional[str] = None
"""Writer API key."""
base_url: Optional[str] = None
"""Base url to use, if None decides based on model name."""
class Co... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
bf2cf988e4d3-2 | """Get the identifying parameters."""
return {
**{"model_id": self.model_id, "writer_org_id": self.writer_org_id},
**self._default_params,
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "writer"
def _call(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
bf2cf988e4d3-3 | # 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 |
4828e0b4e329-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 |
4828e0b4e329-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
4828e0b4e329-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"
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
4828e0b4e329-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("... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
52d648e51df5-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 |
52d648e51df5-1 | api_base: str = "https://api.clarifai.com"
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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
52d648e51df5-2 | prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any
) -> str:
"""Call out to Clarfai's PostModelOutputs endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of s... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
52d648e51df5-3 | # The userDataObject is created in the overview and
# is required when using a PAT
# If version_id None, Defaults to the latest model version
post_model_outputs_request = service_pb2.PostModelOutputsRequest(
user_app_id=self.userDataObject,
model_id=self.model_id,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
ec84d0b710fb-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 |
ec84d0b710fb-1 | """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 |
4e6910fbc4ba-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 |
4e6910fbc4ba-1 | """Build extra kwargs from additional params that were passed in."""
all_required_field_names = {field.alias for field in cls.__fields__.values()}
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
4e6910fbc4ba-2 | try:
import replicate as replicate_python
except ImportError:
raise ImportError(
"Could not import replicate python package. "
"Please install it with `pip install replicate`."
)
# get the model and version
model_str, version_st... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
afe64ccd5679-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 |
b46a9402f8f9-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 |
b46a9402f8f9-1 | raise ValueError(f"Found {field_name} supplied twice.")
logger.warning(
f"""{field_name} was transfered to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
b46a9402f8f9-2 | response = StochasticAI("Tell me a joke.")
"""
params = self.model_kwargs or {}
params = {**params, **kwargs}
response_post = requests.post(
url=self.api_url,
json={"prompt": prompt, "params": params},
headers={
"apiKey": f"{self.stocha... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
89a879b6d8d7-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 |
89a879b6d8d7-1 | logits_all: bool = Field(False, alias="logits_all")
"""Return logits for all tokens, not just the last token."""
vocab_only: bool = Field(False, alias="vocab_only")
"""Only load the vocabulary, no weights."""
use_mlock: bool = Field(False, alias="use_mlock")
"""Force system to keep model in RAM."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
89a879b6d8d7-2 | starting from beginning if the context has run out."""
allow_download: bool = False
"""If model does not exist in ~/.cache/gpt4all/, download it."""
client: Any = None #: :meta private:
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@staticmethod
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
89a879b6d8d7-3 | model_path += delimiter
values["client"] = GPT4AllModel(
model_name,
model_path=model_path or None,
model_type=values["backend"],
allow_download=values["allow_download"],
)
if values["n_threads"] is not None:
# set n_threads
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
89a879b6d8d7-4 | The string generated by the model.
Example:
.. code-block:: python
prompt = "Once upon a time, "
response = model(prompt, n_predict=55)
"""
text_callback = None
if run_manager:
text_callback = partial(run_manager.on_llm_new_token, v... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
9152b5755288-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 |
9152b5755288-1 | 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 |
9152b5755288-2 | """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`."
)
params = se... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
28cd4760119c-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 |
28cd4760119c-1 | """
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 |
28cd4760119c-2 | 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 |
28cd4760119c-3 | )
return cls(
pipeline=pipeline,
model_id=model_id,
model_kwargs=_model_kwargs,
pipeline_kwargs=_pipeline_kwargs,
**kwargs,
)
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
b4f4da8343ad-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 |
b4f4da8343ad-1 | "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 |
b4f4da8343ad-2 | 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 |
b4f4da8343ad-3 | """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."""
openai_api_ke... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-4 | 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 |
b4f4da8343ad-5 | 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 |
b4f4da8343ad-6 | "Please install it with `pip install openai`."
)
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.")
ret... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-7 | The full LLM output.
Example:
.. code-block:: python
response = openai.generate(["Tell me a joke."])
"""
# TODO: write a unit test for this
params = self._invocation_params
params = {**params, **kwargs}
sub_prompts = self.get_sub_prompts(params... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-8 | prompts: List[str],
stop: Optional[List[str]] = None,
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, **kw... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-9 | return self.create_llm_result(choices, prompts, token_usage)
def get_sub_prompts(
self,
params: Dict[str, Any],
prompts: List[str],
stop: Optional[List[str]] = None,
) -> List[List[str]]:
"""Get the sub prompts for llm call."""
if stop is not None:
if ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-10 | ),
)
for choice in sub_choices
]
)
llm_output = {"token_usage": token_usage, "model_name": self.model_name}
return LLMResult(generations=generations, llm_output=llm_output)
def stream(self, prompt: str, stop: Optional[List[str]] = N... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-11 | @property
def _invocation_params(self) -> Dict[str, Any]:
"""Get the parameters used to invoke the model."""
openai_creds: Dict[str, Any] = {
"api_key": self.openai_api_key,
"api_base": self.openai_api_base,
"organization": self.openai_organization,
}
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-12 | enc = tiktoken.encoding_for_model(model_name)
except KeyError:
logger.warning("Warning: model not found. Using cl100k_base encoding.")
model = "cl100k_base"
enc = tiktoken.get_encoding(model)
return enc.encode(
text,
allowed_special=self.allowe... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-13 | "text-ada-001": 2049,
"ada": 2049,
"text-babbage-001": 2040,
"babbage": 2049,
"text-curie-001": 2049,
"curie": 2049,
"davinci": 2049,
"text-davinci-003": 4097,
"text-davinci-002": 4097,
"code-davinci-002": 8001,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-14 | max_tokens = openai.max_token_for_prompt("Tell me a joke.")
"""
num_tokens = self.get_num_tokens(prompt)
return self.max_context_size - num_tokens
[docs]class OpenAI(BaseOpenAI):
"""Wrapper around OpenAI large language models.
To use, you should have the ``openai`` python package install... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-15 | 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_VERSION",
)
values["openai_api_type"] = get_from_dict_... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-16 | .. 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=dict)
"""Hol... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-17 | raise ValueError(f"Found {field_name} supplied twice.")
extra[field_name] = values.pop(field_name)
values["model_kwargs"] = extra
return values
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in env... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-18 | "`openai` has no `ChatCompletion` attribute, this is likely "
"due to an old version of the openai package. Try upgrading it "
"with `pip install --upgrade openai`."
)
warnings.warn(
"You are trying to use a chat model. This way of initializing it is "
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-19 | run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
messages, params = self._get_chat_params(prompts, stop)
params = {**params, **kwargs}
if self.streaming:
response = ""
params["stream"] = True
for stream_resp in... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-20 | self, messages=messages, **params
):
token = stream_resp["choices"][0]["delta"].get("content", "")
response += token
if run_manager:
await run_manager.on_llm_new_token(
token,
)
return... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
b4f4da8343ad-21 | "Please install it with `pip install tiktoken`."
)
enc = tiktoken.encoding_for_model(self.model_name)
return enc.encode(
text,
allowed_special=self.allowed_special,
disallowed_special=self.disallowed_special,
) | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
beb764fe74ad-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
beb764fe74ad-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
beb764fe74ad-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
beb764fe74ad-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::
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
beb764fe74ad-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
beb764fe74ad-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:... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
beb764fe74ad-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
beb764fe74ad-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
cbb70596ee90-0 | Source code for langchain.llms.petals
"""Wrapper around Petals API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils imp... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
cbb70596ee90-1 | """Whether or not to use sampling; use greedy decoding otherwise."""
max_length: Optional[int] = None
"""The maximum length of the sequence to be generated."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call
not explicitly specified.""... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
cbb70596ee90-2 | from petals import DistributedBloomForCausalLM
from transformers import BloomTokenizerFast
model_name = values["model_name"]
values["tokenizer"] = BloomTokenizerFast.from_pretrained(model_name)
values["client"] = DistributedBloomForCausalLM.from_pretrained(model_name)
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
cbb70596ee90-3 | """Call the Petals API."""
params = self._default_params
params = {**params, **kwargs}
inputs = self.tokenizer(prompt, return_tensors="pt")["input_ids"]
outputs = self.client.generate(inputs, **params)
text = self.tokenizer.decode(outputs[0])
if stop is not None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
aa28b4b5edff-0 | Source code for langchain.llms.openllm
"""Wrapper around OpenLLM APIs."""
from __future__ import annotations
import copy
import json
import logging
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Literal,
Optional,
TypedDict,
Union,
overload,
)
from pydantic import PrivateAttr
f... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
aa28b4b5edff-1 | For all available supported models, you can run 'openllm models'.
If you have a OpenLLM server running, you can also use it remotely:
.. code-block:: python
from langchain.llms import OpenLLM
llm = OpenLLM(server_url='http://localhost:3000')
llm("What is the difference be... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
aa28b4b5edff-2 | *,
model_id: Optional[str] = ...,
embedded: Literal[True, False] = ...,
**llm_kwargs: Any,
) -> None:
...
@overload
def __init__(
self,
*,
server_url: str = ...,
server_type: Literal["grpc", "http"] = ...,
**llm_kwargs: Any,
) -> No... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.