id stringlengths 14 16 | text stringlengths 29 2.73k | source stringlengths 49 117 |
|---|---|---|
34de076c5d57-2 | raise ImportError(
"Could not import replicate python package. "
"Please install it with `pip install replicate`."
)
# get the model and version
model_str, version_str = self.model.split(":")
model = replicate_python.models.get(model_str)
versi... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
bafbc7d0fe39-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://python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
bafbc7d0fe39-1 | """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/credentials.html
If a specific credential profile should be used, you must pass
the name of the profil... | https://python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
bafbc7d0fe39-2 | 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, values: Dict) -> Dict:
"""Validate that AWS credentials to and pytho... | https://python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
bafbc7d0fe39-3 | return "amazon_bedrock"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
"""Call out to Bedrock service model.
Args:
prompt: The prompt to pass into the model.
... | https://python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
ada7dbdedc24-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://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
ada7dbdedc24-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://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
ada7dbdedc24-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://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
ada7dbdedc24-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://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
ada7dbdedc24-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://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
ada7dbdedc24-5 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
ce585433b30d-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://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
ce585433b30d-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://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
ce585433b30d-2 | return "huggingface_endpoint"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
prompt: The prompt to pass into t... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
ce585433b30d-3 | 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 stop is not None:
# This is a bit hacky... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
97f56ddeb833-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://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
97f56ddeb833-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://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
97f56ddeb833-2 | 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 = self.model_kwargs or {}
response = mod... | https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
82323e2b0f27-0 | Source code for langchain.llms.stochasticai
"""Wrapper around StochasticAI APIs."""
import logging
import time
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base... | https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
82323e2b0f27-1 | raise ValueError(f"Found {field_name} supplied twice.")
logger.warning(
f"""{field_name} was transfered to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
... | https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
82323e2b0f27-2 | """
params = self.model_kwargs or {}
response_post = requests.post(
url=self.api_url,
json={"prompt": prompt, "params": params},
headers={
"apiKey": f"{self.stochasticai_api_key}",
"Accept": "application/json",
"Content-... | https://python.langchain.com/en/latest/_modules/langchain/llms/stochasticai.html |
afa27ae0a4f8-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://python.langchain.com/en/latest/_modules/langchain/llms/fake.html |
013a01484bb4-0 | Source code for langchain.llms.sagemaker_endpoint
"""Wrapper around 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
f... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
013a01484bb4-1 | """The MIME type of the response data returned from endpoint"""
@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 t... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
013a01484bb4-2 | )
credentials_profile_name = (
"default"
)
se = SagemakerEndpoint(
endpoint_name=endpoint_name,
region_name=region_name,
credentials_profile_name=credentials_profile_name
)
"""
client: Any #: :meta p... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
013a01484bb4-3 | def transform_output(self, output: bytes) -> str:
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[D... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
013a01484bb4-4 | @property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {
**{"endpoint_name": self.endpoint_name},
**{"model_kwargs": _model_kwargs},
}
@property
def _llm_type(s... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
013a01484bb4-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
By Harrison Chase
© Copyright 2023, Harrison Chase.
Las... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
dac4dc7c2960-0 | Source code for langchain.llms.google_palm
"""Wrapper arround Google's PaLM Text APIs."""
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
from pydantic import BaseModel, root_validator
from tenacity import (
before_sleep_log,
retry,
retry_if_exception... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
dac4dc7c2960-1 | ),
before_sleep=before_sleep_log(logger, logging.WARNING),
)
def generate_with_retry(llm: GooglePalm, **kwargs: Any) -> Any:
"""Use tenacity to retry the completion call."""
retry_decorator = _create_retry_decorator()
@retry_decorator
def _generate_with_retry(**kwargs: Any) -> Any:
r... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
dac4dc7c2960-2 | Must be positive."""
max_output_tokens: Optional[int] = None
"""Maximum number of tokens to include in a candidate. Must be greater than zero.
If unset, will default to 64."""
n: int = 1
"""Number of chat completions to generate for each prompt. Note that the API may
not return the full n ... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
dac4dc7c2960-3 | return values
def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> LLMResult:
generations = []
for prompt in prompts:
completion = generate_with_retry(
s... | https://python.langchain.com/en/latest/_modules/langchain/llms/google_palm.html |
2ee1cd014917-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://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
2ee1cd014917-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://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
2ee1cd014917-2 | instruction=prompt,
)
return prompt
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
is_retry: bool = False,
) -> str:
"""Call out to a MosaicML LLM inference endpoint.
... | https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
2ee1cd014917-3 | raise ValueError(
f"Error raised by inference API: {parsed_response['error']}"
)
if "data" not in parsed_response:
raise ValueError(
f"Error raised by inference API, no key data: {parsed_response}"
)
generate... | https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
b565efba966a-0 | Source code for langchain.llms.promptlayer_openai
"""PromptLayer wrapper."""
import datetime
from typing import List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms import OpenAI, OpenAIChat
from langchain.schema import LLMResult... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
b565efba966a-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://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
b565efba966a-2 | for i in range(len(prompts)):
prompt = prompts[i]
generation = generated_responses.generations[i][0]
resp = {
"text": generation.text,
"llm_output": generated_responses.llm_output,
}
pl_request_id = await promptlayer_api_request... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
b565efba966a-3 | ``Generation`` object.
Example:
.. code-block:: python
from langchain.llms import PromptLayerOpenAIChat
openaichat = PromptLayerOpenAIChat(model_name="gpt-3.5-turbo")
"""
pl_tags: Optional[List[str]]
return_pl_id: Optional[bool] = False
def _generate(
self,
... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
b565efba966a-4 | generation.generation_info, dict
):
generation.generation_info = {}
generation.generation_info["pl_request_id"] = pl_request_id
return generated_responses
async def _agenerate(
self,
prompts: List[str],
stop: Optional[List[str]] = N... | https://python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
3a9a9dda96e5-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://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
3a9a9dda96e5-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://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
3a9a9dda96e5-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://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
3a9a9dda96e5-3 | return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
cd05e9768170-0 | Source code for langchain.llms.anthropic
"""Wrapper around Anthropic APIs."""
import re
import warnings
from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple, Union
from pydantic import BaseModel, Extra, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMR... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
cd05e9768170-1 | anthropic_api_key = get_from_dict_or_env(
values, "anthropic_api_key", "ANTHROPIC_API_KEY"
)
try:
import anthropic
values["client"] = anthropic.Client(
api_key=anthropic_api_key,
default_request_timeout=values["default_request_timeout"]... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
cd05e9768170-2 | if stop is None:
stop = []
# Never want model to invent new turns of Human / Assistant dialog.
stop.extend([self.HUMAN_PROMPT])
return stop
[docs]class Anthropic(LLM, _AnthropicCommon):
r"""Wrapper around Anthropic's large language models.
To use, you should have the ``anthro... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
cd05e9768170-3 | extra = Extra.forbid
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "anthropic-llm"
def _wrap_prompt(self, prompt: str) -> str:
if not self.HUMAN_PROMPT or not self.AI_PROMPT:
raise NameError("Please ensure the anthropic package is loaded")
... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
cd05e9768170-4 | if self.streaming:
stream_resp = self.client.completion_stream(
prompt=self._wrap_prompt(prompt),
stop_sequences=stop,
**self._default_params,
)
current_completion = ""
for data in stream_resp:
delta = data["... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
cd05e9768170-5 | **self._default_params,
)
return response["completion"]
[docs] def stream(self, prompt: str, stop: Optional[List[str]] = None) -> Generator:
r"""Call Anthropic completion_stream and return the resulting generator.
BETA: this is a beta feature while we figure out the right abstraction.... | https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
e8b2554ac54e-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://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
e8b2554ac54e-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://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
e8b2554ac54e-2 | return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
e5d668a15059-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://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
e5d668a15059-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://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
e5d668a15059-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://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
e5d668a15059-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://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
e5d668a15059-4 | text_callback = partial(run_manager.on_llm_new_token, verbose=self.verbose)
text = ""
for token in self.client.generate(prompt, **self._default_params()):
if text_callback:
text_callback(token)
text += token
if stop is not None:
text = enforce_... | https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
b9a5d3949e86-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://python.langchain.com/en/latest/_modules/langchain/llms/human.html |
b9a5d3949e86-1 | """Returns the type of LLM."""
return "human-input"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
"""
Displays the prompt to the user and returns their input as a response.... | https://python.langchain.com/en/latest/_modules/langchain/llms/human.html |
2c72b706a043-0 | Source code for langchain.llms.vertexai
"""Wrapper around Google VertexAI models."""
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from pydantic import BaseModel, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils i... | https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
2c72b706a043-1 | "the environment."
@property
def _default_params(self) -> Dict[str, Any]:
base_params = {
"temperature": self.temperature,
"max_output_tokens": self.max_output_tokens,
"top_k": self.top_p,
"top_p": self.top_k,
}
return {**base_params}
d... | https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
2c72b706a043-2 | from vertexai.preview.language_models import TextGenerationModel
except ImportError:
raise_vertex_import_error()
tuned_model_name = values.get("tuned_model_name")
if tuned_model_name:
values["client"] = TextGenerationModel.get_tuned_model(tuned_model_name)
else:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
869ff8f531cc-0 | Source code for langchain.llms.bananadev
"""Wrapper around Banana API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils ... | https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
869ff8f531cc-1 | 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_name} was transfered to model_kwargs.
Please confirm that {field_name} is ... | https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
869ff8f531cc-2 | api_key = self.banana_api_key
model_key = self.model_key
model_inputs = {
# a json specific to your model.
"prompt": prompt,
**params,
}
response = banana.run(api_key, model_key, model_inputs)
try:
text = response["modelOutputs"][0]... | https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
726a69ec9379-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://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html |
726a69ec9379-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://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html |
726a69ec9379-2 | ) -> str:
"""Call out to Anyscale Service endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
... | https://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html |
4b2fad263517-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://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
4b2fad263517-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://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
4b2fad263517-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},
)
response_j... | https://python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
b420600881cb-0 | Source code for langchain.llms.gooseai
"""Wrapper around GooseAI API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.utils import... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
b420600881cb-1 | presence_penalty: float = 0
"""Penalizes repeated tokens."""
n: int = 1
"""How many completions to generate for each prompt."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
logit_bias: Optional[Dict[... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
b420600881cb-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://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
b420600881cb-3 | if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
response = self.client.create(engine=self.model_name, prompt=prompt, **params)
text = response.choices[0].text
return tex... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
b4793aa3a2ac-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://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html |
b4793aa3a2ac-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://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html |
b4793aa3a2ac-2 | "Please install it with `pip install pipeline-ai`."
)
client = PipelineCloud(token=self.pipeline_api_key)
params = self.pipeline_kwargs or {}
run = client.run_pipeline(self.pipeline_key, [prompt, params])
try:
text = run.result_preview[0][0]
except Attribu... | https://python.langchain.com/en/latest/_modules/langchain/llms/pipelineai.html |
bc7f41b2811c-0 | Source code for langchain.llms.huggingface_pipeline
"""Wrapper around HuggingFace Pipeline APIs."""
import importlib.util
import logging
from typing import Any, List, Mapping, Optional
from pydantic import Extra
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from la... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
bc7f41b2811c-1 | """
pipeline: Any #: :meta private:
model_id: str = DEFAULT_MODEL_ID
"""Model name to use."""
model_kwargs: Optional[dict] = None
"""Key word arguments passed to the model."""
pipeline_kwargs: Optional[dict] = None
"""Key word arguments passed to the pipeline."""
class Config:
"... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
bc7f41b2811c-2 | else:
raise ValueError(
f"Got invalid task {task}, "
f"currently only {VALID_TASKS} are supported"
)
except ImportError as e:
raise ValueError(
f"Could not load the {task} model due to missing dependencies."
... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
bc7f41b2811c-3 | )
return cls(
pipeline=pipeline,
model_id=model_id,
model_kwargs=_model_kwargs,
pipeline_kwargs=_pipeline_kwargs,
**kwargs,
)
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
bc7f41b2811c-4 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
e4588129be46-0 | Source code for langchain.llms.self_hosted
"""Run model inference on self-hosted remote hardware."""
import importlib.util
import logging
import pickle
from typing import Any, Callable, List, Mapping, Optional
from pydantic import Extra
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llm... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
e4588129be46-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 ass... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
e4588129be46-2 | llm = SelfHostedPipeline(
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.ll... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
e4588129be46-3 | load_fn_kwargs: Optional[dict] = None
"""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
... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
e4588129be46-4 | if not isinstance(pipeline, str):
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 th... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
8cd16f1d0856-0 | Source code for langchain.llms.openlm
from typing import Any, Dict
from pydantic import root_validator
from langchain.llms.openai import BaseOpenAI
[docs]class OpenLM(BaseOpenAI):
@property
def _invocation_params(self) -> Dict[str, Any]:
return {**{"model": self.model_name}, **super()._invocation_params... | https://python.langchain.com/en/latest/_modules/langchain/llms/openlm.html |
8a503fc0171c-0 | Source code for langchain.llms.rwkv
"""Wrapper for the RWKV model.
Based on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py
https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py
"""
from typing import Any, Dict, List, Mapping, Optional, Set
from pydantic import BaseModel, Extra, roo... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
8a503fc0171c-1 | """Positive values penalize new tokens based on their existing frequency
in the text so far, decreasing the model's likelihood to repeat the same
line verbatim.."""
penalty_alpha_presence: float = 0.4
"""Positive values penalize new tokens based on whether they appear
in the text so far, increasing ... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
8a503fc0171c-2 | """Validate that the python package exists in the environment."""
try:
import tokenizers
except ImportError:
raise ImportError(
"Could not import tokenizers python package. "
"Please install it with `pip install tokenizers`."
)
... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
8a503fc0171c-3 | AVOID_REPEAT_TOKENS = []
AVOID_REPEAT = ",:?!"
for i in AVOID_REPEAT:
dd = self.pipeline.encode(i)
assert len(dd) == 1
AVOID_REPEAT_TOKENS += dd
tokens = [int(x) for x in _tokens]
self.model_tokens += tokens
out: Any = None
while len(to... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
8a503fc0171c-4 | occurrence[token] += 1
logits = self.run_rnn([token])
xxx = self.tokenizer.decode(self.model_tokens[out_last:])
if "\ufffd" not in xxx: # avoid utf-8 display issues
decoded += xxx
out_last = begin + i + 1
if i >= self.max_tokens_per_ge... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
bdc5d3131f6c-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://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
bdc5d3131f6c-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://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
bdc5d3131f6c-2 | text.append(chunk)
_run_manager.on_llm_new_token(chunk, verbose=self.verbose)
return "".join(text)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
d04aca0fd0ca-0 | Source code for langchain.llms.petals
"""Wrapper around Petals API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils imp... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.