id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 54 121 |
|---|---|---|
c9e3e15a7952-2 | model_load_fn: Callable = load_embedding_model
"""Function to load the model remotely on the server."""
load_fn_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model load function."""
inference_fn: Callable = _embed_documents
"""Inference function to extract the embeddings."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
c9e3e15a7952-3 | model_name=model_name, hardware=gpu)
"""
model_id: str = DEFAULT_INSTRUCT_MODEL
"""Model name to use."""
embed_instruction: str = DEFAULT_EMBED_INSTRUCTION
"""Instruction to use for embedding documents."""
query_instruction: str = DEFAULT_QUERY_INSTRUCTION
"""Instruction to use for embedding... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
c9e3e15a7952-4 | Returns:
Embeddings for the text.
"""
instruction_pair = [self.query_instruction, text]
embedding = self.client(self.pipeline_ref, [instruction_pair])[0]
return embedding.tolist() | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
97ac13dd59d1-0 | Source code for langchain.embeddings.embaas
"""Wrapper around embaas embeddings API."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import BaseModel, Extra, root_validator
from typing_extensions import NotRequired, TypedDict
from langchain.embeddings.base import Embeddings
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html |
97ac13dd59d1-1 | api_url: str = EMBAAS_API_URL
"""The URL for the embaas embeddings API."""
embaas_api_key: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html |
97ac13dd59d1-2 | return embeddings
def _generate_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Generate embeddings using the Embaas API."""
payload = self._generate_payload(texts)
try:
return self._handle_request(payload)
except requests.exceptions.RequestException as e:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html |
6d0aab9f0020-0 | Source code for langchain.embeddings.sagemaker_endpoint
"""Wrapper around Sagemaker InvokeEndpoint API."""
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.llms.sagemaker_endpoint import ContentHandlerBase
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
6d0aab9f0020-1 | credentials_profile_name=credentials_profile_name
)
"""
client: Any #: :meta private:
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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
6d0aab9f0020-2 | """ # noqa: E501
model_kwargs: Optional[Dict] = None
"""Key word 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.amazonaws.com/v1/documentation/ap... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
6d0aab9f0020-3 | # replace newlines, which can negatively affect performance.
texts = list(map(lambda x: x.replace("\n", " "), texts))
_model_kwargs = self.model_kwargs or {}
_endpoint_kwargs = self.endpoint_kwargs or {}
body = self.content_handler.transform_input(texts, _model_kwargs)
content_ty... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
6d0aab9f0020-4 | """Compute query embeddings using a SageMaker inference endpoint.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
return self._embedding_func([text])[0] | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
b9ce2f7fc1c3-0 | Source code for langchain.embeddings.llamacpp
"""Wrapper around llama.cpp embedding models."""
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.embeddings.base import Embeddings
[docs]class LlamaCppEmbeddings(BaseModel, Embeddings):
"""Wrapper ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
b9ce2f7fc1c3-1 | use_mlock: bool = Field(False, alias="use_mlock")
"""Force system to keep model in RAM."""
n_threads: Optional[int] = Field(None, alias="n_threads")
"""Number of threads to use. If None, the number
of threads is automatically determined."""
n_batch: Optional[int] = Field(8, alias="n_batch")
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
b9ce2f7fc1c3-2 | raise ModuleNotFoundError(
"Could not import llama-cpp-python library. "
"Please install the llama-cpp-python library to "
"use this embedding model: pip install llama-cpp-python"
)
except Exception as e:
raise ValueError(
f... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
315ba205e080-0 | Source code for langchain.embeddings.dashscope
"""Wrapper around DashScope embedding models."""
from __future__ import annotations
import logging
from typing import (
Any,
Callable,
Dict,
List,
Optional,
)
from pydantic import BaseModel, Extra, root_validator
from requests.exceptions import HTTPErro... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html |
315ba205e080-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/embeddings/dashscope.html |
315ba205e080-2 | class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
import dashscope
"""Validate that api key and python package exists in environment."""
values["dashscope_api_key"] = get... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html |
315ba205e080-3 | Embedding for the text.
"""
embedding = embed_with_retry(
self, input=text, text_type="query", model=self.model
)[0]["embedding"]
return embedding | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html |
ba98ed991532-0 | Source code for langchain.memory.motorhead_memory
from typing import Any, Dict, List, Optional
import requests
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import get_buffer_string
MANAGED_URL = "https://api.getmetal.io/v1/motorhead"
# LOCAL_URL = "http://localhost:8080"
[docs]class Mot... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html |
ba98ed991532-1 | messages = res_data.get("messages", [])
context = res_data.get("context", "NONE")
for message in reversed(messages):
if message["role"] == "AI":
self.chat_memory.add_ai_message(message["content"])
else:
self.chat_memory.add_user_message(message["co... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html |
ab43006de074-0 | Source code for langchain.memory.entity
import logging
from abc import ABC, abstractmethod
from itertools import islice
from typing import Any, Dict, Iterable, List, Optional
from pydantic import BaseModel, Field
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langch... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ab43006de074-1 | return self.store.get(key, default)
[docs] def set(self, key: str, value: Optional[str]) -> None:
self.store[key] = value
[docs] def delete(self, key: str) -> None:
del self.store[key]
[docs] def exists(self, key: str) -> bool:
return key in self.store
[docs] def clear(self) -> None:... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ab43006de074-2 | self.redis_client = redis.Redis.from_url(url=url, decode_responses=True)
except redis.exceptions.ConnectionError as error:
logger.error(error)
self.session_id = session_id
self.key_prefix = key_prefix
self.ttl = ttl
self.recall_ttl = recall_ttl or ttl
@property
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ab43006de074-3 | iterator = iter(iterable)
while batch := list(islice(iterator, batch_size)):
yield batch
for keybatch in batched(
self.redis_client.scan_iter(f"{self.full_key_prefix}:*"), 500
):
self.redis_client.delete(*keybatch)
[docs]class SQLiteEntityStore(BaseEnt... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ab43006de074-4 | query = f"""
SELECT value
FROM {self.full_table_name}
WHERE key = ?
"""
cursor = self.conn.execute(query, (key,))
result = cursor.fetchone()
if result is not None:
value = result[0]
return value
return default
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ab43006de074-5 | With a swapable entity store, persisting entities across conversations.
Defaults to an in-memory entity store, and can be swapped out for a Redis,
SQLite, or other entity store.
"""
human_prefix: str = "Human"
ai_prefix: str = "AI"
llm: BaseLanguageModel
entity_extraction_prompt: BasePromptT... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ab43006de074-6 | # Create an LLMChain for predicting entity names from the recent chat history:
chain = LLMChain(llm=self.llm, prompt=self.entity_extraction_prompt)
if self.input_key is None:
prompt_input_key = get_prompt_input_key(inputs, self.memory_variables)
else:
prompt_input_key = s... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ab43006de074-7 | if self.return_messages:
# Get last `k` pair of chat messages:
buffer: Any = self.buffer[-self.k * 2 :]
else:
# Reuse the string we made earlier:
buffer = buffer_string
return {
self.chat_history_key: buffer,
"entities": entity_summ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ab43006de074-8 | summary=existing_summary,
entity=entity,
history=buffer_string,
input=input_data,
)
# Save the updated summary to the entity store
self.entity_store.set(entity, output.strip())
[docs] def clear(self) -> None:
"""Clear memory ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
3486c9174b8a-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
3486c9174b8a-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
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
4b7da26a10e5-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
4b7da26a10e5-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
8520a5ee727d-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html |
442d9c81ca8d-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
442d9c81ca8d-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
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
442d9c81ca8d-2 | [docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.buffer = "" | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
c813748e0185-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
c813748e0185-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
9a881b3f6a7a-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]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/readonly.html |
71d05a5188a7-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()
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/simple.html |
380a3fecde3b-0 | Source code for langchain.memory.token_buffer
from typing import Any, Dict, List
from langchain.base_language import BaseLanguageModel
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationTokenBufferMemory(BaseChatMemory):
"""Buf... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
380a3fecde3b-1 | if curr_buffer_length > self.max_token_limit:
pruned_memory = []
while curr_buffer_length > self.max_token_limit:
pruned_memory.append(buffer.pop(0))
curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer) | https://api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
90e9147f6de0-0 | Source code for langchain.memory.summary_buffer
from typing import Any, Dict, List
from pydantic import root_validator
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.summary import SummarizerMixin
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationSummaryB... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
90e9147f6de0-1 | if expected_keys != set(prompt_variables):
raise ValueError(
"Got unexpected prompt input variables. The prompt expects "
f"{prompt_variables}, but it should have {expected_keys}."
)
return values
[docs] def save_context(self, inputs: Dict[str, Any], ou... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
d3067a1e5395-0 | Source code for langchain.memory.kg
from typing import Any, Dict, List, Type, Union
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.graphs import NetworkxEntityGraph
from langchain.graphs.networkx_graph import KnowledgeTriple, get... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
d3067a1e5395-1 | entities = self._get_current_entities(inputs)
summary_strings = []
for entity in entities:
knowledge = self.kg.get_entity_knowledge(entity)
if knowledge:
summary = f"On {entity}: {'. '.join(knowledge)}."
summary_strings.append(summary)
cont... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
d3067a1e5395-2 | human_prefix=self.human_prefix,
ai_prefix=self.ai_prefix,
)
output = chain.predict(
history=buffer_string,
input=input_string,
)
return get_entities(output)
def _get_current_entities(self, inputs: Dict[str, Any]) -> List[str]:
"""Get the cu... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
d3067a1e5395-3 | [docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.kg.clear() | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
f92dd48dc452-0 | Source code for langchain.memory.chat_message_histories.zep
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Dict, List, Optional
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
)
if TYPE_CHECKING:
from zep_python import... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
f92dd48dc452-1 | ) -> None:
try:
from zep_python import ZepClient
except ImportError:
raise ValueError(
"Could not import zep-python package. "
"Please install it with `pip install zep-python`."
)
self.zep_client = ZepClient(base_url=url)
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
f92dd48dc452-2 | return None
return zep_memory.summary.content
def _get_memory(self) -> Optional[Memory]:
"""Retrieve memory from Zep"""
from zep_python import NotFoundError
try:
zep_memory: Memory = self.zep_client.get_memory(self.session_id)
except NotFoundError:
log... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
f92dd48dc452-3 | """
try:
self.zep_client.delete_memory(self.session_id)
except NotFoundError:
logger.warning(
f"Session {self.session_id} not found in Zep. Skipping delete."
) | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
90e5aed4021f-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,... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
90e5aed4021f-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
90e5aed4021f-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)
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
90e5aed4021f-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
e39f0d4c97c6-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html |
26aed2d5d85e-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
26aed2d5d85e-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
26aed2d5d85e-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
26aed2d5d85e-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.... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
f03e723a0847-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
f03e723a0847-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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
f03e723a0847-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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
f03e723a0847-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
68ddf579b500-0 | Source code for langchain.memory.chat_message_histories.sql
import json
import logging
from typing import List
from sqlalchemy import Column, Integer, Text, create_engine
try:
from sqlalchemy.orm import declarative_base
except ImportError:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
68ddf579b500-1 | DynamicBase = declarative_base()
self.Message = create_message_model(self.table_name, DynamicBase)
# Create all does the check for us in case the table exists.
DynamicBase.metadata.create_all(self.engine)
@property
def messages(self) -> List[BaseMessage]: # type: ignore
"""Retri... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
f2dcfa9df0e4-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html |
da4a8150ec28-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
da4a8150ec28-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
ad40ad93b269-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
ad40ad93b269-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
7662a8aa06af-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(... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
7662a8aa06af-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
aac3c1be102a-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
aac3c1be102a-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... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
a44ea63966c1-0 | Source code for langchain.agents.loading
"""Functionality for loading agents."""
import json
import logging
from pathlib import Path
from typing import Any, List, Optional, Union
import yaml
from langchain.agents.agent import BaseMultiActionAgent, BaseSingleActionAgent
from langchain.agents.tools import Tool
from langc... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
a44ea63966c1-1 | if load_from_tools:
if llm is None:
raise ValueError(
"If `load_from_llm_and_tools` is set to True, "
"then LLM must be provided"
)
if tools is None:
raise ValueError(
"If `load_from_llm_and_tools` is set to True, "
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
a44ea63966c1-2 | if hub_result := try_load_from_hub(
path, _load_agent_from_file, "agents", {"json", "yaml"}
):
return hub_result
else:
return _load_agent_from_file(path, **kwargs)
def _load_agent_from_file(
file: Union[str, Path], **kwargs: Any
) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
db617d351d5d-0 | Source code for langchain.agents.initialize
"""Load agent."""
from typing import Any, Optional, Sequence
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_types import AgentType
from langchain.agents.loading import AGENT_TO_CLASS, load_agent
from langchain.base_language import BaseLanguageMod... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
db617d351d5d-1 | agent = AgentType.ZERO_SHOT_REACT_DESCRIPTION
if agent is not None and agent_path is not None:
raise ValueError(
"Both `agent` and `agent_path` are specified, "
"but at most only one should be."
)
if agent is not None:
if agent not in AGENT_TO_CLASS:
r... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
9315a95a386b-0 | Source code for langchain.agents.load_tools
# flake8: noqa
"""Load tools."""
import warnings
from typing import Any, Dict, List, Optional, Callable, Tuple
from mypy_extensions import Arg, KwArg
from langchain.agents.tools import Tool
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.base im... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
9315a95a386b-1 | from langchain.tools.shell.tool import ShellTool
from langchain.tools.sleep.tool import SleepTool
from langchain.tools.wikipedia.tool import WikipediaQueryRun
from langchain.tools.wolfram_alpha.tool import WolframAlphaQueryRun
from langchain.tools.openweathermap.tool import OpenWeatherMapQueryRun
from langchain.utiliti... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
9315a95a386b-2 | def _get_tools_requests_delete() -> BaseTool:
return RequestsDeleteTool(requests_wrapper=TextRequestsWrapper())
def _get_terminal() -> BaseTool:
return ShellTool()
def _get_sleep() -> BaseTool:
return SleepTool()
_BASE_TOOLS: Dict[str, Callable[[], BaseTool]] = {
"python_repl": _get_python_repl,
"re... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
9315a95a386b-3 | return Tool(
name="Calculator",
description="Useful for when you need to answer questions about math.",
func=LLMMathChain.from_llm(llm=llm).run,
coroutine=LLMMathChain.from_llm(llm=llm).arun,
)
def _get_open_meteo_api(llm: BaseLanguageModel) -> BaseTool:
chain = APIChain.from_llm... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
9315a95a386b-4 | func=chain.run,
)
def _get_tmdb_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:
tmdb_bearer_token = kwargs["tmdb_bearer_token"]
chain = APIChain.from_llm_and_api_docs(
llm,
tmdb_docs.TMDB_DOCS,
headers={"Authorization": f"Bearer {tmdb_bearer_token}"},
)
return Tool(
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
9315a95a386b-5 | def _get_google_search(**kwargs: Any) -> BaseTool:
return GoogleSearchRun(api_wrapper=GoogleSearchAPIWrapper(**kwargs))
def _get_wikipedia(**kwargs: Any) -> BaseTool:
return WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(**kwargs))
def _get_arxiv(**kwargs: Any) -> BaseTool:
return ArxivQueryRun(api_wrapp... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
9315a95a386b-6 | )
def _get_searx_search(**kwargs: Any) -> BaseTool:
return SearxSearchRun(wrapper=SearxSearchWrapper(**kwargs))
def _get_searx_search_results_json(**kwargs: Any) -> BaseTool:
wrapper_kwargs = {k: v for k, v in kwargs.items() if k != "num_results"}
return SearxSearchResults(wrapper=SearxSearchWrapper(**wrapp... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
9315a95a386b-7 | ] = {
"news-api": (_get_news_api, ["news_api_key"]),
"tmdb-api": (_get_tmdb_api, ["tmdb_bearer_token"]),
"podcast-api": (_get_podcast_api, ["listen_api_key"]),
}
_EXTRA_OPTIONAL_TOOLS: Dict[str, Tuple[Callable[[KwArg(Any)], BaseTool], List[str]]] = {
"wolfram-alpha": (_get_wolfram_alpha, ["wolfram_alpha... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
9315a95a386b-8 | "searx-search": (_get_searx_search, ["searx_host", "engines", "aiosession"]),
"wikipedia": (_get_wikipedia, ["top_k_results", "lang"]),
"arxiv": (
_get_arxiv,
["top_k_results", "load_max_docs", "load_all_available_meta"],
),
"pupmed": (
_get_pupmed,
["top_k_results", "loa... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
9315a95a386b-9 | **kwargs: Any,
) -> BaseTool:
"""Loads a tool from the HuggingFace Hub.
Args:
task_or_repo_id: Task or model repo id.
model_repo_id: Optional model repo id.
token: Optional token.
remote: Optional remote. Defaults to False.
**kwargs:
Returns:
A tool.
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
9315a95a386b-10 | Args:
tool_names: name of tools to load.
llm: Optional language model, may be needed to initialize certain tools.
callbacks: Optional callback manager or list of callback handlers.
If not provided, default global callback manager will be used.
Returns:
List of tools.
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
9315a95a386b-11 | f"provided: {missing_keys}"
)
sub_kwargs = {k: kwargs[k] for k in extra_keys}
tool = _get_llm_tool_func(llm=llm, **sub_kwargs)
tools.append(tool)
elif name in _EXTRA_OPTIONAL_TOOLS:
_get_tool_func, extra_keys = _EXTRA_OPTIONAL_TOOLS[name]
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
1e075621b75c-0 | Source code for langchain.agents.agent_types
from enum import Enum
[docs]class AgentType(str, Enum):
"""Enumerator with the Agent types."""
ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description"
REACT_DOCSTORE = "react-docstore"
SELF_ASK_WITH_SEARCH = "self-ask-with-search"
CONVERSATIONAL_REACT... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_types.html |
c33eb77314f9-0 | Source code for langchain.agents.agent
"""Chain that takes in an input and produces an action and action input."""
from __future__ import annotations
import asyncio
import json
import logging
import time
from abc import abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
c33eb77314f9-1 | return None
[docs] @abstractmethod
def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Ste... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
c33eb77314f9-2 | # `force` just returns a constant string
return AgentFinish(
{"output": "Agent stopped due to iteration limit or time limit."}, ""
)
else:
raise ValueError(
f"Got unsupported early_stopping_method `{early_stopping_method}`"
)
[docs]... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
c33eb77314f9-3 | directory_path.mkdir(parents=True, exist_ok=True)
# Fetch dictionary to save
agent_dict = self.dict()
if save_path.suffix == ".json":
with open(file_path, "w") as f:
json.dump(agent_dict, f, indent=4)
elif save_path.suffix == ".yaml":
with open(fil... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
c33eb77314f9-4 | **kwargs: Any,
) -> Union[List[AgentAction], AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
callbacks: Callbacks to run.
**kwargs: User inputs.
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.