id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
32a612515e5d-5 | """Initialize with necessary components."""
self._check_deprecated_kwargs(kwargs)
try:
# TODO use importlib to check if redis is installed
import redis # noqa: F401
except ImportError as e:
raise ImportError(
"Could not import redis python pac... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-6 | This is a user-friendly interface that:
1. Embeds documents.
2. Creates a new Redis index if it doesn't already exist
3. Adds the documents to the newly created Redis index.
4. Returns the keys of the newly created documents once stored.
This method will generate ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-7 | Optional fields to index within the metadata. Overrides generated
schema. Defaults to None.
vector_schema (Optional[Dict[str, Union[str, int]]], optional): Optional
vector schema to use. Defaults to None.
**kwargs (Any): Additional keyword arguments to pass to the... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-8 | raise ValueError("Number of metadatas must match number of texts")
if not (isinstance(metadatas, list) and isinstance(metadatas[0], dict)):
raise ValueError("Metadatas must be a list of dicts")
generated_schema = _generate_field_schema(metadatas[0])
if index_schema:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-9 | texts: List[str],
embedding: Embeddings,
metadatas: Optional[List[dict]] = None,
index_name: Optional[str] = None,
index_schema: Optional[Union[Dict[str, str], str, os.PathLike]] = None,
vector_schema: Optional[Dict[str, Union[str, int]]] = None,
**kwargs: Any,
) -> R... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-10 | texts (List[str]): List of texts to add to the vectorstore.
embedding (Embeddings): Embedding model class (i.e. OpenAIEmbeddings)
for embedding queries.
metadatas (Optional[List[dict]], optional): Optional list of metadata dicts
to add to the vectorstore. Defaults... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-11 | Example:
.. code-block:: python
from langchain.vectorstores import Redis
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
redisearch = Redis.from_existing_index(
embeddings,
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-12 | raise ValueError(f"Redis failed to connect: {e}")
return cls(
redis_url,
index_name,
embedding,
index_schema=schema,
**kwargs,
)
@property
def schema(self) -> Dict[str, List[Any]]:
"""Return the schema of the index."""
r... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-13 | )
try:
# We need to first remove redis_url from kwargs,
# otherwise passing it to Redis will result in an error.
if "redis_url" in kwargs:
kwargs.pop("redis_url")
client = get_client(redis_url=redis_url, **kwargs)
except ValueError as e:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-14 | raise ValueError(f"Your redis connected error: {e}")
# Check if index exists
try:
client.ft(index_name).dropindex(delete_documents)
logger.info("Drop index")
return True
except: # noqa: E722
# Index not exist
return False
[docs] def... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-15 | raise ValueError("Number of metadatas must match number of texts")
if not (isinstance(metadatas, list) and isinstance(metadatas[0], dict)):
raise ValueError("Metadatas must be a list of dicts")
# Write data to redis
pipeline = self.client.pipeline(transaction=False)
f... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-16 | def similarity_search_limit_score(
self, query: str, k: int = 4, score_threshold: float = 0.2, **kwargs: Any
) -> List[Document]:
"""
Returns the most similar indexed documents to the query text within the
score_threshold range.
Deprecated: Use similarity_search with distance... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-17 | k (int): The number of documents to return. Default is 4.
filter (RedisFilterExpression, optional): Optional metadata filter.
Defaults to None.
return_metadata (bool, optional): Whether to return metadata.
Defaults to True.
Returns:
List[Tuple[... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-18 | + "This is likely due to malformation of "
+ "filter, vector, or query argument"
) from e
raise e
# Prepare document results
docs_with_scores: List[Tuple[Document, float]] = []
for result in results.docs:
metadata = {}
if re... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-19 | k=k,
filter=filter,
return_metadata=return_metadata,
distance_threshold=distance_threshold,
**kwargs,
)
[docs] def similarity_search_by_vector(
self,
embedding: List[float],
k: int = 4,
filter: Optional[RedisFilterExpression] = N... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-20 | )
redis_query, params_dict = self._prepare_query(
embedding,
k=k,
filter=filter,
distance_threshold=distance_threshold,
with_metadata=return_metadata,
with_distance=False,
)
# Perform vector search
# ignore type beca... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-21 | ) -> List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
query (str): Text to look up documents similar to.
k (int): Number of ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-22 | ),
dtype=self._schema.vector_dtype,
)
for prefetch_id in prefetch_ids
]
# Select documents using maximal marginal relevance
selected_indices = maximal_marginal_relevance(
np.array(query_embedding), prefetch_embeddings, lambda_mult=lambda_mult, ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-23 | ) -> Tuple["Query", Dict[str, Any]]:
# Creates Redis query
params_dict: Dict[str, Union[str, bytes, float]] = {
"vector": _array_to_buffer(query_embedding, self._schema.vector_dtype),
}
# prepare return fields including score
return_fields = [self._schema.content_key]... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-24 | return (
Query(query_string)
.return_fields(*return_fields)
.sort_by("distance")
.paging(0, k)
.dialect(2)
)
def _prepare_vector_query(
self,
k: int,
filter: Optional[RedisFilterExpression] = None,
return_fields: Opt... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-25 | # should only be called after init of Redis (so Import handled)
from langchain.vectorstores.redis.schema import RedisModel, read_schema
schema = RedisModel()
# read in schema (yaml file or dict) and
# pass to the Pydantic validators
if index_schema:
schema_values = re... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-26 | IndexType,
)
except ImportError:
raise ImportError(
"Could not import redis python package. "
"Please install it with `pip install redis`."
)
# Set vector dimension
# can't obtain beforehand because we don't
# know which... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-27 | if key in deprecated_kwargs:
raise ValueError(
f"Keyword argument '{key}' is deprecated. "
f"Please use '{deprecated_kwargs[key]}' instead."
)
def _select_relevance_score_fn(self) -> Callable[[float], float]:
if self.relevance_score_fn:... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-28 | "numeric": [],
"tag": [],
}
for key, value in data.items():
# Numeric fields
try:
int(value)
result["numeric"].append({"name": key})
continue
except (ValueError, TypeError):
pass
# None values are not indexed as of now
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-29 | field names and values are the metadata values.
Returns:
Dict[str, Any]: A sanitized dictionary ready for indexing in Redis.
Raises:
ValueError: If any metadata value is not one of the known
types (string, int, float, or list of strings).
"""
def raise_error(key: str, value: ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-30 | search_kwargs: Dict[str, Any] = {
"k": 4,
"score_threshold": 0.9,
# set to None to avoid distance used in score_threshold search
"distance_threshold": None,
}
"""Default search kwargs."""
allowed_search_types = [
"similarity",
"similarity_distance_threshold",
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
32a612515e5d-31 | return docs
async def _aget_relevant_documents(
self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun
) -> List[Document]:
raise NotImplementedError("RedisVectorStoreRetriever does not support async")
[docs] def add_documents(self, documents: List[Document], **kwargs: Any) -> ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/base.html |
c67042f3f52d-0 | Source code for langchain.vectorstores.redis.schema
from __future__ import annotations
import os
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import numpy as np
import yaml
from typing_extensions import TYPE_CHECKING, Literal
from langchain.pydantic_v1 import BaseMo... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
c67042f3f52d-1 | [docs] def as_field(self) -> TagField:
from redis.commands.search.field import TagField # type: ignore
return TagField(
self.name,
separator=self.separator,
case_sensitive=self.case_sensitive,
sortable=self.sortable,
no_index=self.no_index,... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
c67042f3f52d-2 | from redis.commands.search.field import VectorField # type: ignore
return VectorField(
self.name,
self.algorithm,
{
"TYPE": self.datatype,
"DIM": self.dims,
"DISTANCE_METRIC": self.distance_metric,
"INITIAL_CAP"... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
c67042f3f52d-3 | extra: Optional[List[RedisField]] = None
# filled by default_vector_schema
vector: Optional[List[Union[FlatVectorField, HNSWVectorField]]] = None
content_key: str = "content"
content_vector_key: str = "content_vector"
[docs] def add_content_field(self) -> None:
if self.text is None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
c67042f3f52d-4 | if isinstance(attr_value, list) and len(attr_value) > 0:
field_values: List[Dict[str, Any]] = []
# iterate over all fields in each category (tag, text, etc)
for val in attr_value:
value: Dict[str, Any] = {}
# iterate over values wit... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
c67042f3f52d-5 | )
[docs] def get_fields(self) -> List["RedisField"]:
redis_fields: List["RedisField"] = []
if self.is_empty:
return redis_fields
for field_name in self.__fields__.keys():
if field_name not in ["content_key", "content_vector_key", "extra"]:
field_group =... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
c67042f3f52d-6 | if Path(index_schema).resolve().is_file():
with open(index_schema, "rb") as f:
return yaml.safe_load(f)
else:
raise FileNotFoundError(f"index_schema file {index_schema} does not exist")
else:
raise TypeError(
f"index_schema must be a dict, or path ... | https://api.python.langchain.com/en/latest/_modules/langchain/vectorstores/redis/schema.html |
7b436b4d2b38-0 | Source code for langchain.adapters.openai
from __future__ import annotations
import importlib
from typing import (
Any,
AsyncIterator,
Dict,
Iterable,
List,
Mapping,
Sequence,
Union,
overload,
)
from typing_extensions import Literal
from langchain.schema.chat import ChatSession
from ... | https://api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html |
7b436b4d2b38-1 | else:
return ChatMessage(content=_dict["content"], role=role)
[docs]def convert_message_to_dict(message: BaseMessage) -> dict:
message_dict: Dict[str, Any]
if isinstance(message, ChatMessage):
message_dict = {"role": message.role, "content": message.content}
elif isinstance(message, HumanMes... | https://api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html |
7b436b4d2b38-2 | """
return [convert_dict_to_message(m) for m in messages]
def _convert_message_chunk_to_delta(chunk: BaseMessageChunk, i: int) -> Dict[str, Any]:
_dict: Dict[str, Any] = {}
if isinstance(chunk, AIMessageChunk):
if i == 0:
# Only shows up in the first chunk
_dict["role"] = "as... | https://api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html |
7b436b4d2b38-3 | ...
[docs] @staticmethod
def create(
messages: Sequence[Dict[str, Any]],
*,
provider: str = "ChatOpenAI",
stream: bool = False,
**kwargs: Any,
) -> Union[dict, Iterable]:
models = importlib.import_module("langchain.chat_models")
model_cls = getattr(mode... | https://api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html |
7b436b4d2b38-4 | models = importlib.import_module("langchain.chat_models")
model_cls = getattr(models, provider)
model_config = model_cls(**kwargs)
converted_messages = convert_openai_messages(messages)
if not stream:
result = await model_config.ainvoke(converted_messages)
return ... | https://api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html |
6d6bd884e705-0 | Source code for langchain.llms.cohere
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
from tenacity import (
before_sleep_log,
retry,
retry_if_exception_type,
stop_after_attempt,
wait_exponential,
)
from langchain.callbacks.manager import (
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/cohere.html |
6d6bd884e705-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 |
6d6bd884e705-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 |
6d6bd884e705-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 |
6d6bd884e705-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 |
0b8480f91248-0 | Source code for langchain.llms.textgen
import json
import logging
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms.base import LLM
from langchain.pydantic... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
0b8480f91248-1 | (only the most likely token is used). Higher value = more randomness."""
top_p: Optional[float] = 0.1
"""If not set to 1, select tokens with probabilities adding up to less than this
number. Higher value = higher range of possible random results."""
typical_p: Optional[float] = 1
"""If not set to 1,... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
0b8480f91248-2 | """Penalty Alpha"""
length_penalty: Optional[float] = 1
"""Length Penalty"""
early_stopping: bool = Field(False, alias="early_stopping")
"""Early stopping"""
seed: int = Field(-1, alias="seed")
"""Seed (-1 for random)"""
add_bos_token: bool = Field(True, alias="add_bos_token")
"""Add the... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
0b8480f91248-3 | "repetition_penalty": self.repetition_penalty,
"top_k": self.top_k,
"min_length": self.min_length,
"no_repeat_ngram_size": self.no_repeat_ngram_size,
"num_beams": self.num_beams,
"penalty_alpha": self.penalty_alpha,
"length_penalty": self.length_pe... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
0b8480f91248-4 | if self.preset is None:
params = self._default_params
else:
params = {"preset": self.preset}
# then sets it as configured, or default to an empty list:
params["stopping_strings"] = self.stopping_strings or stop or []
return params
def _call(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
0b8480f91248-5 | result = ""
return result
async def _acall(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call the textgen web API and return the output.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
0b8480f91248-6 | **kwargs: Any,
) -> Iterator[GenerationChunk]:
"""Yields results objects as they are generated in real time.
It also calls the callback manager's on_llm_new_token event with
similar parameters to the OpenAI LLM class method of the same name.
Args:
prompt: The prompts to p... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
0b8480f91248-7 | text=result["text"],
generation_info=None,
)
yield chunk
elif result["event"] == "stream_end":
websocket_client.close()
return
if run_manager:
run_manager.on_llm_new_token(token=chunk.text)
as... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
0b8480f91248-8 | )
params = {**self._get_parameters(stop), **kwargs}
url = f"{self.model_url}/api/v1/stream"
request = params.copy()
request["prompt"] = prompt
websocket_client = websocket.WebSocket()
websocket_client.connect(url)
websocket_client.send(json.dumps(request))
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/textgen.html |
8bbaa07031da-0 | Source code for langchain.llms.opaqueprompts
import logging
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.schema.language_model import BaseLanguageMo... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/opaqueprompts.html |
8bbaa07031da-1 | "please install it with `pip install opaqueprompts`."
)
if op.__package__ is None:
raise ValueError(
"Could not properly import `opaqueprompts`, "
"opaqueprompts.__package__ is None."
)
api_key = get_from_dict_or_env(
values... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/opaqueprompts.html |
8bbaa07031da-2 | sanitized_prompt_value_str = sanitize_response.sanitized_texts[0]
# TODO: Add in callbacks once child runs for LLMs are supported by LangSmith.
# call the LLM with the sanitized prompt and get the response
llm_response = self.base_llm.predict(
sanitized_prompt_value_str,
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/opaqueprompts.html |
08bda1e34ffa-0 | Source code for langchain.llms.self_hosted_hugging_face
import importlib.util
import logging
from typing import Any, Callable, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.self_hosted import SelfHostedPipeline
from langchain.llms.utils import enforce_stop_... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
08bda1e34ffa-1 | 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 returns a pipeline for the task.
"""
fro... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/self_hosted_hugging_face.html |
08bda1e34ffa-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 |
08bda1e34ffa-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 |
08bda1e34ffa-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 |
dba2a06d542f-0 | Source code for langchain.llms.gradient_ai
from typing import Any, Dict, List, Mapping, Optional, Union
import aiohttp
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms.base import LLM
from langchain.llms.utils import enforce... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html |
dba2a06d542f-1 | """gradient.ai API Token, which can be generated by going to
https://auth.gradient.ai/select-workspace
and selecting "Access tokens" under the profile drop-down.
"""
model_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model."""
gradient_api_url: str = "https://api.gr... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html |
dba2a06d542f-2 | raise ValueError("`temperature` must be in the range [0.0, 1.0]")
if not 0 <= kw.get("top_p", 0.5) <= 1:
raise ValueError("`top_p` must be in the range [0.0, 1.0]")
if 0 >= kw.get("top_k", 0.5):
raise ValueError("`top_k` must be positive")
if 0 >= kw.g... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html |
dba2a06d542f-3 | _params = {**_model_kwargs, **kwargs}
return dict(
url=f"{self.gradient_api_url}/models/{self.model_id}/complete",
headers={
"authorization": f"Bearer {self.gradient_access_token}",
"x-gradient-workspace-id": f"{self.gradient_workspace_id}",
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html |
dba2a06d542f-4 | if stop is not None:
# Apply stop tokens when making calls to Gradient
text = enforce_stop_tokens(text, stop)
return text
async def _acall(
self,
prompt: str,
stop: Union[List[str], None] = None,
run_manager: Union[AsyncCallbackManagerForLLMRun, None] ... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/gradient_ai.html |
a41153157044-0 | Source code for langchain.llms.huggingface_hub
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, root_validator
from lang... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
a41153157044-1 | extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
huggingfacehub_api_token = get_from_dict_or_env(
values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
a41153157044-2 | run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
51014ac61471-0 | Source code for langchain.llms.anthropic
import re
import warnings
from typing import (
Any,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Mapping,
Optional,
Union,
)
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
51014ac61471-1 | top_p: Optional[float] = None
"""Total probability mass of tokens to consider at each step."""
streaming: bool = False
"""Whether to stream the results."""
default_request_timeout: Optional[float] = None
"""Timeout for requests to Anthropic Completion API. Default is 600 seconds."""
anthropic_ap... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
51014ac61471-2 | check_package_version("anthropic", gte_version="0.3")
values["client"] = anthropic.Anthropic(
base_url=values["anthropic_api_url"],
api_key=values["anthropic_api_key"].get_secret_value(),
timeout=values["default_request_timeout"],
)
val... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
51014ac61471-3 | """Get the identifying parameters."""
return {**{}, **self._default_params}
def _get_anthropic_stop(self, stop: Optional[List[str]] = None) -> List[str]:
if not self.HUMAN_PROMPT or not self.AI_PROMPT:
raise NameError("Please ensure the anthropic package is loaded")
if stop is No... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
51014ac61471-4 | allow_population_by_field_name = True
arbitrary_types_allowed = True
@root_validator()
def raise_warning(cls, values: Dict) -> Dict:
"""Raise warning that this class is deprecated."""
warnings.warn(
"This Anthropic LLM is deprecated. "
"Please use `from langchain.... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
51014ac61471-5 | stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
prompt = "What are the biggest risks facing humanity?"
prompt = f"\n\nHuman: {prompt}\n\nAssistant:"
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
51014ac61471-6 | response = await self.async_client.completions.create(
prompt=self._wrap_prompt(prompt),
stop_sequences=stop,
**params,
)
return response.completion
def _stream(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Opti... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
51014ac61471-7 | **kwargs: Any,
) -> AsyncIterator[GenerationChunk]:
r"""Call Anthropic completion_stream and return the resulting generator.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
A generator rep... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html |
c95b5bf6303b-0 | Source code for langchain.llms.huggingface_pipeline
from __future__ import annotations
import importlib.util
import logging
from typing import Any, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import BaseLLM
from langchain.llms.utils import enforce_st... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
c95b5bf6303b-1 | )
hf = HuggingFacePipeline(pipeline=pipe)
"""
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 argume... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
c95b5bf6303b-2 | elif task in ("text2text-generation", "summarization"):
model = AutoModelForSeq2SeqLM.from_pretrained(model_id, **_model_kwargs)
else:
raise ValueError(
f"Got invalid task {task}, "
f"currently only {VALID_TASKS} are supported"
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
c95b5bf6303b-3 | model_kwargs=_model_kwargs,
**_pipeline_kwargs,
)
if pipeline.task not in VALID_TASKS:
raise ValueError(
f"Got invalid task {pipeline.task}, "
f"currently only {VALID_TASKS} are supported"
)
return cls(
pipeline=pipe... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
c95b5bf6303b-4 | # Text generation return includes the starter text
text = response["generated_text"][len(batch_prompts[j]) :]
elif self.pipeline.task == "text2text-generation":
text = response["generated_text"]
elif self.pipeline.task == "summarization":
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_pipeline.html |
d5e269089938-0 | Source code for langchain.llms.deepinfra
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_validator... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
d5e269089938-1 | @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 of llm."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
d5e269089938-2 | "Error raised by inference API HTTP code: %s, %s"
% (res.status_code, res.text)
)
try:
t = res.json()
text = t["results"][0]["generated_text"]
except requests.exceptions.JSONDecodeError as e:
raise ValueError(
f"Error raised... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
6ed38bcbd480-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] | https://api.python.langchain.com/en/latest/_modules/langchain/llms/utils.html |
3bb407edfd05-0 | Source code for langchain.llms.tongyi
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
from requests.exceptions import HTTPError
from tenacity import (
before_sleep_log,
retry,
retry_if_exception_type,
stop_after_attempt,
wait_exponential,
)
fr... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/tongyi.html |
3bb407edfd05-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 |
3bb407edfd05-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 |
3bb407edfd05-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 |
3bb407edfd05-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 |
6329991291aa-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html |
6329991291aa-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_... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html |
6329991291aa-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html |
6329991291aa-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... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/vllm.html |
429088d7c785-0 | Source code for langchain.llms.mosaicml
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_validator
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
429088d7c785-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 |
429088d7c785-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 |
429088d7c785-3 | # to be robust to multiple response formats.
if isinstance(parsed_response, dict):
output_keys = ["data", "output", "outputs"]
for key in output_keys:
if key in parsed_response:
output_item = parsed_response[key]
... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
b67389fc406f-0 | Source code for langchain.llms.manifest
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, root_validator
[docs]class ManifestWrapper(LLM):
"""HazyResearch's Manifest libr... | https://api.python.langchain.com/en/latest/_modules/langchain/llms/manifest.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.