id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
59
127
f754198f078c-5
ai_prefix: str = "AI" llm: BaseLanguageModel entity_extraction_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT entity_summarization_prompt: BasePromptTemplate = ENTITY_SUMMARIZATION_PROMPT entity_cache: List[str] = [] k: int = 3 chat_history_key: str = "history" entity_store: BaseEntit...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/entity.html
f754198f078c-6
self.entity_cache = entities if self.return_messages: buffer: Any = self.buffer[-self.k * 2 :] else: buffer = buffer_string return { self.chat_history_key: buffer, "entities": entity_summaries, } [docs] def save_context(self, inputs: Dic...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/entity.html
3eae703cd074-0
Source code for langchain.memory.buffer from typing import Any, Dict, List, Optional from pydantic import root_validator from langchain.memory.chat_memory import BaseChatMemory, BaseMemory from langchain.memory.utils import get_prompt_input_key from langchain.schema import get_buffer_string [docs]class ConversationBuff...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/buffer.html
3eae703cd074-1
def validate_chains(cls, values: Dict) -> Dict: """Validate that return messages is not True.""" if values.get("return_messages", False): raise ValueError( "return_messages must be False for ConversationStringBufferMemory" ) return values @property ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/buffer.html
da535f71bcbf-0
Source code for langchain.memory.readonly from typing import Any, Dict, List from langchain.schema import BaseMemory [docs]class ReadOnlySharedMemory(BaseMemory): """A memory wrapper that is read-only and cannot be changed.""" memory: BaseMemory @property def memory_variables(self) -> List[str]: ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/readonly.html
7bade8772e28-0
Source code for langchain.memory.summary from __future__ import annotations from typing import Any, Dict, List, Type from pydantic import BaseModel, root_validator from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.memory.chat_memory import BaseChatMemory from...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/summary.html
7bade8772e28-1
**kwargs: Any, ) -> ConversationSummaryMemory: obj = cls(llm=llm, chat_memory=chat_memory, **kwargs) for i in range(0, len(obj.chat_memory.messages), summarize_step): obj.buffer = obj.predict_new_summary( obj.chat_memory.messages[i : i + summarize_step], obj.buffer ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/summary.html
7bade8772e28-2
[docs] def clear(self) -> None: """Clear memory contents.""" super().clear() self.buffer = "" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/summary.html
9c91c449cbfa-0
Source code for langchain.memory.vectorstore """Class for a VectorStore-backed memory object.""" from typing import Any, Dict, List, Optional, Union from pydantic import Field from langchain.memory.chat_memory import BaseMemory from langchain.memory.utils import get_prompt_input_key from langchain.schema import Documen...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/vectorstore.html
9c91c449cbfa-1
docs = self.retriever.get_relevant_documents(query) result: Union[List[Document], str] if not self.return_docs: result = "\n".join([doc.page_content for doc in docs]) else: result = docs return {self.memory_key: result} def _form_documents( self, input...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/vectorstore.html
41f620be7ba0-0
Source code for langchain.memory.simple from typing import Any, Dict, List from langchain.schema import BaseMemory [docs]class SimpleMemory(BaseMemory): """Simple memory for storing context or other bits of information that shouldn't ever change between prompts. """ memories: Dict[str, Any] = dict() ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/simple.html
44c59d235693-0
Source code for langchain.memory.buffer_window from typing import Any, Dict, List from langchain.memory.chat_memory import BaseChatMemory from langchain.schema import BaseMessage, get_buffer_string [docs]class ConversationBufferWindowMemory(BaseChatMemory): """Buffer for storing conversation memory.""" human_pr...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/buffer_window.html
9b2f4aad14b2-0
Source code for langchain.memory.combined import warnings from typing import Any, Dict, List, Set from pydantic import validator from langchain.memory.chat_memory import BaseChatMemory from langchain.schema import BaseMemory [docs]class CombinedMemory(BaseMemory): """Class for combining multiple memories' data toge...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/combined.html
9b2f4aad14b2-1
for memory in self.memories: memory_variables.extend(memory.memory_variables) return memory_variables [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]: """Load all vars from sub-memories.""" memory_data: Dict[str, Any] = {} # Collect vars fr...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/combined.html
20edaa51834b-0
Source code for langchain.memory.chat_message_histories.cassandra import json import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_KEYSPACE_NAME = "chat_history" DEF...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cassandra.html
20edaa51834b-1
OperationTimedOut, UnresolvableContactPoints, ) from cassandra.cluster import Cluster, PlainTextAuthProvider except ImportError: raise ValueError( "Could not import cassandra-driver python package. " "Please install it with `pip...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cassandra.html
20edaa51834b-2
{self.table_name} (id UUID, session_id varchar, history text, PRIMARY KEY ((session_id), id) );""" ) except (OperationTimedOut, Unavailable) as error: logger.error( f"Unable to create cassandra \ chat message history table: {self.table_na...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cassandra.html
20edaa51834b-3
logger.error("Unable to write chat history messages to cassandra") raise error [docs] def clear(self) -> None: """Clear session memory from Cassandra""" from cassandra import OperationTimedOut, Unavailable try: self.session.execute( f"DELETE FROM {self....
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cassandra.html
6749248172d0-0
Source code for langchain.memory.chat_message_histories.cosmos_db """Azure CosmosDB Memory History.""" from __future__ import annotations import logging from types import TracebackType from typing import TYPE_CHECKING, Any, List, Optional, Type from langchain.schema import ( BaseChatMessageHistory, BaseMessage,...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cosmos_db.html
6749248172d0-1
:param connection_string: The connection string to use to authenticate. :param ttl: The time to live (in seconds) to use for documents in the container. :param cosmos_client_kwargs: Additional kwargs to pass to the CosmosClient. """ self.cosmos_endpoint = cosmos_endpoint self.cos...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cosmos_db.html
6749248172d0-2
PartitionKey, ) except ImportError as exc: raise ImportError( "You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501 ) from exc database = self._client.create_database_if_not_exists(self.cosmos_database) ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cosmos_db.html
6749248172d0-3
) except CosmosHttpResponseError: logger.info("no session found") return if "messages" in item and len(item["messages"]) > 0: self.messages = messages_from_dict(item["messages"]) [docs] def add_message(self, message: BaseMessage) -> None: """Add a self-crea...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/cosmos_db.html
854ce6e834b8-0
Source code for langchain.memory.chat_message_histories.in_memory from typing import List from pydantic import BaseModel from langchain.schema import ( BaseChatMessageHistory, BaseMessage, ) [docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel): messages: List[BaseMessage] = [] [docs] def add...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/in_memory.html
2aa1cbe92cf1-0
Source code for langchain.memory.chat_message_histories.file import json import logging from pathlib import Path from typing import List from langchain.schema import ( BaseChatMessageHistory, BaseMessage, messages_from_dict, messages_to_dict, ) logger = logging.getLogger(__name__) [docs]class FileChatMe...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/file.html
74dcd0b60b09-0
Source code for langchain.memory.chat_message_histories.redis import json import logging from typing import List, Optional from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) [docs]class RedisChatMessageHistory(...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/redis.html
74dcd0b60b09-1
"""Append the message to the record in Redis""" self.redis_client.lpush(self.key, json.dumps(_message_to_dict(message))) if self.ttl: self.redis_client.expire(self.key, self.ttl) [docs] def clear(self) -> None: """Clear session memory from Redis""" self.redis_client.delete...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/redis.html
865da7177912-0
Source code for langchain.memory.chat_message_histories.postgres import json import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_CONNECTION_STRING = "postgresql://p...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/postgres.html
865da7177912-1
messages = messages_from_dict(items) return messages [docs] def add_message(self, message: BaseMessage) -> None: """Append the message to the record in PostgreSQL""" from psycopg import sql query = sql.SQL("INSERT INTO {} (session_id, message) VALUES (%s, %s);").format( sq...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/postgres.html
c80fabc7b629-0
Source code for langchain.memory.chat_message_histories.dynamodb import logging from typing import List, Optional from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, messages_to_dict, ) logger = logging.getLogger(__name__) [docs]class DynamoDBCha...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/dynamodb.html
c80fabc7b629-1
except ClientError as error: if error.response["Error"]["Code"] == "ResourceNotFoundException": logger.warning("No record found with session id: %s", self.session_id) else: logger.error(error) if response and "Item" in response: items = respons...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/dynamodb.html
a9683cbd94d7-0
Source code for langchain.memory.chat_message_histories.momento from __future__ import annotations import json from datetime import timedelta from typing import TYPE_CHECKING, Any, Optional from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) from l...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/momento.html
a9683cbd94d7-1
Note: to instantiate the cache client passed to MomentoChatMessageHistory, you must have a Momento account at https://gomomento.com/. Args: session_id (str): The session ID to use for this chat session. cache_client (CacheClient): The Momento cache client. cache_name ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/momento.html
a9683cbd94d7-2
def from_client_params( cls, session_id: str, cache_name: str, ttl: timedelta, *, configuration: Optional[momento.config.Configuration] = None, auth_token: Optional[str] = None, **kwargs: Any, ) -> MomentoChatMessageHistory: """Construct cache ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/momento.html
a9683cbd94d7-3
return [] elif isinstance(fetch_response, CacheListFetch.Error): raise fetch_response.inner_exception else: raise Exception(f"Unexpected response: {fetch_response}") [docs] def add_message(self, message: BaseMessage) -> None: """Store a message in the cache. Ar...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/momento.html
19a9baed8b87-0
Source code for langchain.memory.chat_message_histories.mongodb import json import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_DBNAME = "chat_history" DEFAULT_COLL...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/mongodb.html
19a9baed8b87-1
except errors.OperationFailure as error: logger.error(error) if cursor: items = [json.loads(document["History"]) for document in cursor] else: items = [] messages = messages_from_dict(items) return messages [docs] def add_message(self, message: Base...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/memory/chat_message_histories/mongodb.html
e7a97b3acca7-0
Source code for langchain.llms.deepinfra """Wrapper around DeepInfra APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils im...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/deepinfra.html
e7a97b3acca7-1
return values @property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" return { **{"model_id": self.model_id}, **{"model_kwargs": self.model_kwargs}, } @property def _llm_type(self) -> str: """Return type ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/deepinfra.html
e7a97b3acca7-2
if res.status_code != 200: raise ValueError( "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.JSONDecod...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/deepinfra.html
06b7f3f65424-0
Source code for langchain.llms.rwkv """Wrapper for the RWKV model. Based on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py """ from typing import Any, Dict, List, Mapping, Optional, Set from pydantic import BaseModel, Extra, roo...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/rwkv.html
06b7f3f65424-1
"""Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim..""" penalty_alpha_presence: float = 0.4 """Positive values penalize new tokens based on whether they appear in the text so far, increasing ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/rwkv.html
06b7f3f65424-2
"""Validate that the python package exists in the environment.""" try: import tokenizers except ImportError: raise ImportError( "Could not import tokenizers python package. " "Please install it with `pip install tokenizers`." ) ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/rwkv.html
06b7f3f65424-3
AVOID_REPEAT_TOKENS = [] AVOID_REPEAT = ",:?!" for i in AVOID_REPEAT: dd = self.pipeline.encode(i) assert len(dd) == 1 AVOID_REPEAT_TOKENS += dd tokens = [int(x) for x in _tokens] self.model_tokens += tokens out: Any = None while len(to...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/rwkv.html
06b7f3f65424-4
occurrence[token] += 1 logits = self.run_rnn([token]) xxx = self.tokenizer.decode(self.model_tokens[out_last:]) if "\ufffd" not in xxx: # avoid utf-8 display issues decoded += xxx out_last = begin + i + 1 if i >= self.max_tokens_per_ge...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/rwkv.html
867e1d128899-0
Source code for langchain.llms.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from abc import abstractmethod from typing import Any, Dict, Generic, List, Mapping, Optional, TypeVar, Union from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun f...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html
867e1d128899-1
"""The MIME type of the response data returned from endpoint""" @abstractmethod def transform_input(self, prompt: INPUT_TYPE, model_kwargs: Dict) -> bytes: """Transforms the input to a format that model can accept as the request Body. Should return bytes or seekable file like object in t...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html
867e1d128899-2
) credentials_profile_name = ( "default" ) se = SagemakerEndpoint( endpoint_name=endpoint_name, region_name=region_name, credentials_profile_name=credentials_profile_name ) """ client: Any #: :meta p...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html
867e1d128899-3
def transform_output(self, output: bytes) -> str: response_json = json.loads(output.read().decode("utf-8")) return response_json[0]["generated_text"] """ model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" endpoint_kwargs: Optional[D...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html
867e1d128899-4
@property def _identifying_params(self) -> Mapping[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"endpoint_name": self.endpoint_name}, **{"model_kwargs": _model_kwargs}, } @property def _llm_type(s...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html
867e1d128899-5
text = self.content_handler.transform_output(response["Body"]) if stop is not None: # This is a bit hacky, but I can't figure out a better way to enforce # stop tokens when making calls to the sagemaker endpoint. text = enforce_stop_tokens(text, stop) return text By H...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/sagemaker_endpoint.html
6912a53ff031-0
Source code for langchain.llms.petals """Wrapper around Petals API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils imp...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/petals.html
6912a53ff031-1
"""Whether or not to use sampling; use greedy decoding otherwise.""" max_length: Optional[int] = None """The maximum length of the sequence to be generated.""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/petals.html
6912a53ff031-2
from petals import DistributedBloomForCausalLM from transformers import BloomTokenizerFast model_name = values["model_name"] values["tokenizer"] = BloomTokenizerFast.from_pretrained(model_name) values["client"] = DistributedBloomForCausalLM.from_pretrained(model_name) ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/petals.html
6912a53ff031-3
"""Call the Petals API.""" 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: ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/petals.html
9d38096d69b8-0
Source code for langchain.llms.writer """Wrapper around Writer APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import e...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/writer.html
9d38096d69b8-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/writer.html
9d38096d69b8-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, ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/writer.html
9d38096d69b8-3
# are not enforced by the model parameters text = enforce_stop_tokens(text, stop) return text By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/writer.html
1fc3dc302d95-0
Source code for langchain.llms.mosaicml """Wrapper around MosaicML APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils impo...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/mosaicml.html
1fc3dc302d95-1
) """ endpoint_url: str = ( "https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict" ) """Endpoint URL to use.""" inject_instruction_format: bool = False """Whether to inject the instruction format into the prompt.""" model_kwargs: Optional[dict] = None """Key word ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/mosaicml.html
1fc3dc302d95-2
instruction=prompt, ) return prompt def _call( self, 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 i...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/mosaicml.html
1fc3dc302d95-3
raise ValueError( 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): ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/mosaicml.html
1fc3dc302d95-4
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/mosaicml.html
70dcace8783d-0
Source code for langchain.llms.replicate """Wrapper around Replicate API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.utils im...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/replicate.html
70dcace8783d-1
"""Build extra kwargs from additional params that were passed in.""" all_required_field_names = {field.alias for field in cls.__fields__.values()} extra = values.get("model_kwargs", {}) for field_name in list(values): if field_name not in all_required_field_names: if ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/replicate.html
70dcace8783d-2
import replicate as replicate_python except ImportError: raise ImportError( "Could not import replicate python package. " "Please install it with `pip install replicate`." ) # get the model and version model_str, version_str = self.model.sp...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/replicate.html
8e5972ee73f8-0
Source code for langchain.llms.huggingface_endpoint """Wrapper around HuggingFace APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain....
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_endpoint.html
8e5972ee73f8-1
huggingfacehub_api_token: Optional[str] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" hugging...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_endpoint.html
8e5972ee73f8-2
return "huggingface_endpoint" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> str: """Call out to HuggingFace Hub's inference endpoint. Args: prompt: Th...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_endpoint.html
8e5972ee73f8-3
elif self.task == "text2text-generation": text = generated_text[0]["generated_text"] elif self.task == "summarization": text = generated_text[0]["summary_text"] else: raise ValueError( f"Got invalid task {self.task}, " f"currently only ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_endpoint.html
1fbaaa65f49e-0
Source code for langchain.llms.self_hosted_hugging_face """Wrapper around HuggingFace Pipeline API to run on self-hosted remote hardware.""" import importlib.util import logging from typing import Any, Callable, List, Mapping, Optional from pydantic import Extra from langchain.callbacks.manager import CallbackManagerFo...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted_hugging_face.html
1fbaaa65f49e-1
text = enforce_stop_tokens(text, stop) return text def _load_transformer( model_id: str = DEFAULT_MODEL_ID, task: str = DEFAULT_TASK, device: int = 0, model_kwargs: Optional[dict] = None, ) -> Any: """Inference function to send to the remote hardware. Accepts a huggingface model_id and retur...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted_hugging_face.html
1fbaaa65f49e-2
) if device < 0 and cuda_device_count > 0: logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer ass...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted_hugging_face.html
1fbaaa65f49e-3
hf = SelfHostedHuggingFaceLLM( model_id="google/flan-t5-large", task="text2text-generation", hardware=gpu ) Example passing fn that generates a pipeline (bc the pipeline is not serializable): .. code-block:: python from langchain.llms import SelfHosted...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted_hugging_face.html
1fbaaa65f49e-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):...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted_hugging_face.html
1fbaaa65f49e-5
) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted_hugging_face.html
15c77f83a7b2-0
Source code for langchain.llms.stochasticai """Wrapper around StochasticAI APIs.""" import logging import time from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/stochasticai.html
15c77f83a7b2-1
raise ValueError(f"Found {field_name} supplied twice.") logger.warning( f"""{field_name} was transfered to model_kwargs. Please confirm that {field_name} is what you intended.""" ) extra[field_name] = values.pop(field_name) ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/stochasticai.html
15c77f83a7b2-2
response = StochasticAI("Tell me a joke.") """ params = self.model_kwargs or {} params = {**params, **kwargs} response_post = requests.post( url=self.api_url, json={"prompt": prompt, "params": params}, headers={ "apiKey": f"{self.stocha...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/stochasticai.html
2be2f3485db7-0
Source code for langchain.llms.beam """Wrapper around Beam API.""" 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 Callba...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html
2be2f3485db7-1
max_length=50) 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 endpoi...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html
2be2f3485db7-2
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """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( ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html
2be2f3485db7-3
python_packages={python_packages}, ) app.Trigger.RestAPI( inputs={{"prompt": beam.Types.String(), "max_length": beam.Types.String()}}, outputs={{"text": beam.Types.String()}}, handler="run.py:beam_langchain", ) """ ) script_name = "app....
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html
2be2f3485db7-4
file.write(script.format(model_name=self.model_name)) def _deploy(self) -> str: """Call to Beam.""" try: import beam # type: ignore if beam.__path__ == "": raise ImportError except ImportError: raise ImportError( "Could not...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html
2be2f3485db7-5
self, prompt: str, stop: Optional[list] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **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_l...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/beam.html
aa5d199abcf6-0
Source code for langchain.llms.huggingface_hub """Wrapper around HuggingFace APIs.""" from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain.llms.utils import enf...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_hub.html
aa5d199abcf6-1
"""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.""" huggingfacehub_api_token = get_from_dict_or_env( values, "huggingfac...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_hub.html
aa5d199abcf6-2
prompt: str, stop: Optional[List[str]] = None, 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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_hub.html
aa5d199abcf6-3
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/huggingface_hub.html
53df2fb38aff-0
Source code for langchain.llms.baseten """Wrapper around Baseten deployed model API.""" 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__...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/baseten.html
53df2fb38aff-1
"""Return type of model.""" return "baseten" 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: ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/baseten.html
8682edeeb4ca-0
Source code for langchain.llms.pipelineai """Wrapper around Pipeline Cloud API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import BaseModel, Extra, Field, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from l...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/pipelineai.html
8682edeeb4ca-1
extra = values.get("pipeline_kwargs", {}) for field_name in list(values): if field_name not in all_required_field_names: if field_name in extra: raise ValueError(f"Found {field_name} supplied twice.") logger.warning( f"""{field_...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/pipelineai.html
8682edeeb4ca-2
"Please install it with `pip install pipeline-ai`." ) client = PipelineCloud(token=self.pipeline_api_key) params = self.pipeline_kwargs or {} params = {**params, **kwargs} run = client.run_pipeline(self.pipeline_key, [prompt, params]) try: text = run.resul...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/pipelineai.html
bec8d20e826f-0
Source code for langchain.llms.openai """Wrapper around OpenAI APIs.""" from __future__ import annotations import logging import sys import warnings from typing import ( AbstractSet, Any, Callable, Collection, Dict, Generator, List, Literal, Mapping, Optional, Set, Tuple,...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html
bec8d20e826f-1
"finish_reason" ] response["choices"][0]["logprobs"] = stream_response["choices"][0]["logprobs"] def _streaming_response_template() -> Dict[str, Any]: return { "choices": [ { "text": "", "finish_reason": None, "logprobs": None, ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html
bec8d20e826f-2
return llm.client.create(**kwargs) return _completion_with_retry(**kwargs) async def acompletion_with_retry( llm: Union[BaseOpenAI, OpenAIChat], **kwargs: Any ) -> Any: """Use tenacity to retry the async completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator async de...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html
bec8d20e826f-3
"""How many completions to generate for each prompt.""" best_of: int = 1 """Generates best_of completions server-side and returns the "best".""" model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Holds any model parameters valid for `create` call not explicitly specified.""" openai_api_ke...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html
bec8d20e826f-4
warnings.warn( "You are trying to use a chat model. This way of initializing it is " "no longer supported. Instead, please use: " "`from langchain.chat_models import ChatOpenAI`" ) return OpenAIChat(**data) return super().__new__(cls) c...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html
bec8d20e826f-5
values["openai_api_key"] = get_from_dict_or_env( values, "openai_api_key", "OPENAI_API_KEY" ) values["openai_api_base"] = get_from_dict_or_env( values, "openai_api_base", "OPENAI_API_BASE", default="", ) values["openai_proxy"] =...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html