id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
bb51a9ee8dd6-3 | )
for event in stream:
chunk = event.get("chunk")
if chunk:
chunk_obj = json.loads(chunk.get("bytes").decode())
if provider == "cohere" and (
chunk_obj["is_finished"]
or chunk_obj[cls.provider_to_output_key_map[provi... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
bb51a9ee8dd6-4 | """Needed if you don't want to default to us-east-1 endpoint"""
streaming: bool = False
"""Whether to stream the results."""
provider_stop_sequence_key_name_map: Mapping[str, str] = {
"anthropic": "stop_sequences",
"amazon": "stopSequences",
"ai21": "stop_sequences",
"cohere"... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
bb51a9ee8dd6-5 | "Please check that credentials in the specified "
"profile name are valid."
) from e
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
bb51a9ee8dd6-6 | prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> Iterator[GenerationChunk]:
_model_kwargs = self.model_kwargs or {}
provider = self._get_provider()
if stop:
if provider not in self.p... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
bb51a9ee8dd6-7 | 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 profile from the ~/.aws/credentials file that is to be used.
Make sure the credentials / roles used have the required policies to
access the Bedro... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
bb51a9ee8dd6-8 | stop (Optional[List[str]], optional): Stop sequences. These will
override any stop sequences in the `model_kwargs` attribute.
Defaults to None.
run_manager (Optional[CallbackManagerForLLMRun], optional): Callback
run managers used to process the output. Defaul... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
bb51a9ee8dd6-9 | else:
return super().get_num_tokens(text)
[docs] def get_token_ids(self, text: str) -> List[int]:
if self._model_is_anthropic:
return get_token_ids_anthropic(text)
else:
return super().get_token_ids(text) | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html |
a76b5c517262-0 | Source code for langchain.llms.openllm
from __future__ import annotations
import copy
import json
import logging
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Literal,
Optional,
TypedDict,
Union,
overload,
)
from langchain.callbacks.manager import (
AsyncCallbackManagerFor... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
a76b5c517262-1 | )
llm("What is the difference between a duck and a goose?")
For all available supported models, you can run 'openllm models'.
If you have a OpenLLM server running, you can also use it remotely:
.. code-block:: python
from langchain.llms import OpenLLM
llm = OpenLLM(se... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
a76b5c517262-2 | @overload
def __init__(
self,
model_name: Optional[str] = ...,
*,
model_id: Optional[str] = ...,
embedded: Literal[True, False] = ...,
**llm_kwargs: Any,
) -> None:
...
@overload
def __init__(
self,
*,
server_url: str = ...,... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
a76b5c517262-3 | super().__init__(
**{
"server_url": server_url,
"server_type": server_type,
"llm_kwargs": llm_kwargs,
}
)
self._runner = None # type: ignore
self._client = client
else:
as... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
a76b5c517262-4 | model_id='google/flan-t5-large',
embedded=False,
)
tools = load_tools(["serpapi", "llm-math"], llm=llm)
agent = initialize_agent(
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION
)
svc = bentoml.Service("langchain-openllm... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
a76b5c517262-5 | )
@property
def _llm_type(self) -> str:
return "openllm_client" if self._client else "openllm"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
try:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
a76b5c517262-6 | **kwargs: Any,
) -> str:
try:
import openllm
except ImportError as e:
raise ImportError(
"Could not import openllm. Make sure to install it with "
"'pip install openllm'."
) from e
copied = copy.deepcopy(self.llm_kwargs)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/openllm.html |
357fa1908d5c-0 | Source code for langchain.llms.bananadev
import logging
from typing import Any, Dict, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.pydantic_v1 import Extra, Field, root_val... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
357fa1908d5c-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
357fa1908d5c-2 | try:
from banana_dev import Client
except ImportError:
raise ImportError(
"Could not import banana-dev python package. "
"Please install it with `pip install banana-dev`."
)
params = self.model_kwargs or {}
params = {**params, *... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bananadev.html |
58dde93ed5bc-0 | Source code for langchain.llms.modal
import logging
from typing import Any, Dict, List, Mapping, Optional
import requests
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.pydantic_v1 import Extra, Fie... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
58dde93ed5bc-1 | logger.warning(
f"""{field_name} was transferred 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
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/modal.html |
a3b831e1cafd-0 | Source code for langchain.llms.base
"""Base interface for large language models to expose."""
from __future__ import annotations
import asyncio
import functools
import inspect
import json
import logging
import warnings
from abc import ABC, abstractmethod
from functools import partial
from pathlib import Path
from typin... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-1 | from langchain.globals import get_verbose
return get_verbose()
@functools.lru_cache
def _log_error_once(msg: str) -> None:
"""Log an error once."""
logger.error(msg)
[docs]def create_base_retry_decorator(
error_types: List[Type[BaseException]],
max_retries: int = 1,
run_manager: Optional[
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-2 | retry_instance = retry_instance | retry_if_exception_type(error)
return retry(
reraise=True,
stop=stop_after_attempt(max_retries),
wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
retry=retry_instance,
before_sleep=_before_sleep,
)
[docs]def get_prom... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-3 | prompt = prompts[missing_prompt_idxs[i]]
if llm_cache is not None:
llm_cache.update(prompt, llm_string, result)
llm_output = new_results.llm_output
return llm_output
[docs]class BaseLLM(BaseLanguageModel[str], ABC):
"""Base LLM abstract interface.
It should take in a prompt and retur... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-4 | """
if verbose is None:
return _get_verbosity()
else:
return verbose
# --- Runnable methods ---
@property
def OutputType(self) -> Type[str]:
"""Get the input type for this runnable."""
return str
def _convert_input(self, input: LanguageModelInput) ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-5 | config = config or {}
llm_result = await self.agenerate_prompt(
[self._convert_input(input)],
stop=stop,
callbacks=config.get("callbacks"),
tags=config.get("tags"),
metadata=config.get("metadata"),
run_name=config.get("run_name"),
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-6 | for i in range(0, len(inputs), max_concurrency)
]
config = [{**c, "max_concurrency": None} for c in config] # type: ignore[misc]
return [
output
for i, batch in enumerate(batches)
for output in self.batch(
batch,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-7 | else:
raise e
else:
batches = [
inputs[i : i + max_concurrency]
for i in range(0, len(inputs), max_concurrency)
]
config = [{**c, "max_concurrency": None} for c in config] # type: ignore[misc]
return [
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-8 | [prompt],
invocation_params=params,
options=options,
name=config.get("run_name"),
)
try:
generation: Optional[GenerationChunk] = None
for chunk in self._stream(
prompt, stop=stop, run_manager=run_... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-9 | dumpd(self),
[prompt],
invocation_params=params,
options=options,
name=config.get("run_name"),
)
try:
generation: Optional[GenerationChunk] = None
async for chunk in self._astream(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-10 | run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> Iterator[GenerationChunk]:
raise NotImplementedError()
def _astream(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-11 | try:
output = (
self._generate(
prompts,
stop=stop,
# TODO: support multiple run managers
run_manager=run_managers[0] if run_managers else None,
**kwargs,
)
if ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-12 | if (
isinstance(callbacks, list)
and callbacks
and (
isinstance(callbacks[0], (list, BaseCallbackManager))
or callbacks[0] is None
)
):
# We've received a list of callbacks args to apply to each input
assert ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-13 | self.verbose,
cast(List[str], tags),
self.tags,
cast(Dict[str, Any], metadata),
self.metadata,
)
] * len(prompts)
run_name_list = [cast(Optional[str], run_name)] * len(prompts)
params = self.d... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-14 | options=options,
name=run_name_list[idx],
)[0]
for idx in missing_prompt_idxs
]
new_results = self._generate_helper(
missing_prompts, stop, run_managers, bool(new_arg_supported), **kwargs
)
llm_output = u... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-15 | flattened_outputs = output.flatten()
await asyncio.gather(
*[
run_manager.on_llm_end(flattened_output)
for run_manager, flattened_output in zip(
run_managers, flattened_outputs
)
]
)
if run_managers:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-16 | )
callbacks = cast(List[Callbacks], callbacks)
tags_list = cast(List[Optional[List[str]]], tags or ([None] * len(prompts)))
metadata_list = cast(
List[Optional[Dict[str, Any]]], metadata or ([{}] * len(prompts))
)
run_name_list = run_name or ca... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-17 | )
if get_llm_cache() is None or disregard_cache:
if self.cache is not None and self.cache:
raise ValueError(
"Asked to cache, but no cache found at `langchain.cache`."
)
run_managers = await asyncio.gather(
*[
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-18 | if run_managers
else None
)
else:
llm_output = {}
run_info = None
generations = [existing_prompts[i] for i in range(len(prompts))]
return LLMResult(generations=generations, llm_output=llm_output, run=run_info)
[docs] def __call__(
se... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-19 | """Check Cache and run the LLM on the given prompt and input."""
result = await self.agenerate(
[prompt],
stop=stop,
callbacks=callbacks,
tags=tags,
metadata=metadata,
**kwargs,
)
return result.generations[0][0].text
[docs] ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-20 | **kwargs: Any,
) -> BaseMessage:
text = get_buffer_string(messages)
if stop is None:
_stop = None
else:
_stop = list(stop)
content = await self._call_async(text, stop=_stop, **kwargs)
return AIMessage(content=content)
@property
def _identifying... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-21 | directory_path.mkdir(parents=True, exist_ok=True)
# Fetch dictionary to save
prompt_dict = self.dict()
if save_path.suffix == ".json":
with open(file_path, "w") as f:
json.dump(prompt_dict, f, indent=4)
elif save_path.suffix == ".yaml":
with open(f... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
a3b831e1cafd-22 | prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
"""Run the LLM on the given prompt and input."""
# TODO: add caching here.
generations = []
new_arg_supported = inspect... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/base.html |
58fc1b637108-0 | Source code for langchain.llms.llamacpp
from __future__ import annotations
import logging
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Union
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.pydantic_v1 ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
58fc1b637108-1 | """Number of parts to split the model into.
If -1, the number of parts is automatically determined."""
seed: int = Field(-1, alias="seed")
"""Seed. If -1, a random seed is used."""
f16_kv: bool = Field(True, alias="f16_kv")
"""Use half-precision for key/value cache."""
logits_all: bool = Field(F... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
58fc1b637108-2 | logprobs: Optional[int] = Field(None)
"""The number of logprobs to return. If None, no logprobs are returned."""
echo: Optional[bool] = False
"""Whether to echo the prompt."""
stop: Optional[List[str]] = []
"""A list of strings to stop generation when encountered."""
repeat_penalty: Optional[flo... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
58fc1b637108-3 | grammar: formal grammar for constraining model outputs. For instance, the grammar
can be used to force the model to generate valid JSON or to speak exclusively in
emojis. At most one of grammar_path and grammar should be passed in.
"""
verbose: bool = True
"""Print verbose output to stderr."""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
58fc1b637108-4 | except Exception as e:
raise ValueError(
f"Could not load Llama model from path: {model_path}. "
f"Received error {e}"
)
if values["grammar"] and values["grammar_path"]:
grammar = values["grammar"]
grammar_path = values["grammar_pat... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
58fc1b637108-5 | "repeat_penalty": self.repeat_penalty,
"top_k": self.top_k,
}
if self.grammar:
params["grammar"] = self.grammar
return params
@property
def _identifying_params(self) -> Dict[str, Any]:
"""Get the identifying parameters."""
return {**{"model_path": ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
58fc1b637108-6 | Args:
prompt: The prompt to use for generation.
stop: A list of strings to stop generation when encountered.
Returns:
The generated text.
Example:
.. code-block:: python
from langchain.llms import LlamaCpp
llm = LlamaCpp(mod... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
58fc1b637108-7 | Returns:
A generator representing the stream of tokens being generated.
Yields:
A dictionary like objects containing a string token and metadata.
See llama-cpp-python docs and below for more.
Example:
.. code-block:: python
from langchain.l... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
50b0d8486905-0 | Source code for langchain.llms.sagemaker_endpoint
"""Sagemaker InvokeEndpoint API."""
import io
import json
from abc import abstractmethod
from typing import Any, Dict, Generic, Iterator, List, Mapping, Optional, TypeVar, Union
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base im... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
50b0d8486905-1 | that previous bytes are not exposed again.
For more details see:
https://aws.amazon.com/blogs/machine-learning/elevating-the-generative-ai-experience-introducing-streaming-support-in-amazon-sagemaker-hosting/
"""
[docs] def __init__(self, stream: Any) -> None:
self.byte_iterator = iter(stream)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
50b0d8486905-2 | def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes:
input_str = json.dumps({prompt: prompt, **model_kwargs})
return input_str.encode('utf-8')
def transform_output(self, output: bytes) -> str:
response_json = js... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
50b0d8486905-3 | If a specific credential profile should be used, you must pass
the name of the profile from the ~/.aws/credentials file that is to be used.
Make sure the credentials / roles used have the required policies to
access the Sagemaker endpoint.
See: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_pol... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
50b0d8486905-4 | client=client
)
"""
client: Any = None
"""Boto3 client for sagemaker runtime"""
endpoint_name: str = ""
"""The name of the endpoint from the deployed Sagemaker model.
Must be unique within an AWS Region."""
region_name: str = ""
"""The aws region where the Sagemaker model is ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
50b0d8486905-5 | return response_json[0]["generated_text"]
"""
model_kwargs: Optional[Dict] = None
"""Keyword arguments to pass to the model."""
endpoint_kwargs: Optional[Dict] = None
"""Optional attributes passed to the invoke_endpoint
function. See `boto3`_. docs for more info.
.. _boto3: <https://boto3.am... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
50b0d8486905-6 | @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... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
50b0d8486905-7 | for line in iterator:
resp = json.loads(line)
resp_output = resp.get("outputs")[0]
if stop is not None:
# Uses same approach as below
resp_output = enforce_stop_tokens(resp_output, stop)
curre... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html |
76cbe0573d07-0 | Source code for langchain.llms.pai_eas_endpoint
import json
import logging
from typing import Any, Dict, Iterator, List, Mapping, Optional
import requests
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langch... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pai_eas_endpoint.html |
76cbe0573d07-1 | """Enable stream chat mode."""
streaming: bool = False
"""Key/value arguments to pass to the model. Reserved for future use"""
model_kwargs: Optional[dict] = None
version: Optional[str] = "2.0"
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api ke... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pai_eas_endpoint.html |
76cbe0573d07-2 | ) -> dict:
params = self._default_params
if self.stop_sequences is not None and stop_sequences is not None:
raise ValueError("`stop` found in both the input and default params.")
elif self.stop_sequences is not None:
params["stop"] = self.stop_sequences
else:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pai_eas_endpoint.html |
76cbe0573d07-3 | """Generate text from the eas service."""
headers = {
"Content-Type": "application/json",
"Authorization": f"{self.eas_service_token}",
}
if self.version == "1.0":
body = {
"input_ids": f"{prompt}",
}
else:
body ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pai_eas_endpoint.html |
76cbe0573d07-4 | )
res = GenerationChunk(text=response.text)
if run_manager:
run_manager.on_llm_new_token(res.text)
# yield text, if any
yield res
else:
pload = {"prompt": prompt, "use_stream_chat": "True", **invocation_params}
response = re... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/pai_eas_endpoint.html |
b589661046c3-0 | Source code for langchain.llms.huggingface_text_gen_inference
import logging
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms.base import LLM
from langchain.pydantic_v1 i... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html |
b589661046c3-1 | callbacks=callbacks,
streaming=True
)
print(llm("What is Deep Learning?"))
"""
max_new_tokens: int = 512
"""Maximum number of generated tokens"""
top_k: Optional[int] = None
"""The number of highest probability vocabulary tokens to keep for
top-k-filtering... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html |
b589661046c3-2 | streaming: bool = False
"""Whether to generate a stream of tokens asynchronously"""
do_sample: bool = False
"""Activate logits sampling"""
watermark: bool = False
"""Watermarking with [A Watermark for Large Language Models]
(https://arxiv.org/abs/2301.10226)"""
server_kwargs: Dict[str, Any] ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html |
b589661046c3-3 | f"Parameters {invalid_model_kwargs} should be specified explicitly. "
f"Instead they were passed in as part of `model_kwargs` parameter."
)
values["model_kwargs"] = extra
return values
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""V... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html |
b589661046c3-4 | "seed": self.seed,
"do_sample": self.do_sample,
"watermark": self.watermark,
**self.model_kwargs,
}
def _invocation_params(
self, runtime_stop: Optional[List[str]], **kwargs: Any
) -> Dict[str, Any]:
params = {**self._default_params, **kwargs}
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html |
b589661046c3-5 | completion += chunk.text
return completion
invocation_params = self._invocation_params(stop, **kwargs)
res = await self.async_client.generate(prompt, **invocation_params)
# remove stop sequences from the end of the generated text
for stop_seq in invocation_params["stop_sequen... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html |
b589661046c3-6 | async def _astream(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> AsyncIterator[GenerationChunk]:
invocation_params = self._invocation_params(stop, **kwargs)
async for res ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html |
beda28bd3e53-0 | Source code for langchain.llms.arcee
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.pydantic_v1 import Extra, root_validator
from langchain.utilities.arcee import ArceeWrapper, DALMFilter
from langchain.uti... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/arcee.html |
beda28bd3e53-1 | """Keyword arguments to pass to the model."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
underscore_attrs_are_private = True
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "arcee"
def __init__(self, **d... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/arcee.html |
beda28bd3e53-2 | )
# validate model kwargs
if values["model_kwargs"]:
kw = values["model_kwargs"]
# validate size
if kw.get("size") is not None:
if not kw.get("size") >= 0:
raise ValueError("`size` must be positive")
# validate filters
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/arcee.html |
780809a1d861-0 | Source code for langchain.llms.utils
"""Common utility functions for LLM APIs."""
import re
from typing import List
[docs]def enforce_stop_tokens(text: str, stop: List[str]) -> str:
"""Cut off the text as soon as any stop words occur."""
return re.split("|".join(stop), text, maxsplit=1)[0] | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/utils.html |
b105c5230567-0 | Source code for langchain.llms.predibase
from typing import Any, Dict, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.pydantic_v1 import Field
[docs]class Predibase(LLM):
"""Use your Predibase models with Langchain.
To ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/predibase.html |
17b28a4d92cb-0 | Source code for langchain.llms.forefrontai
from typing import Any, Dict, List, Mapping, Optional
import requests
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.pydantic_v1 import Extra, root_validat... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
17b28a4d92cb-1 | """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
return values
@property
def _default_params(self) -> Mapping[str, ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
17b28a4d92cb-2 | response = requests.post(
url=self.endpoint_url,
headers={
"Authorization": f"Bearer {self.forefrontai_api_key}",
"Content-Type": "application/json",
},
json={"text": prompt, **self._default_params, **kwargs},
)
response_jso... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/forefrontai.html |
b1b951170b9d-0 | Source code for langchain.llms.aviary
import dataclasses
import os
from typing import Any, Dict, List, Mapping, Optional, Union, cast
import requests
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.p... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html |
b1b951170b9d-1 | except requests.JSONDecodeError as e:
raise RuntimeError(
f"Error decoding JSON from {request_url}. Text response: {response.text}"
) from e
result = sorted(
[k.lstrip("/").replace("--", "/") for k in result.keys() if "--" in k]
)
return result
[docs]def get_completions(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html |
b1b951170b9d-2 | Attributes:
model: The name of the model to use. Defaults to "amazon/LightGPT".
aviary_url: The URL for the Aviary backend. Defaults to None.
aviary_token: The bearer token for the Aviary backend. Defaults to None.
use_prompt_format: If True, the prompt template for the model will be ign... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html |
b1b951170b9d-3 | os.environ["AVIARY_URL"] = aviary_url
os.environ["AVIARY_TOKEN"] = aviary_token
try:
aviary_models = get_models()
except requests.exceptions.RequestException as e:
raise ValueError(e)
model = values.get("model")
if model and model not in aviary_models:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html |
b1b951170b9d-4 | )
text = cast(str, output["generated_text"])
if stop:
text = enforce_stop_tokens(text, stop)
return text | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aviary.html |
eee6a94c5ba7-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 get_type_to_cls_dict
from langchain.llms.base import BaseLLM
[docs]def load_llm_from_config(config: dict) -> BaseLLM:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/loading.html |
a9f9581add47-0 | Source code for langchain.llms.aleph_alpha
from typing import Any, Dict, List, Optional, Sequence
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.pydantic_v1 import Extra, root_validator
from langcha... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
a9f9581add47-1 | """Total probability mass of tokens to consider at each step."""
presence_penalty: float = 0.0
"""Penalizes repeated tokens."""
frequency_penalty: float = 0.0
"""Penalizes repeated tokens according to frequency."""
repetition_penalties_include_prompt: Optional[bool] = False
"""Flag deciding whet... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
a9f9581add47-2 | echo: bool = False
"""Echo the prompt in the completion."""
use_multiplicative_frequency_penalty: bool = False
sequence_penalty: float = 0.0
sequence_penalty_min_length: int = 2
use_multiplicative_sequence_penalty: bool = False
completion_bias_inclusion: Optional[Sequence[str]] = None
comple... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
a9f9581add47-3 | hosting: Optional[str] = None
"""Determines in which datacenters the request may be processed.
You can either set the parameter to "aleph-alpha" or omit it (defaulting to None).
Not setting this value, or setting it to None, gives us maximal
flexibility in processing your request in our
own datacen... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
a9f9581add47-4 | """Validate that api key and python package exists in environment."""
values["aleph_alpha_api_key"] = convert_to_secret_str(
get_from_dict_or_env(values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY")
)
try:
from aleph_alpha_client import Client
values["client"... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
a9f9581add47-5 | "best_of": self.best_of,
"logit_bias": self.logit_bias,
"log_probs": self.log_probs,
"tokens": self.tokens,
"disable_optimizations": self.disable_optimizations,
"minimum_tokens": self.minimum_tokens,
"echo": self.echo,
"use_multiplicati... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
a9f9581add47-6 | prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call out to Aleph Alpha's completion endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of st... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html |
01a04567bd2a-0 | Source code for langchain.llms.vllm
from typing import Any, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import BaseLLM
from langchain.llms.openai import BaseOpenAI
from langchain.pydantic_v1 import Field, root_validator
from langchain.schema.output impo... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html |
01a04567bd2a-1 | """Whether to use beam search instead of sampling."""
stop: Optional[List[str]] = None
"""List of strings that stop the generation when they are generated."""
ignore_eos: bool = False
"""Whether to ignore the EOS token and continue generating tokens after
the EOS token is generated."""
max_new_... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html |
01a04567bd2a-2 | )
return values
@property
def _default_params(self) -> Dict[str, Any]:
"""Get the default parameters for calling vllm."""
return {
"n": self.n,
"best_of": self.best_of,
"max_tokens": self.max_new_tokens,
"top_k": self.top_k,
"to... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html |
01a04567bd2a-3 | [docs]class VLLMOpenAI(BaseOpenAI):
"""vLLM OpenAI-compatible API client"""
@property
def _invocation_params(self) -> Dict[str, Any]:
"""Get the parameters used to invoke the model."""
openai_creds: Dict[str, Any] = {
"api_key": self.openai_api_key,
"api_base": self.o... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html |
efc815370e4b-0 | Source code for langchain.llms.gooseai
import logging
from typing import Any, Dict, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.pydantic_v1 import Extra, Field, SecretStr, root_validator
from langchain.utils import convert_t... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
efc815370e4b-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[... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
efc815370e4b-2 | )
values["gooseai_api_key"] = gooseai_api_key
try:
import openai
openai.api_key = gooseai_api_key.get_secret_value()
openai.api_base = "https://api.goose.ai/v1"
values["client"] = openai.Completion
except ImportError:
raise ImportError(... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
efc815370e4b-3 | """Call the GooseAI API."""
params = self._default_params
if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
params = {**params, **kwargs}
response = self.client.cr... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
3bad0e72466d-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/koboldai.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.