id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 53 121 |
|---|---|---|
7744ce54b709-0 | Source code for langchain.llms.beam
"""Wrapper around Beam API."""
import base64
import json
import logging
import subprocess
import textwrap
import time
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import Callba... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
7744ce54b709-1 | max_length=50)
llm._deploy()
call_result = llm._call(input)
"""
model_name: str = ""
name: str = ""
cpu: str = ""
memory: str = ""
gpu: str = ""
python_version: str = ""
python_packages: List[str] = []
max_length: str = ""
url: str = ""
"""model endpoi... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
7744ce54b709-2 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
beam_client_id = get_from_dict_or_env(
values, "beam_client_id", "BEAM_CLIENT_ID"
)
beam_client_secret = get_from_dict_or_env(
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
7744ce54b709-3 | python_packages={python_packages},
)
app.Trigger.RestAPI(
inputs={{"prompt": beam.Types.String(), "max_length": beam.Types.String()}},
outputs={{"text": beam.Types.String()}},
handler="run.py:beam_langchain",
)
"""
)
script_name = "app.... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
7744ce54b709-4 | file.write(script.format(model_name=self.model_name))
def _deploy(self) -> str:
"""Call to Beam."""
try:
import beam # type: ignore
if beam.__path__ == "":
raise ImportError
except ImportError:
raise ImportError(
"Could not... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
7744ce54b709-5 | self,
prompt: str,
stop: Optional[list] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call to Beam."""
url = "https://apps.beam.cloud/" + self.app_id if self.app_id else self.url
payload = {"prompt": prompt, "max_l... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
6424d3c807bc-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 |
6424d3c807bc-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 |
6424d3c807bc-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 |
6424d3c807bc-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 |
6424d3c807bc-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 |
091abb7a9dc7-0 | Source code for langchain.llms.mosaicml
"""Wrapper around MosaicML 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 impo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
091abb7a9dc7-1 | )
"""
endpoint_url: str = (
"https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict"
)
"""Endpoint URL to use."""
inject_instruction_format: bool = False
"""Whether to inject the instruction format into the prompt."""
model_kwargs: Optional[dict] = None
"""Key word ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
091abb7a9dc7-2 | instruction=prompt,
)
return prompt
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
is_retry: bool = False,
**kwargs: Any,
) -> str:
"""Call out to a MosaicML LLM i... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
091abb7a9dc7-3 | raise ValueError(
f"Error raised by inference API: {parsed_response['error']}"
)
# The inference API has changed a couple of times, so we add some handling
# to be robust to multiple response formats.
if isinstance(parsed_response, dict):
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
fffc8ddb2863-0 | Source code for langchain.llms.self_hosted_hugging_face
"""Wrapper around HuggingFace Pipeline API to run on self-hosted remote hardware."""
import importlib.util
import logging
from typing import Any, Callable, List, Mapping, Optional
from pydantic import Extra
from langchain.callbacks.manager import CallbackManagerFo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
fffc8ddb2863-1 | text = enforce_stop_tokens(text, stop)
return text
def _load_transformer(
model_id: str = DEFAULT_MODEL_ID,
task: str = DEFAULT_TASK,
device: int = 0,
model_kwargs: Optional[dict] = None,
) -> Any:
"""Inference function to send to the remote hardware.
Accepts a huggingface model_id and retur... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
fffc8ddb2863-2 | )
if device < 0 and cuda_device_count > 0:
logger.warning(
"Device has %d GPUs available. "
"Provide device={deviceId} to `from_model_id` to use available"
"GPUs for execution. deviceId is -1 for CPU and "
"can be a positive integer ass... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
fffc8ddb2863-3 | hf = SelfHostedHuggingFaceLLM(
model_id="google/flan-t5-large", task="text2text-generation",
hardware=gpu
)
Example passing fn that generates a pipeline (bc the pipeline is not serializable):
.. code-block:: python
from langchain.llms import SelfHosted... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
fffc8ddb2863-4 | """Function to load the model remotely on the server."""
inference_fn: Callable = _generate_text #: :meta private:
"""Inference function to send to the remote hardware."""
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_hugging_face.html |
c1572e618812-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 |
c1572e618812-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 |
c1572e618812-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 |
c1572e618812-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 |
5294a5213db8-0 | Source code for langchain.llms.modal
"""Wrapper around Modal API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
5294a5213db8-1 | logger.warning(
f"""{field_name} was transfered to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
values["model_kwargs"] = extra
return values
@property
d... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
396539f8144f-0 | Source code for langchain.llms.huggingface_hub
"""Wrapper around HuggingFace APIs."""
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enf... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
396539f8144f-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_hub.html |
396539f8144f-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_hub.html |
c35c8ce2ebea-0 | Source code for langchain.llms.deepinfra
"""Wrapper around DeepInfra 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 im... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
c35c8ce2ebea-1 | return values
@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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
c35c8ce2ebea-2 | if res.status_code != 200:
raise ValueError(
"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.JSONDecod... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
7f60c7eae2ab-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 |
7f60c7eae2ab-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 |
7f60c7eae2ab-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 |
7f60c7eae2ab-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 |
c5ad16128bb0-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 |
c5ad16128bb0-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 |
c5ad16128bb0-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 |
49a5e105d115-0 | Source code for langchain.llms.forefrontai
"""Wrapper around ForefrontAI APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.util... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
49a5e105d115-1 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key exists in environment."""
forefrontai_api_key = get_from_dict_or_env(
values, "forefrontai_api_key", "FOREFRONTAI_API_KEY"
)
values["forefrontai_api_key"] = forefrontai_api_key... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
49a5e105d115-2 | """
response = requests.post(
url=self.endpoint_url,
headers={
"Authorization": f"Bearer {self.forefrontai_api_key}",
"Content-Type": "application/json",
},
json={"text": prompt, **self._default_params, **kwargs},
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
37ffbcb10380-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 |
20b4b9965769-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 |
20b4b9965769-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 |
20b4b9965769-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 |
20b4b9965769-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 |
fa0d32304a25-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 |
fa0d32304a25-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 |
fa0d32304a25-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 |
fa0d32304a25-3 | "llm_kwargs": llm_kwargs,
}
)
self._runner = None # type: ignore
self._client = client
else:
assert model_name is not None, "Must provide 'model_name' or 'server_url'"
# since the LLM are relatively huge, we don't actually want to conv... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
fa0d32304a25-4 | tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION
)
svc = bentoml.Service("langchain-openllm", runners=[llm.runner])
@svc.api(input=Text(), output=Text())
def chat(input_text: str):
return agent.run(input_text)
"""
if self._runner is ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
fa0d32304a25-5 | **kwargs: Any,
) -> str:
try:
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)
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
fa0d32304a25-6 | (
prompt,
generate_kwargs,
postprocess_kwargs,
) = self._runner.llm.sanitize_parameters(prompt, **kwargs)
generated_result = await self._runner.generate.async_run(
prompt, **generate_kwargs
)
return self._run... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
d3bf2adbe359-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 |
d3bf2adbe359-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 |
d3bf2adbe359-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 |
d3bf2adbe359-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 |
742d57dc5585-0 | Source code for langchain.llms.azureml_endpoint
"""Wrapper around AzureML Managed Online Endpoint API."""
import json
import urllib.request
from abc import abstractmethod
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, validator
from langchain.callbacks.manager import CallbackManag... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
742d57dc5585-1 | .. code-block:: python
class ContentFormatter(ContentFormatterBase):
content_type = "application/json"
accepts = "application/json"
def format_request_payload(
self,
prompt: str,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
742d57dc5585-2 | )
return str.encode(input_str)
def format_response_payload(self, output: bytes) -> str:
response_json = json.loads(output)
return response_json[0]["0"]
class HFContentFormatter(ContentFormatterBase):
"""Content handler for LLMs from the HuggingFace catalog."""
def format_request_payl... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
742d57dc5585-3 | )
""" # noqa: E501
endpoint_url: str = ""
"""URL of pre-existing Endpoint. Should be passed to constructor or specified as
env var `AZUREML_ENDPOINT_URL`."""
endpoint_api_key: str = ""
"""Authentication Key for Endpoint. Should be passed to constructor or specified as
env var `AZUR... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
742d57dc5585-4 | """Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {
**{"deployment_name": self.deployment_name},
**{"model_kwargs": _model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "azureml... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
dd0613d97371-0 | Source code for langchain.llms.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import Any, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms import OpenAI, OpenAIChat
from langchain.schema import LLMR... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
dd0613d97371-1 | """Call OpenAI generate and then call PromptLayer API to log the request."""
from promptlayer.utils import get_api_key, promptlayer_api_request
request_start_time = datetime.datetime.now().timestamp()
generated_responses = super()._generate(prompts, stop, run_manager)
request_end_time = ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
dd0613d97371-2 | generated_responses = await super()._agenerate(prompts, stop, run_manager)
request_end_time = datetime.datetime.now().timestamp()
for i in range(len(prompts)):
prompt = prompts[i]
generation = generated_responses.generations[i][0]
resp = {
"text": gene... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
dd0613d97371-3 | parameters:
``pl_tags``: List of strings to tag the request with.
``return_pl_id``: If True, the PromptLayer request ID will be
returned in the ``generation_info`` field of the
``Generation`` object.
Example:
.. code-block:: python
from langchain.llms impo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
dd0613d97371-4 | resp,
request_start_time,
request_end_time,
get_api_key(),
return_pl_id=self.return_pl_id,
)
if self.return_pl_id:
if generation.generation_info is None or not isinstance(
generation.generation_in... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
dd0613d97371-5 | generation.generation_info, dict
):
generation.generation_info = {}
generation.generation_info["pl_request_id"] = pl_request_id
return generated_responses | https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
c632f6301701-0 | Source code for langchain.llms.anyscale
"""Wrapper around Anyscale"""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enf... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html |
c632f6301701-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 |
c632f6301701-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 |
83688381afcc-0 | Source code for langchain.llms.octoai_endpoint
"""Wrapper around OctoAI APIs."""
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/octoai_endpoint.html |
83688381afcc-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 |
83688381afcc-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 |
b3f9cd2de67e-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 |
b3f9cd2de67e-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 |
b3f9cd2de67e-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 |
f13f728fdb0c-0 | Source code for langchain.llms.vertexai
"""Wrapper around Google VertexAI models."""
import asyncio
from concurrent.futures import Executor, ThreadPoolExecutor
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional
from pydantic import BaseModel, root_validator
from langchain.callbacks.manager import (
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
f13f728fdb0c-1 | project: Optional[str] = None
"The default GCP project to use when making Vertex API calls."
location: str = "us-central1"
"The default location to use when making API calls."
credentials: Any = None
"The default custom credentials (google.auth.credentials.Credentials) to use "
"when making API ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
f13f728fdb0c-2 | if stop is None and self.stop is not None:
stop = self.stop
if stop:
return enforce_stop_tokens(text, stop)
return text
@property
def _llm_type(self) -> str:
return "vertexai"
@classmethod
def _get_task_executor(cls, request_parallelism: int = 5) -> Execut... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
f13f728fdb0c-3 | tuned_model_name
)
else:
values["client"] = TextGenerationModel.from_pretrained(model_name)
else:
from vertexai.preview.language_models import CodeGenerationModel
values["client"] = CodeGenerationModel.from_pretrained(mo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
8d772eded1bc-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 |
8d772eded1bc-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 |
8d772eded1bc-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 |
8d772eded1bc-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 |
e33d533c875a-0 | Source code for langchain.llms.pipelineai
"""Wrapper around Pipeline Cloud API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html |
e33d533c875a-1 | extra = values.get("pipeline_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if field_name in extra:
raise ValueError(f"Found {field_name} supplied twice.")
logger.warning(
f"""{field_... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html |
e33d533c875a-2 | "Please install it with `pip install pipeline-ai`."
)
client = PipelineCloud(token=self.pipeline_api_key)
params = self.pipeline_kwargs or {}
params = {**params, **kwargs}
run = client.run_pipeline(self.pipeline_key, [prompt, params])
try:
text = run.resul... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html |
9d44ce391a09-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 |
9d44ce391a09-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 |
6bdbf29394fd-0 | Source code for langchain.llms.bedrock
import json
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
class LLMInputOutp... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
6bdbf29394fd-1 | else:
return response_body.get("results")[0].get("outputText")
[docs]class Bedrock(LLM):
"""LLM provider to invoke Bedrock models.
To authenticate, the AWS client uses the following methods to
automatically load credentials:
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/crede... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
6bdbf29394fd-2 | equivalent to the modelId property in the list-foundation-models api"""
model_kwargs: Optional[Dict] = None
"""Key word arguments to pass to the model."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
6bdbf29394fd-3 | """Return type of llm."""
return "amazon_bedrock"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call out to Bedrock service model.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
778646bd4fc3-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 |
778646bd4fc3-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 |
778646bd4fc3-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 |
778646bd4fc3-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 |
778646bd4fc3-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.