id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
6da7296b5c09-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 |
6da7296b5c09-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 |
6da7296b5c09-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 |
7ee100406056-0 | Source code for langchain.llms.openllm
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
from langchain.callbacks.manager imp... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
7ee100406056-1 | )
llm("What is the difference between a duck and a goose?")
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(se... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
7ee100406056-2 | @overload
def __init__(
self,
model_name: Optional[str] = ...,
*,
model_id: Optional[str] = ...,
embedded: Literal[True, False] = ...,
**llm_kwargs: Any,
) -> None:
...
@overload
def __init__(
self,
*,
server_url: str = ...,... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
7ee100406056-3 | super().__init__(
**{
"server_url": server_url,
"server_type": server_type,
"llm_kwargs": llm_kwargs,
}
)
self._runner = None # type: ignore
self._client = client
else:
as... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
7ee100406056-4 | model_id='google/flan-t5-large',
embedded=False,
)
tools = load_tools(["serpapi", "llm-math"], llm=llm)
agent = initialize_agent(
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION
)
svc = bentoml.Service("langchain-openllm... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
7ee100406056-5 | return "openllm_client" if self._client else "openllm"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: CallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> str:
try:
import openllm
except ImportError as e:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
7ee100406056-6 | )
if self._client:
return await self._client.acall(
"generate", prompt, **config.model_dump(flatten=True)
)
else:
assert self._runner is not None
(
prompt,
generate_kwargs,
postprocess_kwargs,... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
dc2d5e31a2e9-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
[docs]class LLMInp... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
dc2d5e31a2e9-1 | else:
return response_body.get("results")[0].get("outputText")
[docs]class Bedrock(LLM):
"""Bedrock models.
To authenticate, the AWS client uses the following methods to
automatically load credentials:
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
If a sp... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
dc2d5e31a2e9-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."""
endpoint_url: Optional[str] = None
"""Needed if you don't want to default to us-east-1 endpoint"""
class Config:
"""Configuration for thi... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
dc2d5e31a2e9-3 | """Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {
**{"model_kwargs": _model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "amazon_bedrock"
def _call(
self,
prompt: str... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
7161dc4a1860-0 | Source code for langchain.llms.llamacpp
import logging
from typing import Any, Dict, Iterator, List, Optional
from pydantic import Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.schema.output import GenerationChunk
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
7161dc4a1860-1 | """Seed. If -1, a random seed is used."""
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")
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
7161dc4a1860-2 | echo: Optional[bool] = False
"""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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
7161dc4a1860-3 | "n_threads",
"n_batch",
"use_mmap",
"last_n_tokens_size",
"verbose",
]
model_params = {k: values[k] for k in model_param_names}
# For backwards compatibility, only include if non-null.
if values["n_gpu_layers"] is not None:
mode... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
7161dc4a1860-4 | "max_tokens": self.max_tokens,
"temperature": self.temperature,
"top_p": self.top_p,
"logprobs": self.logprobs,
"echo": self.echo,
"stop_sequences": self.stop, # key here is convention among LLM classes
"repeat_penalty": self.repeat_penalty,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
7161dc4a1860-5 | run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call the Llama model and return the output.
Args:
prompt: The prompt to use for generation.
stop: A list of strings to stop generation when encountered.
Returns:
Th... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
7161dc4a1860-6 | Args:
prompt: The prompts to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
A generator representing the stream of tokens being generated.
Yields:
A dictionary like objects containing a string token and metadata.
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
b5a54823d981-0 | Source code for langchain.llms.predibase
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Field
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
[docs]class Predibase(LLM):
"""Use your Predibase models with Langchain.
To use, you shou... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/predibase.html |
0c01f6b18b31-0 | Source code for langchain.llms.azureml_endpoint
import json
import urllib.request
import warnings
from abc import abstractmethod
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base impor... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
0c01f6b18b31-1 | result = response.read()
return result
[docs]class ContentFormatterBase:
"""Transform request and response of AzureML endpoint to match with
required schema.
"""
"""
Example:
.. code-block:: python
class ContentFormatter(ContentFormatterBase):
con... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
0c01f6b18b31-2 | prompt = prompt.replace(escape_sequence, escaped_sequence)
return prompt
[docs] @abstractmethod
def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes:
"""Formats the request body according to the input schema of
the model. Returns bytes or seekable file like object in... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
0c01f6b18b31-3 | """
)
[docs]class HFContentFormatter(ContentFormatterBase):
"""Content handler for LLMs from the HuggingFace catalog."""
[docs] def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes:
ContentFormatterBase.escape_special_characters(prompt)
request_payload = json.dumps(
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
0c01f6b18b31-4 | "parameters": model_kwargs,
}
}
)
return str.encode(request_payload)
[docs] def format_response_payload(self, output: bytes) -> str:
"""Formats response"""
return json.loads(output)[0]["0"]
[docs]class AzureMLOnlineEndpoint(LLM, BaseModel):
"""Azure ML ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
0c01f6b18b31-5 | @validator("http_client", always=True, allow_reuse=True)
@classmethod
def validate_client(cls, field_value: Any, values: Dict) -> AzureMLEndpointClient:
"""Validate that api key and python package exists in environment."""
endpoint_key = get_from_dict_or_env(
values, "endpoint_api_ke... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
0c01f6b18b31-6 | The string generated by the model.
Example:
.. code-block:: python
response = azureml_model("Tell me a joke.")
"""
_model_kwargs = self.model_kwargs or {}
request_payload = self.content_formatter.format_request_payload(
prompt, _model_kwargs
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
955ebf401107-0 | Source code for langchain.llms.gpt4all
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 langchain.llms.utils import enforce_... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
955ebf401107-1 | """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 |
955ebf401107-2 | class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@staticmethod
def _model_param_names() -> Set[str]:
return {
"max_tokens",
"n_predict",
"top_k",
"top_p",
"temp",
"n_batch",
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
955ebf401107-3 | if values["n_threads"] is not None:
# set n_threads
values["client"].model.set_thread_count(values["n_threads"])
try:
values["backend"] = values["client"].model_type
except AttributeError:
# The below is for compatibility with GPT4All Python bindings <= 0.... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
955ebf401107-4 | text = ""
params = {**self._default_params(), **kwargs}
for token in self.client.generate(prompt, **params):
if text_callback:
text_callback(token)
text += token
if stop is not None:
text = enforce_stop_tokens(text, stop)
return text | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
71fd6876afdf-0 | Source code for langchain.llms.gooseai
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 get_from_dict_or_env
logger = log... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
71fd6876afdf-1 | """Penalizes repeated tokens."""
n: int = 1
"""How many completions to generate for each prompt."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
logit_bias: Optional[Dict[str, float]] = Field(default_fac... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
71fd6876afdf-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 |
71fd6876afdf-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 |
530be5b3f987-0 | Source code for langchain.llms.deepinfra
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 enforce_stop_tokens
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
530be5b3f987-1 | @property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"model_id": self.model_id},
**{"model_kwargs": self.model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
530be5b3f987-2 | "Error raised by inference API HTTP code: %s, %s"
% (res.status_code, res.text)
)
try:
t = res.json()
text = t["results"][0]["generated_text"]
except requests.exceptions.JSONDecodeError as e:
raise ValueError(
f"Error raised... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
642a33144b92-0 | Source code for langchain.llms.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 enforce_stop_tokens
from langchai... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html |
642a33144b92-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_... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html |
642a33144b92-2 | def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call out to Anyscale Service endpoint.
Args:
prompt: The prompt to pass into the model.
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html |
8b3003335e76-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 |
8b3003335e76-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 |
ab96b63333ff-0 | Source code for langchain.llms.octoai_endpoint
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
from langchain.utils i... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html |
ab96b63333ff-1 | """OCTOAI API Token"""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator(allow_reuse=True)
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
octoai_api_toke... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html |
ab96b63333ff-2 | _model_kwargs = self.model_kwargs or {}
# Prepare the payload JSON
parameter_payload = {"inputs": prompt, "parameters": _model_kwargs}
try:
# Initialize the OctoAI client
from octoai import client
octoai_client = client.Client(token=self.octoai_api_token)
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html |
6127615a0cd8-0 | Source code for langchain.llms.anthropic
import re
import warnings
from typing import Any, AsyncIterator, Callable, Dict, Iterator, List, Mapping, Optional
from pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
6127615a0cd8-1 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
values["anthropic_api_key"] = get_from_dict_or_env(
values, "anthropic_api_key", "ANTHROPIC_API_KEY"
)
# Get custom api url from en... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
6127615a0cd8-2 | d = {
"max_tokens_to_sample": self.max_tokens_to_sample,
"model": self.model,
}
if self.temperature is not None:
d["temperature"] = self.temperature
if self.top_k is not None:
d["top_k"] = self.top_k
if self.top_p is not None:
d... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
6127615a0cd8-3 | response = model("What are the biggest risks facing humanity?")
# Or if you want to use the chat mode, build a few-shot-prompt, or
# put words in the Assistant's mouth, use HUMAN_PROMPT and AI_PROMPT:
raw_prompt = "What are the biggest risks facing humanity?"
prompt = f"{... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
6127615a0cd8-4 | def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
r"""Call out to Anthropic's completion endpoint.
Args:
prompt: The prompt to pass into the model.
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
6127615a0cd8-5 | ):
completion += chunk.text
return completion
stop = self._get_anthropic_stop(stop)
params = {**self._default_params, **kwargs}
response = await self.async_client.completions.create(
prompt=self._wrap_prompt(prompt),
stop_sequences=stop,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
6127615a0cd8-6 | prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> AsyncIterator[GenerationChunk]:
r"""Call Anthropic completion_stream and return the resulting generator.
Args:
prompt: The prompt to pas... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
f94c3bb5270d-0 | Source code for langchain.llms.sagemaker_endpoint
"""Sagemaker InvokeEndpoint API."""
from abc import abstractmethod
from typing import Any, Dict, Generic, List, Mapping, Optional, TypeVar, Union
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.l... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
f94c3bb5270d-1 | [docs] @abstractmethod
def transform_input(self, prompt: INPUT_TYPE, model_kwargs: Dict) -> bytes:
"""Transforms the input to a format that model can accept
as the request Body. Should return bytes or seekable file
like object in the format specified in the content_type
request he... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
f94c3bb5270d-2 | "default"
)
se = SagemakerEndpoint(
endpoint_name=endpoint_name,
region_name=region_name,
credentials_profile_name=credentials_profile_name
)
"""
client: Any #: :meta private:
endpoint_name: str = ""
"""The name of the ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
f94c3bb5270d-3 | response_json = json.loads(output.read().decode("utf-8"))
return response_json[0]["generated_text"]
"""
model_kwargs: Optional[Dict] = None
"""Key word arguments to pass to the model."""
endpoint_kwargs: Optional[Dict] = None
"""Optional attributes passed to the invoke_endpoint
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
f94c3bb5270d-4 | """Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {
**{"endpoint_name": self.endpoint_name},
**{"model_kwargs": _model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "sagemaker_e... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
f94c3bb5270d-5 | if stop is not None:
# This is a bit hacky, but I can't figure out a better way to enforce
# stop tokens when making calls to the sagemaker endpoint.
text = enforce_stop_tokens(text, stop)
return text | https://api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
cb32612253d2-0 | Source code for langchain.llms.textgen
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__)
[docs]class TextGen(LLM):
"""text-ge... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
cb32612253d2-1 | """If not set to 1, select tokens with probabilities adding up to less than this
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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
cb32612253d2-2 | """Early stopping"""
seed: int = Field(-1, alias="seed")
"""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
"""Trun... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
cb32612253d2-3 | "no_repeat_ngram_size": self.no_repeat_ngram_size,
"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_toke... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
cb32612253d2-4 | # then sets it as configured, or default to an empty list:
params["stop"] = self.stopping_strings or stop or []
return params
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
bdf173021316-0 | Source code for langchain.llms.nlpcloud
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_env
[docs]class NLPCloud(LLM):
""... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
bdf173021316-1 | bad_words: List[str] = []
"""List of tokens not allowed to be generated."""
top_p: int = 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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
bdf173021316-2 | raise ImportError(
"Could not import nlpcloud python package. "
"Please install it with `pip install nlpcloud`."
)
return values
@property
def _default_params(self) -> Mapping[str, Any]:
"""Get the default parameters for calling NLPCloud API."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
bdf173021316-3 | **kwargs: Any,
) -> str:
"""Call out to NLPCloud's create endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Not supported by this interface (pass in init method)
Returns:
The string generated by the model.
Example:
.. cod... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
13308b12162c-0 | Source code for langchain.llms.aleph_alpha
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 enforce_stop_tokens
from langchain.utils impo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
13308b12162c-1 | presence_penalty: float = 0.0
"""Penalizes repeated tokens."""
frequency_penalty: float = 0.0
"""Penalizes repeated tokens according to frequency."""
repetition_penalties_include_prompt: Optional[bool] = False
"""Flag deciding whether presence penalty or frequency penalty are
updated from the pr... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
13308b12162c-2 | sequence_penalty: float = 0.0
sequence_penalty_min_length: int = 2
use_multiplicative_sequence_penalty: bool = False
completion_bias_inclusion: Optional[Sequence[str]] = None
completion_bias_inclusion_first_token_only: bool = False
completion_bias_exclusion: Optional[Sequence[str]] = None
comple... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
13308b12162c-3 | """Determines in which datacenters the request may be processed.
You can either set the parameter to "aleph-alpha" or omit it (defaulting to None).
Not setting this value, or setting it to None, gives us maximal
flexibility in processing your request in our
own datacenters and on servers hosted with ot... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
13308b12162c-4 | """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:
from aleph_alpha_client import Client
values["client"] = Client(
token... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
13308b12162c-5 | "logit_bias": self.logit_bias,
"log_probs": self.log_probs,
"tokens": self.tokens,
"disable_optimizations": self.disable_optimizations,
"minimum_tokens": self.minimum_tokens,
"echo": self.echo,
"use_multiplicative_frequency_penalty": self.use_multi... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
13308b12162c-6 | run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call out to Aleph Alpha's completion endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
T... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
9305743edd50-0 | Source code for langchain.llms.openai
from __future__ import annotations
import logging
import sys
import warnings
from typing import (
AbstractSet,
Any,
AsyncIterator,
Callable,
Collection,
Dict,
Iterator,
List,
Literal,
Mapping,
Optional,
Set,
Tuple,
Union,
)
fr... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-1 | finish_reason=stream_response["choices"][0].get("finish_reason", None),
logprobs=stream_response["choices"][0].get("logprobs", None),
),
)
def _update_response(response: Dict[str, Any], stream_response: Dict[str, Any]) -> None:
"""Update response from the stream response."""
response["ch... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-2 | llm: Union[BaseOpenAI, OpenAIChat],
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> Any:
"""Use tenacity to retry the completion call."""
retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
@retry_decorator
def _completion_with_retry(**kwargs: Any)... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-3 | temperature: float = 0.7
"""What sampling temperature to use."""
max_tokens: int = 256
"""The maximum number of tokens to generate in the completion.
-1 returns as many tokens as possible given the prompt and
the models maximal context size."""
top_p: float = 1
"""Total probability mass of t... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-4 | streaming: bool = False
"""Whether to stream the results or not."""
allowed_special: Union[Literal["all"], AbstractSet[str]] = set()
"""Set of special tokens that are allowed。"""
disallowed_special: Union[Literal["all"], Collection[str]] = "all"
"""Set of special tokens that are not allowed。"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-5 | )
return OpenAIChat(**data)
return super().__new__(cls)
class Config:
"""Configuration for this pydantic object."""
allow_population_by_field_name = True
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra kwarg... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-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 |
9305743edd50-7 | self, prompt=prompt, run_manager=run_manager, **params
):
chunk = _stream_response_to_generation_chunk(stream_resp)
yield chunk
if run_manager:
run_manager.on_llm_new_token(
chunk.text,
verbose=self.verbose,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-8 | Args:
prompts: The prompts to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The full LLM output.
Example:
.. code-block:: python
response = openai.generate(["Tell me a joke."])
"""
#... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-9 | )
choices.extend(response["choices"])
update_token_usage(_keys, response, token_usage)
return self.create_llm_result(choices, prompts, token_usage)
async def _agenerate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: O... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-10 | if generation.generation_info
else None,
}
)
else:
response = await acompletion_with_retry(
self, prompt=_prompts, run_manager=run_manager, **params
)
choices.extend(response["choi... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-11 | generations.append(
[
Generation(
text=choice["text"],
generation_info=dict(
finish_reason=choice.get("finish_reason"),
logprobs=choice.get("logprobs"),
),
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-12 | 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 in order to calculate get_num_tokens. "
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-13 | "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,
"text-babbage-001": 2040... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-14 | 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)
[docs] def max_tokens_for_prompt(self, prompt: str) -> int:
"""Calculate the maximum number of tokens possible to generate ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-15 | 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 |
9305743edd50-16 | return "azure"
[docs]class OpenAIChat(BaseLLM):
"""OpenAI Chat large language models.
To use, you should have the ``openai`` python package installed, and the
environment variable ``OPENAI_API_KEY`` set with your API key.
Any parameters that are valid to be passed to the openai.create call can be passed... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-17 | @root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra kwargs from additional params that were passed in."""
all_required_field_names = {field.alias for field in cls.__fields__.values()}
extra = values.get("model_kwargs", {})
for fiel... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-18 | openai.organization = openai_organization
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. "
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-19 | if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
if params.get("max_tokens") == -1:
# for ChatGPT api, omitting max_tokens is equivalent to having no limit
del pa... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-20 | token = stream_resp["choices"][0]["delta"].get("content", "")
yield GenerationChunk(text=token)
if run_manager:
await run_manager.on_llm_new_token(token)
def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Op... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html |
9305743edd50-21 | if self.streaming:
generation: Optional[GenerationChunk] = None
async for chunk in self._astream(prompts[0], stop, run_manager, **kwargs):
if generation is None:
generation = chunk
else:
generation += chunk
asser... | 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.