id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
3af31488ec12-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 |
cc7202c43bb3-0 | Source code for langchain.llms.nlpcloud
"""Wrapper around NLPCloud 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.utils import get_from_dict_or_e... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
cc7202c43bb3-1 | """Total probability mass of tokens to consider at each step."""
top_k: int = 50
"""The number of highest probability tokens to keep for top-k filtering."""
repetition_penalty: float = 1.0
"""Penalizes repeated tokens. 1.0 means no penalty."""
length_penalty: float = 1.0
"""Exponential penalty t... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
cc7202c43bb3-2 | @property
def _default_params(self) -> Mapping[str, Any]:
"""Get the default parameters for calling NLPCloud API."""
return {
"temperature": self.temperature,
"min_length": self.min_length,
"max_length": self.max_length,
"length_no_input": self.length_... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
cc7202c43bb3-3 | The string generated by the model.
Example:
.. code-block:: python
response = nlpcloud("Tell me a joke.")
"""
if stop and len(stop) > 1:
raise ValueError(
"NLPCloud only supports a single stop sequence per generation."
"Pass... | https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html |
6f448721791e-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 |
6f448721791e-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 |
6f448721791e-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 |
6f448721791e-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 |
6f448721791e-4 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
1476fb476d70-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 |
1476fb476d70-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 |
5b801df9af67-0 | Source code for langchain.llms.huggingface_text_gen_inference
"""Wrapper around Huggingface text generation inference API."""
from functools import partial
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html |
5b801df9af67-1 | inference_server_url = "http://localhost:8010/",
max_new_tokens = 512,
top_k = 10,
top_p = 0.95,
typical_p = 0.95,
temperature = 0.01,
repetition_penalty = 1.03,
)
print(llm("What is Deep Learning?"))... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html |
5b801df9af67-2 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that python package exists in environment."""
try:
import text_generation
values["client"] = text_generation.Client(
values["inference_server_url"], timeout=values["timeout"]
... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html |
5b801df9af67-3 | text_callback = None
if run_manager:
text_callback = partial(
run_manager.on_llm_new_token, verbose=self.verbose
)
params = {
"stop_sequences": stop,
"max_new_tokens": self.max_new_tokens,
"top_k"... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html |
9e44ec0afe7e-0 | Source code for langchain.llms.cohere
"""Wrapper around Cohere 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 enforce_sto... | https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
9e44ec0afe7e-1 | """Penalizes repeated tokens. Between 0 and 1."""
truncate: Optional[str] = None
"""Specify how the client handles inputs longer than the maximum token
length: Truncate from START, END or NONE"""
cohere_api_key: Optional[str] = None
stop: Optional[List[str]] = None
class Config:
"""Confi... | https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
9e44ec0afe7e-2 | def _llm_type(self) -> str:
"""Return type of llm."""
return "cohere"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
"""Call out to Cohere's generate endpoint.
Args:... | https://python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
046c7844323b-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://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
046c7844323b-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://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
046c7844323b-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://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
046c7844323b-3 | headers={"Authorization": f"Bearer {self.ai21_api_key}"},
json={"prompt": prompt, "stopSequences": stop, **self._default_params},
)
if response.status_code != 200:
optional_detail = response.json().get("error")
raise ValueError(
f"AI21 /complete call f... | https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html |
61b3c310a900-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 |
61b3c310a900-1 | """Whether or not to use sampling; use greedy decoding otherwise."""
max_length: Optional[int] = None
"""The maximum length of the sequence to be generated."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call
not explicitly specified.""... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
61b3c310a900-2 | from petals import DistributedBloomForCausalLM
from transformers import BloomTokenizerFast
model_name = values["model_name"]
values["tokenizer"] = BloomTokenizerFast.from_pretrained(model_name)
values["client"] = DistributedBloomForCausalLM.from_pretrained(model_name)
... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
61b3c310a900-3 | """Call the Petals API."""
params = self._default_params
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 since... | https://python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
f1ffd5e41703-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://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
f1ffd5e41703-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://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
f1ffd5e41703-2 | 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 host:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
f1ffd5e41703-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://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
f1ffd5e41703-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://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
f1ffd5e41703-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://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
f1ffd5e41703-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://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
f1ffd5e41703-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://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html |
d119a9ab854d-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 CallbackManagerForLLMRun
from langchain.llms.base import LLM
[docs]class FakeListLLM(LLM):
"""Fake LLM wrapper for testing purposes."""
respons... | https://python.langchain.com/en/latest/_modules/langchain/llms/fake.html |
96cf3b4017b5-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://python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
96cf3b4017b5-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://python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
81d1db83149e-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 |
81d1db83149e-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 |
81d1db83149e-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 |
81d1db83149e-3 | text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
de293ff00556-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 |
de293ff00556-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 |
de293ff00556-2 | _run_manager.on_llm_new_token(chunk, verbose=self.verbose)
return "".join(text)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
4f1ff899fd03-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 |
4f1ff899fd03-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 |
4f1ff899fd03-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 |
4f1ff899fd03-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 |
910b4f59783e-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 |
910b4f59783e-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 |
910b4f59783e-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 |
910b4f59783e-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 |
910b4f59783e-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 |
910b4f59783e-5 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
09a8609e3505-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 |
09a8609e3505-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 |
09a8609e3505-2 | try:
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... | https://python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
f686a804fda2-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 |
f686a804fda2-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 |
f686a804fda2-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 |
2f52edd4be46-0 | Source code for langchain.llms.llamacpp
"""Wrapper around llama.cpp."""
import logging
from typing import Any, Dict, Generator, List, Optional
from pydantic import Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
logger = logging.getLogger(__name... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
2f52edd4be46-1 | f16_kv: bool = Field(True, alias="f16_kv")
"""Use half-precision for key/value cache."""
logits_all: bool = Field(False, alias="logits_all")
"""Return logits for all tokens, not just the last token."""
vocab_only: bool = Field(False, alias="vocab_only")
"""Only load the vocabulary, no weights."""
... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
2f52edd4be46-2 | """Whether to echo the prompt."""
stop: Optional[List[str]] = []
"""A list of strings to stop generation when encountered."""
repeat_penalty: Optional[float] = 1.1
"""The penalty to apply to repeated tokens."""
top_k: Optional[int] = 40
"""The top-k value to use for sampling."""
last_n_token... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
2f52edd4be46-3 | except ImportError:
raise ModuleNotFoundError(
"Could not import llama-cpp-python library. "
"Please install the llama-cpp-python library to "
"use this embedding model: pip install llama-cpp-python"
)
except Exception as e:
rai... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
2f52edd4be46-4 | Returns:
Dictionary containing the combined parameters.
"""
# Raise error if stop sequences are in both input and default params
if self.stop and stop is not None:
raise ValueError("`stop` found in both the input and default params.")
params = self._default_params... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
2f52edd4be46-5 | result = self.client(prompt=prompt, **params)
return result["choices"][0]["text"]
[docs] def stream(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> Generator[Dict, None, None]:
"""Yields results... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
2f52edd4be46-6 | for chunk in result:
token = chunk["choices"][0]["text"]
log_probs = chunk["choices"][0].get("logprobs", None)
if run_manager:
run_manager.on_llm_new_token(
token=token, verbose=self.verbose, log_probs=log_probs
)
yield ... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
ed5bafea50fe-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 |
ed5bafea50fe-1 | 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_name} was transfered to model_kwargs.
... | https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
ed5bafea50fe-2 | params = self.model_kwargs or {}
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:
... | https://python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
069320713a9f-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 |
069320713a9f-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 |
069320713a9f-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 |
3b825901a272-0 | Source code for langchain.llms.replicate
"""Wrapper around Replicate API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.utils im... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
3b825901a272-1 | """Build extra kwargs from additional params that were passed in."""
all_required_field_names = {field.alias for field in cls.__fields__.values()}
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if ... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
3b825901a272-2 | except ImportError:
raise ImportError(
"Could not import replicate python package. "
"Please install it with `pip install replicate`."
)
# get the model and version
model_str, version_str = self.model.split(":")
model = replicate_python.mod... | https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html |
327e9c8f6473-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 |
327e9c8f6473-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 |
327e9c8f6473-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 |
327e9c8f6473-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 |
327e9c8f6473-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 |
327e9c8f6473-5 | text = self.content_handler.transform_output(response["Body"])
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 H... | https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
3e42cb4307d0-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 |
3e42cb4307d0-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 |
3e42cb4307d0-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 |
3e42cb4307d0-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 |
4e628ad0b928-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 |
4e628ad0b928-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 |
4e628ad0b928-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 |
4e628ad0b928-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 |
4e628ad0b928-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 |
2b10162f2488-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 |
2b10162f2488-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 |
2b10162f2488-2 | starting from beginning if the context has run out."""
client: Any = None #: :meta private:
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@staticmethod
def _model_param_names() -> Set[str]:
return {
"n_ctx",
"n_predict",... | https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
2b10162f2488-3 | except ImportError:
raise ValueError(
"Could not import gpt4all python package. "
"Please install it with `pip install gpt4all`."
)
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameter... | https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
2b10162f2488-4 | text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html |
0640766354ad-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 |
0640766354ad-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 |
0640766354ad-2 | text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.