id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
2a7a4c91d432-0 | Source code for langchain.llms.clarifai
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_stop_tokens
from langchain.utils im... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
2a7a4c91d432-1 | extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that we have all required info to access Clarifai
platform and python package exists in environment."""
values["pat"] = get_from_dict_or_env(values, "pat", "CLARIFAI_PAT")
user... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
2a7a4c91d432-2 | """Get the identifying parameters."""
return {
**{
"user_id": self.user_id,
"app_id": self.app_id,
"model_id": self.model_id,
}
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "clarif... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
2a7a4c91d432-3 | version_id=self.model_version_id,
inputs=[
resources_pb2.Input(
data=resources_pb2.Data(text=resources_pb2.Text(raw=prompt))
)
],
)
post_model_outputs_response = self.stub.PostModelOutputs(
post_model_outputs_request... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/clarifai.html |
d6a7f58e2d38-0 | Source code for langchain.llms.koboldai
import logging
from typing import Any, Dict, List, Optional
import requests
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
logger = logging.getLogger(__name__)
[docs]def clean_url(url: str) -> str:
"""Remove trailing slash... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html |
d6a7f58e2d38-1 | use_memory: Optional[bool] = False
"""Whether to use the memory from the KoboldAI GUI when generating text."""
max_context_length: Optional[int] = 1600
"""Maximum number of tokens to send to the model.
minimum: 1
"""
max_length: Optional[int] = 80
"""Number of tokens to generate.
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html |
d6a7f58e2d38-2 | """Typical sampling value.
maximum: 1
minimum: 0
"""
@property
def _llm_type(self) -> str:
return "koboldai"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html |
d6a7f58e2d38-3 | "typical": self.typical,
}
if stop is not None:
data["stop_sequence"] = stop
response = requests.post(
f"{clean_url(self.endpoint)}/api/v1/generate", json=data
)
response.raise_for_status()
json_response = response.json()
if (
"... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html |
f9959318c632-0 | Source code for langchain.llms.tongyi
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
from pydantic import Field, root_validator
from requests.exceptions import HTTPError
from tenacity import (
before_sleep_log,
retry,
retry_if_exception_type,
sto... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html |
f9959318c632-1 | elif resp.status_code in [400, 401]:
raise ValueError(
f"status_code: {resp.status_code} \n "
f"code: {resp.code} \n message: {resp.message}"
)
else:
raise HTTPError(
f"HTTP error occurred: status_code: {resp.status_code} \n "
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html |
f9959318c632-2 | To use, you should have the ``dashscope`` python package installed, and the
environment variable ``DASHSCOPE_API_KEY`` set with your API key, or pass
it as a named parameter to the constructor.
Example:
.. code-block:: python
from langchain.llms import Tongyi
Tongyi = tongyi(... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html |
f9959318c632-3 | """Validate that api key and python package exists in environment."""
get_from_dict_or_env(values, "dashscope_api_key", "DASHSCOPE_API_KEY")
try:
import dashscope
except ImportError:
raise ImportError(
"Could not import dashscope python package. "
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html |
f9959318c632-4 | **kwargs,
}
completion = generate_with_retry(
self,
prompt=prompt,
**params,
)
return completion["output"]["text"]
def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[Call... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html |
8b639c23a7b1-0 | Source code for langchain.llms.cerebriumai
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 import enforce_stop_tokens
from... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
8b639c23a7b1-1 | 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} supplied twice.")
logger.warning(
f"""{field_nam... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
8b639c23a7b1-2 | 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 = model_api_request(
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
eb54d591e8cb-0 | Source code for langchain.llms.symblai_nebula
import logging
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html |
eb54d591e8cb-1 | penalty_alpha: Optional[float] = 0.1
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."""
nebula_service_ur... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html |
eb54d591e8cb-2 | return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {
"nebula_service_url": self.nebula_service_url,
"nebula_service_path": self.nebula_service_path,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html |
eb54d591e8cb-3 | "max_new_tokens": self.max_new_tokens,
"top_k": self.top_k,
"penalty_alpha": self.penalty_alpha,
}
if len(self.conversation) == 0:
raise ValueError("Error conversation is empty.")
logger.debug(f"NEBULA _model_kwargs: {_model_kwargs}")
logger.debug(f"NE... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/symblai_nebula.html |
1274ccef8160-0 | Source code for langchain.llms.promptlayer_openai
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 LLMResult
[docs]class PromptLay... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/promptlayer_openai.html |
1274ccef8160-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 |
1274ccef8160-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 |
1274ccef8160-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 |
1274ccef8160-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 |
1274ccef8160-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 |
cb10b8565247-0 | Source code for langchain.llms.self_hosted
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.llms.base import LLM
from langchain.llms.utils import enforce... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
cb10b8565247-1 | if device < 0 and cuda_device_count > 0:
logger.warning(
"Device has %d GPUs available. "
"Provide device={deviceId} to `from_model_id` to use available"
"GPUs for execution. deviceId is -1 for CPU and "
"can be a positive integer associated wi... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
cb10b8565247-2 | model_load_fn=load_pipeline,
hardware=gpu,
model_reqs=model_reqs, inference_fn=inference_fn
)
Example for <2GB model (can be serialized and sent directly to the server):
.. code-block:: python
from langchain.llms import SelfHostedPipeline
i... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
cb10b8565247-3 | """Key word arguments to pass to the model load function."""
model_reqs: List[str] = ["./", "torch"]
"""Requirements to install on hardware to inference the model."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
def __init__(self, **kwargs: Any):
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
cb10b8565247-4 | logger.warning(
"Serializing pipeline to send to remote hardware. "
"Note, it can be quite slow"
"to serialize and send large models with each execution. "
"Consider sending the pipeline"
"to the cluster and passing the path to the pipeline... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
4dcef184a255-0 | Source code for langchain.llms.baseten
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Field
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
logger = logging.getLogger(__name__)
[docs]class Baseten(LLM):
"""Baseten models... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html |
4dcef184a255-1 | def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call to Baseten deployed model endpoint."""
try:
import baseten
except ImportError as exc:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html |
13b2c1101ed6-0 | Source code for langchain.llms.bananadev
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 import enforce_stop_tokens
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
13b2c1101ed6-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 transferred to model_kwargs.
Please confirm that {field_name} is... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
13b2c1101ed6-2 | )
params = self.model_kwargs or {}
params = {**params, **kwargs}
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_... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
ed7bf109950e-0 | Source code for langchain.llms.modal
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.llms.utils import enforce_stop_t... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
ed7bf109950e-1 | Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
values["model_kwargs"] = extra
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
4d6453310205-0 | Source code for langchain.llms.loading
"""Base interface for loading large language model APIs."""
import json
from pathlib import Path
from typing import Union
import yaml
from langchain.llms import type_to_cls_dict
from langchain.llms.base import BaseLLM
[docs]def load_llm_from_config(config: dict) -> BaseLLM:
""... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/loading.html |
d114f8b629e9-0 | Source code for langchain.llms.manifest
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
[docs]class ManifestWrapper(LLM):
"""HazyResearch's Manifest library."""
c... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html |
d114f8b629e9-1 | f"Manifest currently only supports a single stop token, got {stop}"
)
params = self.llm_kwargs or {}
params = {**params, **kwargs}
if stop is not None:
params["stop_token"] = stop
return self.client.run(prompt, **params) | https://api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html |
d65d2d54c20d-0 | Source code for langchain.llms.mosaicml
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchai... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
d65d2d54c20d-1 | )
"""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 arguments to pass to the model."""
retry_sleep: float = 1.0
"""How long to try sleeping for if a rate limit is ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
d65d2d54c20d-2 | 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 inference endpoint.
Args:
prompt: The prompt to pass into the model.
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
d65d2d54c20d-3 | 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):
output_keys = ["data", "output"... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
0efed88b0d1c-0 | Source code for langchain.llms.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 LLM
from langchain.llms.utils ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html |
0efed88b0d1c-1 | ) from e
result = sorted(
[k.lstrip("/").replace("--", "/") for k in result.keys() if "--" in k]
)
return result
[docs]def get_completions(
model: str,
prompt: str,
use_prompt_format: bool = True,
version: str = "",
) -> Dict[str, Union[str, float, int]]:
"""Get completions from ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html |
0efed88b0d1c-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 |
0efed88b0d1c-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 |
3ffb3cb906b6-0 | Source code for langchain.llms.huggingface_pipeline
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 langchain.llms.utils import enforce_stop_tokens
DE... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
3ffb3cb906b6-1 | 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:
"""Configuration for this pydantic object."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
3ffb3cb906b6-2 | f"currently only {VALID_TASKS} are supported"
)
except ImportError as e:
raise ValueError(
f"Could not load the {task} model due to missing dependencies."
) from e
if importlib.util.find_spec("torch") is not None:
import torch
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
3ffb3cb906b6-3 | 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."""
return {
"model_id": self.model_id,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
ac942ed4e6ea-0 | Source code for langchain.llms.writer
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/writer.html |
ac942ed4e6ea-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 |
ac942ed4e6ea-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 |
ac942ed4e6ea-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 |
0705ed1d37e7-0 | Source code for langchain.llms.beam
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 CallbackManagerForLLMRun
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
0705ed1d37e7-1 | 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 endpoint to use"""
model_kwar... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
0705ed1d37e7-2 | """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(
values, "beam_client_secret", "BEAM_CLIENT_SECRET"
)
values... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
0705ed1d37e7-3 | outputs={{"text": beam.Types.String()}},
handler="run.py:beam_langchain",
)
"""
)
script_name = "app.py"
with open(script_name, "w") as file:
file.write(
script.format(
name=self.name,
cpu=self.cpu,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
0705ed1d37e7-4 | if beam.__path__ == "":
raise ImportError
except ImportError:
raise ImportError(
"Could not import beam python package. "
"Please install it with `curl "
"https://raw.githubusercontent.com/slai-labs"
"/get-beam/main/get-... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
0705ed1d37e7-5 | **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_length": self.max_length}
payload.update(kwargs)
headers = {
"Accept": "*/*",
"Accept-Encoding": ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
7514b56c43c5-0 | Source code for langchain.llms.cohere
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
from pydantic import Extra, root_validator
from tenacity import (
before_sleep_log,
retry,
retry_if_exception_type,
stop_after_attempt,
wait_exponential,
)
f... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
7514b56c43c5-1 | return llm.client.generate(**kwargs)
return _completion_with_retry(**kwargs)
[docs]def acompletion_with_retry(llm: Cohere, **kwargs: Any) -> Any:
"""Use tenacity to retry the completion call."""
retry_decorator = _create_retry_decorator(llm)
@retry_decorator
async def _completion_with_retry(**kwargs... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
7514b56c43c5-2 | """Penalizes repeated tokens according to frequency. Between 0 and 1."""
presence_penalty: float = 0.0
"""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"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
7514b56c43c5-3 | "presence_penalty": self.presence_penalty,
"truncate": self.truncate,
}
@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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
7514b56c43c5-4 | Returns:
The string generated by the model.
Example:
.. code-block:: python
response = cohere("Tell me a joke.")
"""
params = self._invocation_params(stop, **kwargs)
response = completion_with_retry(
self, model=self.model, prompt=promp... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
f3ffe365e470-0 | Source code for langchain.llms.vertexai
from __future__ import annotations
import asyncio
from concurrent.futures import Executor, ThreadPoolExecutor
from typing import TYPE_CHECKING, Any, Callable, 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 |
f3ffe365e470-1 | retry_decorator = _create_retry_decorator(llm)
@retry_decorator
def _completion_with_retry(*args: Any, **kwargs: Any) -> Any:
return llm.client.predict(*args, **kwargs)
return _completion_with_retry(*args, **kwargs)
class _VertexAICommon(BaseModel):
client: "_LanguageModel" = None #: :meta priv... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
f3ffe365e470-2 | "The amount of parallelism allowed for requests issued to VertexAI models. "
"Default is 5."
max_retries: int = 6
"""The maximum number of retries to make when generating."""
task_executor: ClassVar[Optional[Executor]] = None
@property
def is_codey_model(self) -> bool:
return is_codey_mo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
f3ffe365e470-3 | @property
def _llm_type(self) -> str:
return "vertexai"
@classmethod
def _get_task_executor(cls, request_parallelism: int = 5) -> Executor:
if cls.task_executor is None:
cls.task_executor = ThreadPoolExecutor(max_workers=request_parallelism)
return cls.task_executor
@... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
f3ffe365e470-4 | else:
from vertexai.preview.language_models import CodeGenerationModel
values["client"] = CodeGenerationModel.from_pretrained(model_name)
except ImportError:
raise_vertex_import_error()
return values
async def _acall(
self,
prompt: str,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
24a46d29d66f-0 | Source code for langchain.llms.minimax
"""Wrapper around Minimax APIs."""
from __future__ import annotations
import logging
from typing import (
Any,
Dict,
List,
Optional,
)
import requests
from pydantic import BaseModel, Extra, Field, PrivateAttr, root_validator
from langchain.callbacks.manager import ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html |
24a46d29d66f-1 | f" error: {response.json()['base_resp']['status_msg']}"
)
return response.json()["reply"]
[docs]class Minimax(LLM):
"""Wrapper around Minimax large language models.
To use, you should have the environment variable
``MINIMAX_API_KEY`` and ``MINIMAX_GROUP_ID`` set with your API key,
or... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html |
24a46d29d66f-2 | """Validate that api key and python package exists in environment."""
values["minimax_api_key"] = get_from_dict_or_env(
values, "minimax_api_key", "MINIMAX_API_KEY"
)
values["minimax_group_id"] = get_from_dict_or_env(
values, "minimax_group_id", "MINIMAX_GROUP_ID"
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html |
24a46d29d66f-3 | )
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
r"""Call out to Minimax's completion endpoint to chat
Args:
prompt: The prompt to pass into the m... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html |
23bb7264b0d1-0 | Source code for langchain.llms.self_hosted_hugging_face
import importlib.util
import logging
from typing import Any, Callable, List, Mapping, Optional
from pydantic import Extra
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.self_hosted import SelfHostedPipeline
from langchain.llms... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
23bb7264b0d1-1 | 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 returns a pipeline for the task.
"""
from transforme... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
23bb7264b0d1-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 associated wi... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
23bb7264b0d1-3 | 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 SelfHostedHuggingFaceLLM
from transformers im... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
23bb7264b0d1-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 |
55859b12a9d6-0 | Source code for langchain.llms.petals
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 import enforce_stop_tokens
from lang... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
55859b12a9d6-1 | max_length: Optional[int] = None
"""The maximum length of the sequence to be generated."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call
not explicitly specified."""
huggingface_api_key: Optional[str] = None
class Config:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
55859b12a9d6-2 | from transformers import AutoTokenizer
model_name = values["model_name"]
values["tokenizer"] = AutoTokenizer.from_pretrained(model_name)
values["client"] = AutoDistributedModelForCausalLM.from_pretrained(
model_name
)
values["huggingface_api_ke... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
55859b12a9d6-3 | params = self._default_params
params = {**params, **kwargs}
inputs = self.tokenizer(prompt, return_tensors="pt")["input_ids"]
outputs = self.client.generate(inputs, **params)
text = self.tokenizer.decode(outputs[0])
if stop is not None:
# I believe this is required si... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/petals.html |
8bff61252699-0 | Source code for langchain.llms.ollama
import json
from typing import Any, Dict, Iterator, List, Mapping, Optional
import requests
from pydantic import Extra
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import BaseLLM
from langchain.schema import LLMResult
from langchain.sche... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html |
8bff61252699-1 | coherent text. (Default: 5.0)"""
num_ctx: Optional[int]
"""Sets the size of the context window used to generate the
next token. (Default: 2048) """
num_gpu: Optional[int]
"""The number of GPUs to use. On macOS it defaults to 1 to
enable metal support, 0 to disable."""
num_thread: Optional[in... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html |
8bff61252699-2 | top_k: Optional[int]
"""Reduces the probability of generating nonsense. A higher value (e.g. 100)
will give more diverse answers, while a lower value (e.g. 10)
will be more conservative. (Default: 40)"""
top_p: Optional[int]
"""Works together with top-k. A higher value (e.g., 0.95) will lead
to ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html |
8bff61252699-3 | prompt: str,
stop: Optional[List[str]] = None,
**kwargs: Any,
) -> Iterator[str]:
if self.stop is not None and stop is not None:
raise ValueError("`stop` found in both the input and default params.")
elif self.stop is not None:
stop = self.stop
elif st... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html |
8bff61252699-4 | def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
"""Call out to Ollama's generate endpoint.
Args:
prompt: The prompt to pass into the m... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html |
8bff61252699-5 | yield chunk
if run_manager:
run_manager.on_llm_new_token(
chunk.text,
verbose=self.verbose,
) | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ollama.html |
b1ed21f5a1ce-0 | Source code for langchain.llms.ctransformers
from functools import partial
from typing import Any, Dict, List, Optional, Sequence
from pydantic import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms.base import LLM
[docs]cla... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
b1ed21f5a1ce-1 | "model_type": self.model_type,
"model_file": self.model_file,
"config": self.config,
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "ctransformers"
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
b1ed21f5a1ce-2 | _run_manager = run_manager or CallbackManagerForLLMRun.get_noop_manager()
for chunk in self.client(prompt, stop=stop, stream=True):
text.append(chunk)
_run_manager.on_llm_new_token(chunk, verbose=self.verbose)
return "".join(text)
async def _acall(
self,
promp... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html |
6da7296b5c09-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 |
6da7296b5c09-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 |
6da7296b5c09-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 |
6da7296b5c09-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 |
6da7296b5c09-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.