id
stringlengths
14
15
text
stringlengths
44
2.47k
source
stringlengths
61
181
b67389fc406f-1
if stop is not None and len(stop) != 1: raise NotImplementedError( f"Manifest currently only supports a single stop token, got {stop}" ) params = self.llm_kwargs or {} params = {**params, **kwargs} if stop is not None: params["stop_token"] = st...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html
fe330bdf4c7e-0
Source code for langchain.llms.petals import logging from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, Field, root_valida...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
fe330bdf4c7e-1
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.""" huggingface_api_key: Optional[str] = None class Config: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
fe330bdf4c7e-2
from transformers import AutoTokenizer model_name = values["model_name"] values["tokenizer"] = AutoTokenizer.from_pretrained(model_name) values["client"] = AutoDistributedModelForCausalLM.from_pretrained( model_name ) values["huggingface_api_ke...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
fe330bdf4c7e-3
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: # I believe this is required si...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html
786acbaea8ac-0
Source code for langchain.llms.gpt4all from functools import partial from typing import Any, Dict, List, Mapping, Optional, Set from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extr...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html
786acbaea8ac-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
786acbaea8ac-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
786acbaea8ac-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
786acbaea8ac-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
6e0e57e64798-0
Source code for langchain.llms.writer from typing import Any, Dict, List, Mapping, Optional import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, root_validator fr...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html
6e0e57e64798-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
6e0e57e64798-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
6e0e57e64798-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
e63d7435172e-0
Source code for langchain.llms.replicate from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import Extra, Field, root_valid...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
e63d7435172e-1
"""Optionally pass in the model version object during initialization to avoid having to make an extra API call to retrieve it during streaming. NOTE: not serializable, is excluded from serialization. """ streaming: bool = False """Whether to stream the results.""" stop: List[str] = Fiel...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
e63d7435172e-2
values["model_kwargs"] = extra return values @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" replicate_api_token = get_from_dict_or_env( values, "replicate_api_token", "REPLICATE_API_...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
e63d7435172e-3
stop_conditions = stop or self.stop for s in stop_conditions: if s in completion: completion = completion[: completion.find(s)] return completion def _stream( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[Callba...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
e63d7435172e-4
model_str, version_str = self.model.split(":") model = replicate_python.models.get(model_str) self.version_obj = model.versions.get(version_str) if self.prompt_key is None: # sort through the openapi schema to get the name of the first input input_properties = sor...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/replicate.html
7eef2176b505-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 langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import ( BaseModel, Extra...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
7eef2176b505-1
values["api_url"] = api_url 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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
7eef2176b505-2
) [docs]def get_default_host() -> str: """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 hos...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
7eef2176b505-3
* **Serving endpoint** (recommended for both production and development). 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 ``clus...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
7eef2176b505-4
If the endpoint model signature is different or you want to set extra params, 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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
7eef2176b505-5
You must not set both ``endpoint_name`` and ``cluster_id``. """ 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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
7eef2176b505-6
raise ValueError( "Neither endpoint_name nor cluster_id was set. " "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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
7eef2176b505-7
cluster_driver_port=self.cluster_driver_port, ) 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...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/databricks.html
e2d4a0f45c50-0
Source code for langchain.llms.koboldai import logging from typing import Any, Dict, List, Optional import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM logger = logging.getLogger(__name__) [docs]def clean_url(url: str) -> str: """Remove trailing slash...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html
e2d4a0f45c50-1
use_memory: Optional[bool] = False """Whether to use the memory from the KoboldAI GUI when generating text.""" max_context_length: Optional[int] = 1600 """Maximum number of tokens to send to the model. minimum: 1 """ max_length: Optional[int] = 80 """Number of tokens to generate. ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html
e2d4a0f45c50-2
"""Typical sampling value. maximum: 1 minimum: 0 """ @property def _llm_type(self) -> str: return "koboldai" 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/koboldai.html
e2d4a0f45c50-3
"typical": self.typical, } if stop is not None: data["stop_sequence"] = stop response = requests.post( f"{clean_url(self.endpoint)}/api/v1/generate", json=data ) response.raise_for_status() json_response = response.json() if ( "...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html
c296f7a41595-0
Source code for langchain.llms.openlm from typing import Any, Dict from langchain.llms.openai import BaseOpenAI from langchain.pydantic_v1 import root_validator [docs]class OpenLM(BaseOpenAI): """OpenLM models.""" @property def _invocation_params(self) -> Dict[str, Any]: return {**{"model": self.mod...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openlm.html
bb52f6e78d64-0
Source code for langchain.llms.self_hosted import importlib.util import logging import pickle from typing import Any, Callable, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
bb52f6e78d64-1
if device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer associated wi...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
bb52f6e78d64-2
model_load_fn=load_pipeline, hardware=gpu, model_reqs=model_reqs, inference_fn=inference_fn ) Example for <2GB model (can be serialized and sent directly to the server): .. code-block:: python from langchain.llms import SelfHostedPipeline i...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
bb52f6e78d64-3
"""Key word arguments to pass to the model load function.""" model_reqs: List[str] = ["./", "torch"] """Requirements to install on hardware to inference the model.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def __init__(self, **kwargs: Any): ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
bb52f6e78d64-4
logger.warning( "Serializing pipeline to send to remote hardware. " "Note, it can be quite slow" "to serialize and send large models with each execution. " "Consider sending the pipeline" "to the cluster and passing the path to the pipeline...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
543414821bd1-0
Source code for langchain.llms.javelin_ai_gateway from __future__ import annotations from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.llms.base import LLM from langchain.pydantic_v1 import Ba...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html
543414821bd1-1
gateway_uri: Optional[str] = None """The URI of the Javelin AI Gateway API.""" params: Optional[Params] = None """Parameters for the Javelin AI Gateway API.""" javelin_api_key: Optional[str] = None """The API key for the Javelin AI Gateway API.""" def __init__(self, **kwargs: Any): try: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html
543414821bd1-2
prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call the Javelin AI Gateway API.""" data: Dict[str, Any] = { "prompt": prompt, **(self.params.dict() if self.params else ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html
543414821bd1-3
resp_dict = resp.dict() try: return resp_dict["llm_response"]["choices"][0]["text"] except KeyError: return "" @property def _llm_type(self) -> str: """Return type of llm.""" return "javelin-ai-gateway"
https://api.python.langchain.com/en/latest/_modules/langchain/llms/javelin_ai_gateway.html
3ceb6c75409b-0
Source code for langchain.llms.aviary import dataclasses import os from typing import Any, Dict, List, Mapping, Optional, Union, cast import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.p...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
3ceb6c75409b-1
except requests.JSONDecodeError as e: raise RuntimeError( f"Error decoding JSON from {request_url}. Text response: {response.text}" ) from e result = sorted( [k.lstrip("/").replace("--", "/") for k in result.keys() if "--" in k] ) return result [docs]def get_completions( ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
3ceb6c75409b-2
Attributes: model: The name of the model to use. Defaults to "amazon/LightGPT". aviary_url: The URL for the Aviary backend. Defaults to None. aviary_token: The bearer token for the Aviary backend. Defaults to None. use_prompt_format: If True, the prompt template for the model will be ign...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
3ceb6c75409b-3
os.environ["AVIARY_URL"] = aviary_url os.environ["AVIARY_TOKEN"] = aviary_token try: aviary_models = get_models() except requests.exceptions.RequestException as e: raise ValueError(e) model = values.get("model") if model and model not in aviary_models: ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
3ceb6c75409b-4
) text = cast(str, output["generated_text"]) if stop: text = enforce_stop_tokens(text, stop) return text
https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html
4801ecf38dab-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 langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import Ba...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html
4801ecf38dab-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
4801ecf38dab-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
4801ecf38dab-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
4801ecf38dab-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
4801ecf38dab-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
4801ecf38dab-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
4ac8b7a68c29-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 langchain.callbacks.manager import ( AsyncCallbackManagerFor...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
4ac8b7a68c29-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
4ac8b7a68c29-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
4ac8b7a68c29-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
4ac8b7a68c29-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
4ac8b7a68c29-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
4ac8b7a68c29-6
import openllm except ImportError as e: raise ImportError( "Could not import openllm. Make sure to install it with " "'pip install openllm'." ) from e copied = copy.deepcopy(self.llm_kwargs) copied.update(kwargs) config = openllm.Au...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html
8635ee565047-0
Source code for langchain.llms.predibase from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import Field [docs]class Predibase(LLM): """Use your Predibase models with Langchain. To ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/predibase.html
49348853d12e-0
Source code for langchain.llms.ai21 from typing import Any, Dict, List, Optional import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.utils import get_from_dict_or_env [docs]...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
49348853d12e-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
49348853d12e-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
49348853d12e-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
2de345ca4705-0
Source code for langchain.llms.bedrock import json from abc import ABC from typing import Any, Dict, Iterator, List, Mapping, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 impo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
2de345ca4705-1
count = 0 # track alternation for i in range(len(input_text)): if input_text[i : i + len(HUMAN_PROMPT)] == HUMAN_PROMPT: if count % 2 == 0: count += 1 else: raise ValueError(ALTERNATION_ERROR) if input_text[i : i + len(ASSISTANT_PROMPT)] ==...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
2de345ca4705-2
input_body["textGenerationConfig"] = {**model_kwargs} else: input_body["inputText"] = prompt if provider == "anthropic" and "max_tokens_to_sample" not in input_body: input_body["max_tokens_to_sample"] = 256 return input_body [docs] @classmethod def prepare_output(c...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
2de345ca4705-3
region_name: Optional[str] = None """The aws region e.g., `us-west-2`. Fallsback to AWS_DEFAULT_REGION env variable or region specified in ~/.aws/config in case it is not provided here. """ credentials_profile_name: Optional[str] = None """The name of the profile in the ~/.aws/credentials or ~/.aws/...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
2de345ca4705-4
import boto3 if values["credentials_profile_name"] is not None: session = boto3.Session(profile_name=values["credentials_profile_name"]) else: # use default credentials session = boto3.Session() client_params = {} if values[...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
2de345ca4705-5
params = {**_model_kwargs, **kwargs} input_body = LLMInputOutputAdapter.prepare_input(provider, prompt, params) body = json.dumps(input_body) accept = "application/json" contentType = "application/json" try: response = self.client.invoke_model( body=bo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
2de345ca4705-6
modelId=self.model_id, accept="application/json", contentType="application/json", ) except Exception as e: raise ValueError(f"Error raised by bedrock service: {e}") for chunk in LLMInputOutputAdapter.prepare_output_stream( provider, res...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
2de345ca4705-7
**kwargs: Any, ) -> Iterator[GenerationChunk]: """Call out to Bedrock service with streaming. Args: prompt (str): The prompt to pass into the model stop (Optional[List[str]], optional): Stop sequences. These will override any stop sequences in the `model_kwarg...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html
cfc499203623-0
Source code for langchain.llms.clarifai import logging from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, root_validator from langc...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
cfc499203623-1
"""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 exists in environment.""" values["pat"] = get_from_d...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
cfc499203623-2
@property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return { **{ "user_id": self.user_id, "app_id": self.app_id, "model_id": self.model_id, } } @property def _llm_type...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
cfc499203623-3
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(raw=prompt)) ) ], ) post_model_outp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
cfc499203623-4
raise ImportError( "Could not import clarifai python package. " "Please install it with `pip install clarifai`." ) # TODO: add caching here. generations = [] batch_size = 32 for i in range(0, len(prompts), batch_size): batch = promp...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html
0ed705810520-0
Source code for langchain.llms.huggingface_endpoint from typing import Any, Dict, List, Mapping, Optional import requests from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.pydantic_v1 import Extra, roo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
0ed705810520-1
"""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.""" huggingfacehub_api_token = get_from_dict_or_env( values, "huggingfac...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
0ed705810520-2
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: The prompt to pass into the model. stop: Optional list of...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
0ed705810520-3
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 {VALID_TASKS} are supported" ) if ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
d653fb48aaf8-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
d653fb48aaf8-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
d653fb48aaf8-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
d653fb48aaf8-3
"""Model name to use.""" 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 "...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-4
"""Maximum number of retries to make when generating.""" 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]] = "al...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-5
"no longer supported. Instead, please use: " "`from langchain.chat_models import ChatOpenAI`" ) return OpenAIChat(**data) return super().__new__(cls) class Config: """Configuration for this pydantic object.""" allow_population_by_field_name = True ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-6
except ImportError: raise ImportError( "Could not import openai python package. " "Please install it with `pip install openai`." ) if values["streaming"] and values["n"] > 1: raise ValueError("Cannot stream results when n > 1.") if valu...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-7
for stream_resp in completion_with_retry( 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, ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-8
"""Call out to OpenAI's endpoint with k unique prompts. 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 respo...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-9
self, prompt=_prompts, run_manager=run_manager, **params ) 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: Li...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-10
"logprobs": generation.generation_info.get("logprobs") if generation.generation_info else None, } ) else: response = await acompletion_with_retry( self, prompt=_prompts, run_manager=run_ma...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-11
generations = [] for i, _ in enumerate(prompts): sub_choices = choices[i * self.n : (i + 1) * self.n] generations.append( [ Generation( text=choice["text"], generation_info=dict( ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-12
[docs] def get_token_ids(self, text: str) -> List[int]: """Get the token IDs using the tiktoken package.""" # tiktoken NOT supported for Python < 3.8 if sys.version_info[1] < 8: return super().get_num_tokens(text) try: import tiktoken except ImportError...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-13
"gpt-4-0613": 8192, "gpt-4-32k": 32768, "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": 1...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-14
context_size = model_token_mapping.get(modelname, None) if context_size is None: raise ValueError( f"Unknown model: {modelname}. Please provide a valid OpenAI model name." "Known models are: " + ", ".join(model_token_mapping.keys()) ) return contex...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-15
return {**{"model": self.model_name}, **super()._invocation_params} [docs]class AzureOpenAI(BaseOpenAI): """Azure-specific OpenAI 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-16
"api_version": self.openai_api_version, } return {**openai_params, **super()._invocation_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "azure" [docs]class OpenAIChat(BaseLLM): """OpenAI Chat large language models. To use, you should have t...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html
d653fb48aaf8-17
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。""" @root_validator(pre=True) def build_extra(cls, values: Dict[str, Any]) -...
https://api.python.langchain.com/en/latest/_modules/langchain/llms/openai.html