id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
85dbd60b204a-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 langchain.memory.prompt import SUMMARY_PROMPT from langchain.prompts.base import BasePromptTemplate from langchain.schema import ( BaseChatMessageHistory, BaseMessage, SystemMessage, get_buffer_string, ) class SummarizerMixin(BaseModel): human_prefix: str = "Human" ai_prefix: str = "AI" llm: BaseLanguageModel prompt: BasePromptTemplate = SUMMARY_PROMPT summary_message_cls: Type[BaseMessage] = SystemMessage def predict_new_summary( self, messages: List[BaseMessage], existing_summary: str ) -> str: new_lines = get_buffer_string( messages, human_prefix=self.human_prefix, ai_prefix=self.ai_prefix, ) chain = LLMChain(llm=self.llm, prompt=self.prompt) return chain.predict(summary=existing_summary, new_lines=new_lines) [docs]class ConversationSummaryMemory(BaseChatMemory, SummarizerMixin): """Conversation summarizer to memory.""" buffer: str = "" memory_key: str = "history" #: :meta private: [docs] @classmethod def from_messages( cls, llm: BaseLanguageModel, chat_memory: BaseChatMessageHistory, *, summarize_step: int = 2, **kwargs: Any, ) -> ConversationSummaryMemory:
https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html
85dbd60b204a-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 ) return obj @property def memory_variables(self) -> List[str]: """Will always return list of memory variables. :meta private: """ return [self.memory_key] [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Return history buffer.""" if self.return_messages: buffer: Any = [self.summary_message_cls(content=self.buffer)] else: buffer = self.buffer return {self.memory_key: buffer} @root_validator() def validate_prompt_input_variables(cls, values: Dict) -> Dict: """Validate that prompt input variables are consistent.""" prompt_variables = values["prompt"].input_variables expected_keys = {"summary", "new_lines"} 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], outputs: Dict[str, str]) -> None: """Save context from this conversation to buffer.""" super().save_context(inputs, outputs) self.buffer = self.predict_new_summary( self.chat_memory.messages[-2:], self.buffer ) [docs] def clear(self) -> None: """Clear memory contents."""
https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html
85dbd60b204a-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
33d774276627-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]: """Return memory variables.""" return self.memory.memory_variables [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]: """Load memory variables from memory.""" return self.memory.load_memory_variables(inputs) [docs] def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: """Nothing should be saved or changed""" pass [docs] def clear(self) -> None: """Nothing to clear, got a memory like a vault.""" pass
https://api.python.langchain.com/en/latest/_modules/langchain/memory/readonly.html
813decf5eed1-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 MotorheadMemory(BaseChatMemory): url: str = MANAGED_URL timeout = 3000 memory_key = "history" session_id: str context: Optional[str] = None # Managed Params api_key: Optional[str] = None client_id: Optional[str] = None def __get_headers(self) -> Dict[str, str]: is_managed = self.url == MANAGED_URL headers = { "Content-Type": "application/json", } if is_managed and not (self.api_key and self.client_id): raise ValueError( """ You must provide an API key or a client ID to use the managed version of Motorhead. Visit https://getmetal.io for more information. """ ) if is_managed and self.api_key and self.client_id: headers["x-metal-api-key"] = self.api_key headers["x-metal-client-id"] = self.client_id return headers [docs] async def init(self) -> None: res = requests.get( f"{self.url}/sessions/{self.session_id}/memory", timeout=self.timeout, headers=self.__get_headers(), ) res_data = res.json() res_data = res_data.get("data", res_data) # Handle Managed Version messages = res_data.get("messages", [])
https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html
813decf5eed1-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["content"]) if context and context != "NONE": self.context = context [docs] def load_memory_variables(self, values: Dict[str, Any]) -> Dict[str, Any]: if self.return_messages: return {self.memory_key: self.chat_memory.messages} else: return {self.memory_key: get_buffer_string(self.chat_memory.messages)} @property def memory_variables(self) -> List[str]: return [self.memory_key] [docs] def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: input_str, output_str = self._get_input_output(inputs, outputs) requests.post( f"{self.url}/sessions/{self.session_id}/memory", timeout=self.timeout, json={ "messages": [ {"role": "Human", "content": f"{input_str}"}, {"role": "AI", "content": f"{output_str}"}, ] }, headers=self.__get_headers(), ) super().save_context(inputs, outputs) [docs] def delete_session(self) -> None: """Delete a session""" requests.delete(f"{self.url}/sessions/{self.session_id}/memory")
https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html
1413a1743a14-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 Document from langchain.vectorstores.base import VectorStoreRetriever [docs]class VectorStoreRetrieverMemory(BaseMemory): """Class for a VectorStore-backed memory object.""" retriever: VectorStoreRetriever = Field(exclude=True) """VectorStoreRetriever object to connect to.""" memory_key: str = "history" #: :meta private: """Key name to locate the memories in the result of load_memory_variables.""" input_key: Optional[str] = None """Key name to index the inputs to load_memory_variables.""" return_docs: bool = False """Whether or not to return the result of querying the database directly.""" @property def memory_variables(self) -> List[str]: """The list of keys emitted from the load_memory_variables method.""" return [self.memory_key] def _get_prompt_input_key(self, inputs: Dict[str, Any]) -> str: """Get the input key for the prompt.""" if self.input_key is None: return get_prompt_input_key(inputs, self.memory_variables) return self.input_key [docs] def load_memory_variables( self, inputs: Dict[str, Any] ) -> Dict[str, Union[List[Document], str]]: """Return history buffer.""" input_key = self._get_prompt_input_key(inputs) query = inputs[input_key] docs = self.retriever.get_relevant_documents(query)
https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html
1413a1743a14-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, inputs: Dict[str, Any], outputs: Dict[str, str] ) -> List[Document]: """Format context from this conversation to buffer.""" # Each document should only include the current turn, not the chat history filtered_inputs = {k: v for k, v in inputs.items() if k != self.memory_key} texts = [ f"{k}: {v}" for k, v in list(filtered_inputs.items()) + list(outputs.items()) ] page_content = "\n".join(texts) return [Document(page_content=page_content)] [docs] def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: """Save context from this conversation to buffer.""" documents = self._form_documents(inputs, outputs) self.retriever.add_documents(documents) [docs] def clear(self) -> None: """Nothing to clear."""
https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html
44d406f28df8-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 ConversationSummaryBufferMemory(BaseChatMemory, SummarizerMixin): """Buffer with summarizer for storing conversation memory.""" max_token_limit: int = 2000 moving_summary_buffer: str = "" memory_key: str = "history" @property def buffer(self) -> List[BaseMessage]: return self.chat_memory.messages @property def memory_variables(self) -> List[str]: """Will always return list of memory variables. :meta private: """ return [self.memory_key] [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Return history buffer.""" buffer = self.buffer if self.moving_summary_buffer != "": first_messages: List[BaseMessage] = [ self.summary_message_cls(content=self.moving_summary_buffer) ] buffer = first_messages + buffer if self.return_messages: final_buffer: Any = buffer else: final_buffer = get_buffer_string( buffer, human_prefix=self.human_prefix, ai_prefix=self.ai_prefix ) return {self.memory_key: final_buffer} @root_validator() def validate_prompt_input_variables(cls, values: Dict) -> Dict: """Validate that prompt input variables are consistent.""" prompt_variables = values["prompt"].input_variables expected_keys = {"summary", "new_lines"} if expected_keys != set(prompt_variables): raise ValueError(
https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html
44d406f28df8-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], outputs: Dict[str, str]) -> None: """Save context from this conversation to buffer.""" super().save_context(inputs, outputs) self.prune() [docs] def prune(self) -> None: """Prune buffer if it exceeds max token limit""" buffer = self.chat_memory.messages curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer) 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) self.moving_summary_buffer = self.predict_new_summary( pruned_memory, self.moving_summary_buffer ) [docs] def clear(self) -> None: """Clear memory contents.""" super().clear() self.moving_summary_buffer = ""
https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html
5d35781b0235-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): """Buffer for storing conversation memory.""" human_prefix: str = "Human" ai_prefix: str = "AI" llm: BaseLanguageModel memory_key: str = "history" max_token_limit: int = 2000 @property def buffer(self) -> List[BaseMessage]: """String buffer of memory.""" return self.chat_memory.messages @property def memory_variables(self) -> List[str]: """Will always return list of memory variables. :meta private: """ return [self.memory_key] [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Return history buffer.""" buffer: Any = self.buffer if self.return_messages: final_buffer: Any = buffer else: final_buffer = get_buffer_string( buffer, human_prefix=self.human_prefix, ai_prefix=self.ai_prefix, ) return {self.memory_key: final_buffer} [docs] def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: """Save context from this conversation to buffer. Pruned.""" super().save_context(inputs, outputs) # Prune buffer if it exceeds max token limit buffer = self.chat_memory.messages curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer) if curr_buffer_length > self.max_token_limit:
https://api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html
5d35781b0235-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
d6211d0b18b3-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 langchain.memory.chat_memory import BaseChatMemory from langchain.memory.prompt import ( ENTITY_EXTRACTION_PROMPT, ENTITY_SUMMARIZATION_PROMPT, ) from langchain.memory.utils import get_prompt_input_key from langchain.prompts.base import BasePromptTemplate from langchain.schema import BaseMessage, get_buffer_string logger = logging.getLogger(__name__) class BaseEntityStore(BaseModel, ABC): @abstractmethod def get(self, key: str, default: Optional[str] = None) -> Optional[str]: """Get entity value from store.""" pass @abstractmethod def set(self, key: str, value: Optional[str]) -> None: """Set entity value in store.""" pass @abstractmethod def delete(self, key: str) -> None: """Delete entity value from store.""" pass @abstractmethod def exists(self, key: str) -> bool: """Check if entity exists in store.""" pass @abstractmethod def clear(self) -> None: """Delete all entities from store.""" pass [docs]class InMemoryEntityStore(BaseEntityStore): """Basic in-memory entity store.""" store: Dict[str, Optional[str]] = {} [docs] def get(self, key: str, default: Optional[str] = None) -> Optional[str]: return self.store.get(key, default)
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
d6211d0b18b3-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: return self.store.clear() [docs]class RedisEntityStore(BaseEntityStore): """Redis-backed Entity store. Entities get a TTL of 1 day by default, and that TTL is extended by 3 days every time the entity is read back. """ redis_client: Any session_id: str = "default" key_prefix: str = "memory_store" ttl: Optional[int] = 60 * 60 * 24 recall_ttl: Optional[int] = 60 * 60 * 24 * 3 def __init__( self, session_id: str = "default", url: str = "redis://localhost:6379/0", key_prefix: str = "memory_store", ttl: Optional[int] = 60 * 60 * 24, recall_ttl: Optional[int] = 60 * 60 * 24 * 3, *args: Any, **kwargs: Any, ): try: import redis except ImportError: raise ImportError( "Could not import redis python package. " "Please install it with `pip install redis`." ) super().__init__(*args, **kwargs) try: self.redis_client = redis.Redis.from_url(url=url, decode_responses=True)
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
d6211d0b18b3-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 def full_key_prefix(self) -> str: return f"{self.key_prefix}:{self.session_id}" [docs] def get(self, key: str, default: Optional[str] = None) -> Optional[str]: res = ( self.redis_client.getex(f"{self.full_key_prefix}:{key}", ex=self.recall_ttl) or default or "" ) logger.debug(f"REDIS MEM get '{self.full_key_prefix}:{key}': '{res}'") return res [docs] def set(self, key: str, value: Optional[str]) -> None: if not value: return self.delete(key) self.redis_client.set(f"{self.full_key_prefix}:{key}", value, ex=self.ttl) logger.debug( f"REDIS MEM set '{self.full_key_prefix}:{key}': '{value}' EX {self.ttl}" ) [docs] def delete(self, key: str) -> None: self.redis_client.delete(f"{self.full_key_prefix}:{key}") [docs] def exists(self, key: str) -> bool: return self.redis_client.exists(f"{self.full_key_prefix}:{key}") == 1 [docs] def clear(self) -> None: # iterate a list in batches of size batch_size def batched(iterable: Iterable[Any], batch_size: int) -> Iterable[Any]: iterator = iter(iterable)
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
d6211d0b18b3-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(BaseEntityStore): """SQLite-backed Entity store""" session_id: str = "default" table_name: str = "memory_store" def __init__( self, session_id: str = "default", db_file: str = "entities.db", table_name: str = "memory_store", *args: Any, **kwargs: Any, ): try: import sqlite3 except ImportError: raise ImportError( "Could not import sqlite3 python package. " "Please install it with `pip install sqlite3`." ) super().__init__(*args, **kwargs) self.conn = sqlite3.connect(db_file) self.session_id = session_id self.table_name = table_name self._create_table_if_not_exists() @property def full_table_name(self) -> str: return f"{self.table_name}_{self.session_id}" def _create_table_if_not_exists(self) -> None: create_table_query = f""" CREATE TABLE IF NOT EXISTS {self.full_table_name} ( key TEXT PRIMARY KEY, value TEXT ) """ with self.conn: self.conn.execute(create_table_query) [docs] def get(self, key: str, default: Optional[str] = None) -> Optional[str]: query = f""" SELECT value
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
d6211d0b18b3-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] def set(self, key: str, value: Optional[str]) -> None: if not value: return self.delete(key) query = f""" INSERT OR REPLACE INTO {self.full_table_name} (key, value) VALUES (?, ?) """ with self.conn: self.conn.execute(query, (key, value)) [docs] def delete(self, key: str) -> None: query = f""" DELETE FROM {self.full_table_name} WHERE key = ? """ with self.conn: self.conn.execute(query, (key,)) [docs] def exists(self, key: str) -> bool: query = f""" SELECT 1 FROM {self.full_table_name} WHERE key = ? LIMIT 1 """ cursor = self.conn.execute(query, (key,)) result = cursor.fetchone() return result is not None [docs] def clear(self) -> None: query = f""" DELETE FROM {self.full_table_name} """ with self.conn: self.conn.execute(query) [docs]class ConversationEntityMemory(BaseChatMemory): """Entity extractor & summarizer memory. Extracts named entities from the recent chat history and generates summaries. With a swapable entity store, persisting entities across conversations.
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
d6211d0b18b3-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: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT entity_summarization_prompt: BasePromptTemplate = ENTITY_SUMMARIZATION_PROMPT # Cache of recently detected entity names, if any # It is updated when load_memory_variables is called: entity_cache: List[str] = [] # Number of recent message pairs to consider when updating entities: k: int = 3 chat_history_key: str = "history" # Store to manage entity-related data: entity_store: BaseEntityStore = Field(default_factory=InMemoryEntityStore) @property def buffer(self) -> List[BaseMessage]: """Access chat memory messages.""" return self.chat_memory.messages @property def memory_variables(self) -> List[str]: """Will always return list of memory variables. :meta private: """ return ["entities", self.chat_history_key] [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """ Returns chat history and all generated entities with summaries if available, and updates or clears the recent entity cache. New entity name can be found when calling this method, before the entity summaries are generated, so the entity cache values may be empty if no entity descriptions are generated yet. """ # Create an LLMChain for predicting entity names from the recent chat history:
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
d6211d0b18b3-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 = self.input_key # Extract an arbitrary window of the last message pairs from # the chat history, where the hyperparameter k is the # number of message pairs: buffer_string = get_buffer_string( self.buffer[-self.k * 2 :], human_prefix=self.human_prefix, ai_prefix=self.ai_prefix, ) # Generates a comma-separated list of named entities, # e.g. "Jane, White House, UFO" # or "NONE" if no named entities are extracted: output = chain.predict( history=buffer_string, input=inputs[prompt_input_key], ) # If no named entities are extracted, assigns an empty list. if output.strip() == "NONE": entities = [] else: # Make a list of the extracted entities: entities = [w.strip() for w in output.split(",")] # Make a dictionary of entities with summary if exists: entity_summaries = {} for entity in entities: entity_summaries[entity] = self.entity_store.get(entity, "") # Replaces the entity name cache with the most recently discussed entities, # or if no entities were extracted, clears the cache: self.entity_cache = entities # Should we return as message objects or as a string? if self.return_messages: # Get last `k` pair of chat messages:
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
d6211d0b18b3-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_summaries, } [docs] def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: """ Save context from this conversation history to the entity store. Generates a summary for each entity in the entity cache by prompting the model, and saves these summaries to the entity store. """ super().save_context(inputs, outputs) if self.input_key is None: prompt_input_key = get_prompt_input_key(inputs, self.memory_variables) else: prompt_input_key = self.input_key # Extract an arbitrary window of the last message pairs from # the chat history, where the hyperparameter k is the # number of message pairs: buffer_string = get_buffer_string( self.buffer[-self.k * 2 :], human_prefix=self.human_prefix, ai_prefix=self.ai_prefix, ) input_data = inputs[prompt_input_key] # Create an LLMChain for predicting entity summarization from the context chain = LLMChain(llm=self.llm, prompt=self.entity_summarization_prompt) # Generate new summaries for entities and save them in the entity store for entity in self.entity_cache: # Get existing summary if it exists existing_summary = self.entity_store.get(entity, "") output = chain.predict( summary=existing_summary, entity=entity, history=buffer_string,
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
d6211d0b18b3-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 contents.""" self.chat_memory.clear() self.entity_cache.clear() self.entity_store.clear()
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
0490f5d90c2b-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 together.""" memories: List[BaseMemory] """For tracking all the memories that should be accessed.""" @validator("memories") def check_repeated_memory_variable( cls, value: List[BaseMemory] ) -> List[BaseMemory]: all_variables: Set[str] = set() for val in value: overlap = all_variables.intersection(val.memory_variables) if overlap: raise ValueError( f"The same variables {overlap} are found in multiple" "memory object, which is not allowed by CombinedMemory." ) all_variables |= set(val.memory_variables) return value @validator("memories") def check_input_key(cls, value: List[BaseMemory]) -> List[BaseMemory]: """Check that if memories are of type BaseChatMemory that input keys exist.""" for val in value: if isinstance(val, BaseChatMemory): if val.input_key is None: warnings.warn( "When using CombinedMemory, " "input keys should be so the input is known. " f" Was not set on {val}" ) return value @property def memory_variables(self) -> List[str]: """All the memory variables that this instance provides.""" """Collected from the all the linked memories.""" memory_variables = [] for memory in self.memories: memory_variables.extend(memory.memory_variables)
https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html
0490f5d90c2b-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 from all sub-memories for memory in self.memories: data = memory.load_memory_variables(inputs) memory_data = { **memory_data, **data, } return memory_data [docs] def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: """Save context from this session for every memory.""" # Save context for all sub-memories for memory in self.memories: memory.save_context(inputs, outputs) [docs] def clear(self) -> None: """Clear context from this session for every memory.""" for memory in self.memories: memory.clear()
https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html
9e2fee91d441-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_prefix: str = "Human" ai_prefix: str = "AI" memory_key: str = "history" #: :meta private: k: int = 5 @property def buffer(self) -> List[BaseMessage]: """String buffer of memory.""" return self.chat_memory.messages @property def memory_variables(self) -> List[str]: """Will always return list of memory variables. :meta private: """ return [self.memory_key] [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]: """Return history buffer.""" buffer: Any = self.buffer[-self.k * 2 :] if self.k > 0 else [] if not self.return_messages: buffer = get_buffer_string( buffer, human_prefix=self.human_prefix, ai_prefix=self.ai_prefix, ) return {self.memory_key: buffer}
https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html
8c1de358c6e0-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_entities, parse_triples from langchain.memory.chat_memory import BaseChatMemory from langchain.memory.prompt import ( ENTITY_EXTRACTION_PROMPT, KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT, ) from langchain.memory.utils import get_prompt_input_key from langchain.prompts.base import BasePromptTemplate from langchain.schema import ( BaseMessage, SystemMessage, get_buffer_string, ) [docs]class ConversationKGMemory(BaseChatMemory): """Knowledge graph memory for storing conversation memory. Integrates with external knowledge graph to store and retrieve information about knowledge triples in the conversation. """ k: int = 2 human_prefix: str = "Human" ai_prefix: str = "AI" kg: NetworkxEntityGraph = Field(default_factory=NetworkxEntityGraph) knowledge_extraction_prompt: BasePromptTemplate = KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT entity_extraction_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT llm: BaseLanguageModel summary_message_cls: Type[BaseMessage] = SystemMessage """Number of previous utterances to include in the context.""" memory_key: str = "history" #: :meta private: [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Return history buffer.""" entities = self._get_current_entities(inputs) summary_strings = []
https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html
8c1de358c6e0-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) context: Union[str, List] if not summary_strings: context = [] if self.return_messages else "" elif self.return_messages: context = [ self.summary_message_cls(content=text) for text in summary_strings ] else: context = "\n".join(summary_strings) return {self.memory_key: context} @property def memory_variables(self) -> List[str]: """Will always return list of memory variables. :meta private: """ return [self.memory_key] def _get_prompt_input_key(self, inputs: Dict[str, Any]) -> str: """Get the input key for the prompt.""" if self.input_key is None: return get_prompt_input_key(inputs, self.memory_variables) return self.input_key def _get_prompt_output_key(self, outputs: Dict[str, Any]) -> str: """Get the output key for the prompt.""" if self.output_key is None: if len(outputs) != 1: raise ValueError(f"One output key expected, got {outputs.keys()}") return list(outputs.keys())[0] return self.output_key [docs] def get_current_entities(self, input_string: str) -> List[str]: chain = LLMChain(llm=self.llm, prompt=self.entity_extraction_prompt) buffer_string = get_buffer_string( self.chat_memory.messages[-self.k * 2 :], human_prefix=self.human_prefix,
https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html
8c1de358c6e0-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 current entities in the conversation.""" prompt_input_key = self._get_prompt_input_key(inputs) return self.get_current_entities(inputs[prompt_input_key]) [docs] def get_knowledge_triplets(self, input_string: str) -> List[KnowledgeTriple]: chain = LLMChain(llm=self.llm, prompt=self.knowledge_extraction_prompt) buffer_string = get_buffer_string( self.chat_memory.messages[-self.k * 2 :], human_prefix=self.human_prefix, ai_prefix=self.ai_prefix, ) output = chain.predict( history=buffer_string, input=input_string, verbose=True, ) knowledge = parse_triples(output) return knowledge def _get_and_update_kg(self, inputs: Dict[str, Any]) -> None: """Get and update knowledge graph from the conversation history.""" prompt_input_key = self._get_prompt_input_key(inputs) knowledge = self.get_knowledge_triplets(inputs[prompt_input_key]) for triple in knowledge: self.kg.add_triple(triple) [docs] def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: """Save context from this conversation to buffer.""" super().save_context(inputs, outputs) self._get_and_update_kg(inputs) [docs] def clear(self) -> None: """Clear memory contents."""
https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html
8c1de358c6e0-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
e0f2544af2ff-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 FileChatMessageHistory(BaseChatMessageHistory): """ Chat message history that stores history in a local file. Args: file_path: path of the local file to store the messages. """ def __init__(self, file_path: str): self.file_path = Path(file_path) if not self.file_path.exists(): self.file_path.touch() self.file_path.write_text(json.dumps([])) @property def messages(self) -> List[BaseMessage]: # type: ignore """Retrieve the messages from the local file""" items = json.loads(self.file_path.read_text()) messages = messages_from_dict(items) return messages [docs] def add_message(self, message: BaseMessage) -> None: """Append the message to the record in the local file""" messages = messages_to_dict(self.messages) messages.append(messages_to_dict([message])[0]) self.file_path.write_text(json.dumps(messages)) [docs] def clear(self) -> None: """Clear session memory from the local file""" self.file_path.write_text(json.dumps([]))
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html
8e435060b580-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" DEFAULT_TABLE_NAME = "message_store" DEFAULT_USERNAME = "cassandra" DEFAULT_PASSWORD = "cassandra" DEFAULT_PORT = 9042 [docs]class CassandraChatMessageHistory(BaseChatMessageHistory): """Chat message history that stores history in Cassandra. Args: contact_points: list of ips to connect to Cassandra cluster session_id: arbitrary key that is used to store the messages of a single chat session. port: port to connect to Cassandra cluster username: username to connect to Cassandra cluster password: password to connect to Cassandra cluster keyspace_name: name of the keyspace to use table_name: name of the table to use """ def __init__( self, contact_points: List[str], session_id: str, port: int = DEFAULT_PORT, username: str = DEFAULT_USERNAME, password: str = DEFAULT_PASSWORD, keyspace_name: str = DEFAULT_KEYSPACE_NAME, table_name: str = DEFAULT_TABLE_NAME, ): self.contact_points = contact_points self.session_id = session_id self.port = port self.username = username self.password = password self.keyspace_name = keyspace_name self.table_name = table_name try: from cassandra import ( AuthenticationFailed, OperationTimedOut, UnresolvableContactPoints, )
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
8e435060b580-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 install cassandra-driver`." ) self.cluster: Cluster = Cluster( contact_points, port=port, auth_provider=PlainTextAuthProvider( username=self.username, password=self.password ), ) try: self.session = self.cluster.connect() except ( AuthenticationFailed, UnresolvableContactPoints, OperationTimedOut, ) as error: logger.error( "Unable to establish connection with \ cassandra chat message history database" ) raise error self._prepare_cassandra() def _prepare_cassandra(self) -> None: """Create the keyspace and table if they don't exist yet""" from cassandra import OperationTimedOut, Unavailable try: self.session.execute( f"""CREATE KEYSPACE IF NOT EXISTS {self.keyspace_name} WITH REPLICATION = {{ 'class' : 'SimpleStrategy', 'replication_factor' : 1 }};""" ) except (OperationTimedOut, Unavailable) as error: logger.error( f"Unable to create cassandra \ chat message history keyspace: {self.keyspace_name}." ) raise error self.session.set_keyspace(self.keyspace_name) try: self.session.execute( f"""CREATE TABLE IF NOT EXISTS {self.table_name} (id UUID, session_id varchar,
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
8e435060b580-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_name}" ) raise error @property def messages(self) -> List[BaseMessage]: # type: ignore """Retrieve the messages from Cassandra""" from cassandra import ReadFailure, ReadTimeout, Unavailable try: rows = self.session.execute( f"""SELECT * FROM {self.table_name} WHERE session_id = '{self.session_id}' ;""" ) except (Unavailable, ReadTimeout, ReadFailure) as error: logger.error("Unable to Retreive chat history messages from cassadra") raise error if rows: items = [json.loads(row.history) for row in rows] else: items = [] messages = messages_from_dict(items) return messages [docs] def add_message(self, message: BaseMessage) -> None: """Append the message to the record in Cassandra""" import uuid from cassandra import Unavailable, WriteFailure, WriteTimeout try: self.session.execute( """INSERT INTO message_store (id, session_id, history) VALUES (%s, %s, %s);""", (uuid.uuid4(), self.session_id, json.dumps(_message_to_dict(message))), ) except (Unavailable, WriteTimeout, WriteFailure) as error: logger.error("Unable to write chat history messages to cassandra") raise error
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
8e435060b580-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.table_name} WHERE session_id = '{self.session_id}';" ) except (Unavailable, OperationTimedOut) as error: logger.error("Unable to clear chat history messages from cassandra") raise error def __del__(self) -> None: if self.session: self.session.shutdown() if self.cluster: self.cluster.shutdown()
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
5dd70df681b4-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, messages_from_dict, messages_to_dict, ) logger = logging.getLogger(__name__) if TYPE_CHECKING: from azure.cosmos import ContainerProxy [docs]class CosmosDBChatMessageHistory(BaseChatMessageHistory): """Chat history backed by Azure CosmosDB.""" def __init__( self, cosmos_endpoint: str, cosmos_database: str, cosmos_container: str, session_id: str, user_id: str, credential: Any = None, connection_string: Optional[str] = None, ttl: Optional[int] = None, cosmos_client_kwargs: Optional[dict] = None, ): """ Initializes a new instance of the CosmosDBChatMessageHistory class. Make sure to call prepare_cosmos or use the context manager to make sure your database is ready. Either a credential or a connection string must be provided. :param cosmos_endpoint: The connection endpoint for the Azure Cosmos DB account. :param cosmos_database: The name of the database to use. :param cosmos_container: The name of the container to use. :param session_id: The session ID to use, can be overwritten while loading. :param user_id: The user ID to use, can be overwritten while loading. :param credential: The credential to use to authenticate to Azure Cosmos DB. :param connection_string: The connection string to use to authenticate.
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
5dd70df681b4-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.cosmos_database = cosmos_database self.cosmos_container = cosmos_container self.credential = credential self.conn_string = connection_string self.session_id = session_id self.user_id = user_id self.ttl = ttl self.messages: List[BaseMessage] = [] try: from azure.cosmos import ( # pylint: disable=import-outside-toplevel # noqa: E501 CosmosClient, ) except ImportError as exc: raise ImportError( "You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501 ) from exc if self.credential: self._client = CosmosClient( url=self.cosmos_endpoint, credential=self.credential, **cosmos_client_kwargs or {}, ) elif self.conn_string: self._client = CosmosClient.from_connection_string( conn_str=self.conn_string, **cosmos_client_kwargs or {}, ) else: raise ValueError("Either a connection string or a credential must be set.") self._container: Optional[ContainerProxy] = None [docs] def prepare_cosmos(self) -> None: """Prepare the CosmosDB client. Use this function or the context manager to make sure your database is ready. """ try: from azure.cosmos import ( # pylint: disable=import-outside-toplevel # noqa: E501
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
5dd70df681b4-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) self._container = database.create_container_if_not_exists( self.cosmos_container, partition_key=PartitionKey("/user_id"), default_ttl=self.ttl, ) self.load_messages() def __enter__(self) -> "CosmosDBChatMessageHistory": """Context manager entry point.""" self._client.__enter__() self.prepare_cosmos() return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], traceback: Optional[TracebackType], ) -> None: """Context manager exit""" self.upsert_messages() self._client.__exit__(exc_type, exc_val, traceback) [docs] def load_messages(self) -> None: """Retrieve the messages from Cosmos""" if not self._container: raise ValueError("Container not initialized") try: from azure.cosmos.exceptions import ( # pylint: disable=import-outside-toplevel # noqa: E501 CosmosHttpResponseError, ) except ImportError as exc: raise ImportError( "You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501 ) from exc try: item = self._container.read_item( item=self.session_id, partition_key=self.user_id ) except CosmosHttpResponseError:
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
5dd70df681b4-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-created message to the store""" self.messages.append(message) self.upsert_messages() [docs] def upsert_messages(self) -> None: """Update the cosmosdb item.""" if not self._container: raise ValueError("Container not initialized") self._container.upsert_item( body={ "id": self.session_id, "user_id": self.user_id, "messages": messages_to_dict(self.messages), } ) [docs] def clear(self) -> None: """Clear session memory from this memory and cosmos.""" self.messages = [] if self._container: self._container.delete_item( item=self.session_id, partition_key=self.user_id )
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
19954595db5d-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_COLLECTION_NAME = "message_store" [docs]class MongoDBChatMessageHistory(BaseChatMessageHistory): """Chat message history that stores history in MongoDB. Args: connection_string: connection string to connect to MongoDB session_id: arbitrary key that is used to store the messages of a single chat session. database_name: name of the database to use collection_name: name of the collection to use """ def __init__( self, connection_string: str, session_id: str, database_name: str = DEFAULT_DBNAME, collection_name: str = DEFAULT_COLLECTION_NAME, ): from pymongo import MongoClient, errors self.connection_string = connection_string self.session_id = session_id self.database_name = database_name self.collection_name = collection_name try: self.client: MongoClient = MongoClient(connection_string) except errors.ConnectionFailure as error: logger.error(error) self.db = self.client[database_name] self.collection = self.db[collection_name] self.collection.create_index("SessionId") @property def messages(self) -> List[BaseMessage]: # type: ignore """Retrieve the messages from MongoDB""" from pymongo import errors try: cursor = self.collection.find({"SessionId": self.session_id}) except errors.OperationFailure as error: logger.error(error) if cursor:
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html
19954595db5d-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: BaseMessage) -> None: """Append the message to the record in MongoDB""" from pymongo import errors try: self.collection.insert_one( { "SessionId": self.session_id, "History": json.dumps(_message_to_dict(message)), } ) except errors.WriteError as err: logger.error(err) [docs] def clear(self) -> None: """Clear session memory from MongoDB""" from pymongo import errors try: self.collection.delete_many({"SessionId": self.session_id}) except errors.WriteError as err: logger.error(err)
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html
57a9956fb9b9-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.orm import sessionmaker from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) def create_message_model(table_name, DynamicBase): # type: ignore """ Create a message model for a given table name. Args: table_name: The name of the table to use. DynamicBase: The base class to use for the model. Returns: The model class. """ # Model decleared inside a function to have a dynamic table name class Message(DynamicBase): __tablename__ = table_name id = Column(Integer, primary_key=True) session_id = Column(Text) message = Column(Text) return Message [docs]class SQLChatMessageHistory(BaseChatMessageHistory): """Chat message history stored in an SQL database.""" def __init__( self, session_id: str, connection_string: str, table_name: str = "message_store", ): self.table_name = table_name self.connection_string = connection_string self.engine = create_engine(connection_string, echo=False) self._create_table_if_not_exists() self.session_id = session_id self.Session = sessionmaker(self.engine) def _create_table_if_not_exists(self) -> None: DynamicBase = declarative_base()
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html
57a9956fb9b9-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 """Retrieve all messages from db""" with self.Session() as session: result = session.query(self.Message).where( self.Message.session_id == self.session_id ) items = [json.loads(record.message) for record in result] messages = messages_from_dict(items) return messages [docs] def add_message(self, message: BaseMessage) -> None: """Append the message to the record in db""" with self.Session() as session: jsonstr = json.dumps(_message_to_dict(message)) session.add(self.Message(session_id=self.session_id, message=jsonstr)) session.commit() [docs] def clear(self) -> None: """Clear session memory from db""" with self.Session() as session: session.query(self.Message).filter( self.Message.session_id == self.session_id ).delete() session.commit()
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html
238cd9eca70c-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 langchain.utils import get_from_env if TYPE_CHECKING: import momento def _ensure_cache_exists(cache_client: momento.CacheClient, cache_name: str) -> None: """Create cache if it doesn't exist. Raises: SdkException: Momento service or network error Exception: Unexpected response """ from momento.responses import CreateCache create_cache_response = cache_client.create_cache(cache_name) if isinstance(create_cache_response, CreateCache.Success) or isinstance( create_cache_response, CreateCache.CacheAlreadyExists ): return None elif isinstance(create_cache_response, CreateCache.Error): raise create_cache_response.inner_exception else: raise Exception(f"Unexpected response cache creation: {create_cache_response}") [docs]class MomentoChatMessageHistory(BaseChatMessageHistory): """Chat message history cache that uses Momento as a backend. See https://gomomento.com/""" def __init__( self, session_id: str, cache_client: momento.CacheClient, cache_name: str, *, key_prefix: str = "message_store:", ttl: Optional[timedelta] = None, ensure_cache_exists: bool = True, ): """Instantiate a chat message history cache that uses Momento as a backend. Note: to instantiate the cache client passed to MomentoChatMessageHistory,
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html
238cd9eca70c-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 (str): The name of the cache to use to store the messages. key_prefix (str, optional): The prefix to apply to the cache key. Defaults to "message_store:". ttl (Optional[timedelta], optional): The TTL to use for the messages. Defaults to None, ie the default TTL of the cache will be used. ensure_cache_exists (bool, optional): Create the cache if it doesn't exist. Defaults to True. Raises: ImportError: Momento python package is not installed. TypeError: cache_client is not of type momento.CacheClientObject """ try: from momento import CacheClient from momento.requests import CollectionTtl except ImportError: raise ImportError( "Could not import momento python package. " "Please install it with `pip install momento`." ) if not isinstance(cache_client, CacheClient): raise TypeError("cache_client must be a momento.CacheClient object.") if ensure_cache_exists: _ensure_cache_exists(cache_client, cache_name) self.key = key_prefix + session_id self.cache_client = cache_client self.cache_name = cache_name if ttl is not None: self.ttl = CollectionTtl.of(ttl) else: self.ttl = CollectionTtl.from_cache_ttl() [docs] @classmethod def from_client_params( cls, session_id: str,
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html
238cd9eca70c-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 from CacheClient parameters.""" try: from momento import CacheClient, Configurations, CredentialProvider except ImportError: raise ImportError( "Could not import momento python package. " "Please install it with `pip install momento`." ) if configuration is None: configuration = Configurations.Laptop.v1() auth_token = auth_token or get_from_env("auth_token", "MOMENTO_AUTH_TOKEN") credentials = CredentialProvider.from_string(auth_token) cache_client = CacheClient(configuration, credentials, default_ttl=ttl) return cls(session_id, cache_client, cache_name, ttl=ttl, **kwargs) @property def messages(self) -> list[BaseMessage]: # type: ignore[override] """Retrieve the messages from Momento. Raises: SdkException: Momento service or network error Exception: Unexpected response Returns: list[BaseMessage]: List of cached messages """ from momento.responses import CacheListFetch fetch_response = self.cache_client.list_fetch(self.cache_name, self.key) if isinstance(fetch_response, CacheListFetch.Hit): items = [json.loads(m) for m in fetch_response.value_list_string] return messages_from_dict(items) elif isinstance(fetch_response, CacheListFetch.Miss): return [] elif isinstance(fetch_response, CacheListFetch.Error):
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html
238cd9eca70c-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. Args: message (BaseMessage): The message object to store. Raises: SdkException: Momento service or network error. Exception: Unexpected response. """ from momento.responses import CacheListPushBack item = json.dumps(_message_to_dict(message)) push_response = self.cache_client.list_push_back( self.cache_name, self.key, item, ttl=self.ttl ) if isinstance(push_response, CacheListPushBack.Success): return None elif isinstance(push_response, CacheListPushBack.Error): raise push_response.inner_exception else: raise Exception(f"Unexpected response: {push_response}") [docs] def clear(self) -> None: """Remove the session's messages from the cache. Raises: SdkException: Momento service or network error. Exception: Unexpected response. """ from momento.responses import CacheDelete delete_response = self.cache_client.delete(self.cache_name, self.key) if isinstance(delete_response, CacheDelete.Success): return None elif isinstance(delete_response, CacheDelete.Error): raise delete_response.inner_exception else: raise Exception(f"Unexpected response: {delete_response}")
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html
dd453150ddf3-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://postgres:mypassword@localhost/chat_history" [docs]class PostgresChatMessageHistory(BaseChatMessageHistory): """Chat message history stored in a Postgres database.""" def __init__( self, session_id: str, connection_string: str = DEFAULT_CONNECTION_STRING, table_name: str = "message_store", ): import psycopg from psycopg.rows import dict_row try: self.connection = psycopg.connect(connection_string) self.cursor = self.connection.cursor(row_factory=dict_row) except psycopg.OperationalError as error: logger.error(error) self.session_id = session_id self.table_name = table_name self._create_table_if_not_exists() def _create_table_if_not_exists(self) -> None: create_table_query = f"""CREATE TABLE IF NOT EXISTS {self.table_name} ( id SERIAL PRIMARY KEY, session_id TEXT NOT NULL, message JSONB NOT NULL );""" self.cursor.execute(create_table_query) self.connection.commit() @property def messages(self) -> List[BaseMessage]: # type: ignore """Retrieve the messages from PostgreSQL""" query = f"SELECT message FROM {self.table_name} WHERE session_id = %s;" self.cursor.execute(query, (self.session_id,)) items = [record["message"] for record in self.cursor.fetchall()] messages = messages_from_dict(items)
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
dd453150ddf3-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( sql.Identifier(self.table_name) ) self.cursor.execute( query, (self.session_id, json.dumps(_message_to_dict(message))) ) self.connection.commit() [docs] def clear(self) -> None: """Clear session memory from PostgreSQL""" query = f"DELETE FROM {self.table_name} WHERE session_id = %s;" self.cursor.execute(query, (self.session_id,)) self.connection.commit() def __del__(self) -> None: if self.cursor: self.cursor.close() if self.connection: self.connection.close()
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
e876b100fc58-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 Memory, MemorySearchResult, Message, NotFoundError logger = logging.getLogger(__name__) [docs]class ZepChatMessageHistory(BaseChatMessageHistory): """A ChatMessageHistory implementation that uses Zep as a backend. Recommended usage:: # Set up Zep Chat History zep_chat_history = ZepChatMessageHistory( session_id=session_id, url=ZEP_API_URL, ) # Use a standard ConversationBufferMemory to encapsulate the Zep chat history memory = ConversationBufferMemory( memory_key="chat_history", chat_memory=zep_chat_history ) Zep provides long-term conversation storage for LLM apps. The server stores, summarizes, embeds, indexes, and enriches conversational AI chat histories, and exposes them via simple, low-latency APIs. For server installation instructions and more, see: https://getzep.github.io/ This class is a thin wrapper around the zep-python package. Additional Zep functionality is exposed via the `zep_summary` and `zep_messages` properties. For more information on the zep-python package, see: https://github.com/getzep/zep-python """ def __init__( self, session_id: str, url: str = "http://localhost:8000", ) -> None: try:
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html
e876b100fc58-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) self.session_id = session_id @property def messages(self) -> List[BaseMessage]: # type: ignore """Retrieve messages from Zep memory""" zep_memory: Optional[Memory] = self._get_memory() if not zep_memory: return [] messages: List[BaseMessage] = [] # Extract summary, if present, and messages if zep_memory.summary: if len(zep_memory.summary.content) > 0: messages.append(HumanMessage(content=zep_memory.summary.content)) if zep_memory.messages: msg: Message for msg in zep_memory.messages: if msg.role == "ai": messages.append(AIMessage(content=msg.content)) else: messages.append(HumanMessage(content=msg.content)) return messages @property def zep_messages(self) -> List[Message]: """Retrieve summary from Zep memory""" zep_memory: Optional[Memory] = self._get_memory() if not zep_memory: return [] return zep_memory.messages @property def zep_summary(self) -> Optional[str]: """Retrieve summary from Zep memory""" zep_memory: Optional[Memory] = self._get_memory() if not zep_memory or not zep_memory.summary: return None return zep_memory.summary.content
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html
e876b100fc58-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: logger.warning( f"Session {self.session_id} not found in Zep. Returning None" ) return None return zep_memory [docs] def add_message(self, message: BaseMessage) -> None: """Append the message to the Zep memory history""" from zep_python import Memory, Message zep_message: Message if isinstance(message, HumanMessage): zep_message = Message(content=message.content, role="human") else: zep_message = Message(content=message.content, role="ai") zep_memory = Memory(messages=[zep_message]) self.zep_client.add_memory(self.session_id, zep_memory) [docs] def search( self, query: str, metadata: Optional[Dict] = None, limit: Optional[int] = None ) -> List[MemorySearchResult]: """Search Zep memory for messages matching the query""" from zep_python import MemorySearchPayload payload: MemorySearchPayload = MemorySearchPayload( text=query, metadata=metadata ) return self.zep_client.search_memory(self.session_id, payload, limit=limit) [docs] def clear(self) -> None: """Clear session memory from Zep. Note that Zep is long-term storage for memory and this is not advised unless you have specific data retention requirements. """ try:
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html
e876b100fc58-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
53a9d10a7316-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 DynamoDBChatMessageHistory(BaseChatMessageHistory): """Chat message history that stores history in AWS DynamoDB. This class expects that a DynamoDB table with name `table_name` and a partition Key of `SessionId` is present. Args: table_name: name of the DynamoDB table session_id: arbitrary key that is used to store the messages of a single chat session. endpoint_url: URL of the AWS endpoint to connect to. This argument is optional and useful for test purposes, like using Localstack. If you plan to use AWS cloud service, you normally don't have to worry about setting the endpoint_url. """ def __init__( self, table_name: str, session_id: str, endpoint_url: Optional[str] = None ): import boto3 if endpoint_url: client = boto3.resource("dynamodb", endpoint_url=endpoint_url) else: client = boto3.resource("dynamodb") self.table = client.Table(table_name) self.session_id = session_id @property def messages(self) -> List[BaseMessage]: # type: ignore """Retrieve the messages from DynamoDB""" from botocore.exceptions import ClientError response = None try: response = self.table.get_item(Key={"SessionId": self.session_id}) except ClientError as error:
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
53a9d10a7316-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 = response["Item"]["History"] else: items = [] messages = messages_from_dict(items) return messages [docs] def add_message(self, message: BaseMessage) -> None: """Append the message to the record in DynamoDB""" from botocore.exceptions import ClientError messages = messages_to_dict(self.messages) _message = _message_to_dict(message) messages.append(_message) try: self.table.put_item( Item={"SessionId": self.session_id, "History": messages} ) except ClientError as err: logger.error(err) [docs] def clear(self) -> None: """Clear session memory from DynamoDB""" from botocore.exceptions import ClientError try: self.table.delete_item(Key={"SessionId": self.session_id}) except ClientError as err: logger.error(err)
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
7376c5e2441a-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_message(self, message: BaseMessage) -> None: """Add a self-created message to the store""" self.messages.append(message) [docs] def clear(self) -> None: self.messages = []
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html
7beeb594e6c2-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(BaseChatMessageHistory): """Chat message history stored in a Redis database.""" def __init__( self, session_id: str, url: str = "redis://localhost:6379/0", key_prefix: str = "message_store:", ttl: Optional[int] = None, ): try: import redis except ImportError: raise ImportError( "Could not import redis python package. " "Please install it with `pip install redis`." ) try: self.redis_client = redis.Redis.from_url(url=url) except redis.exceptions.ConnectionError as error: logger.error(error) self.session_id = session_id self.key_prefix = key_prefix self.ttl = ttl @property def key(self) -> str: """Construct the record key to use""" return self.key_prefix + self.session_id @property def messages(self) -> List[BaseMessage]: # type: ignore """Retrieve the messages from Redis""" _items = self.redis_client.lrange(self.key, 0, -1) items = [json.loads(m.decode("utf-8")) for m in _items[::-1]] messages = messages_from_dict(items) return messages [docs] def add_message(self, message: BaseMessage) -> None: """Append the message to the record in Redis"""
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html
7beeb594e6c2-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(self.key)
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html
cdc99c384235-0
Source code for langchain.tools.plugin from __future__ import annotations import json from typing import Optional, Type import requests import yaml from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool class ApiConfig(BaseModel): type: str url: str has_user_authentication: Optional[bool] = False class AIPlugin(BaseModel): """AI Plugin Definition.""" schema_version: str name_for_model: str name_for_human: str description_for_model: str description_for_human: str auth: Optional[dict] = None api: ApiConfig logo_url: Optional[str] contact_email: Optional[str] legal_info_url: Optional[str] @classmethod def from_url(cls, url: str) -> AIPlugin: """Instantiate AIPlugin from a URL.""" response = requests.get(url).json() return cls(**response) def marshal_spec(txt: str) -> dict: """Convert the yaml or json serialized spec to a dict. Args: txt: The yaml or json serialized spec. Returns: dict: The spec as a dict. """ try: return json.loads(txt) except json.JSONDecodeError: return yaml.safe_load(txt) class AIPluginToolSchema(BaseModel): """AIPLuginToolSchema.""" tool_input: Optional[str] = "" [docs]class AIPluginTool(BaseTool): plugin: AIPlugin api_spec: str args_schema: Type[AIPluginToolSchema] = AIPluginToolSchema [docs] @classmethod
https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
cdc99c384235-1
[docs] @classmethod def from_plugin_url(cls, url: str) -> AIPluginTool: plugin = AIPlugin.from_url(url) description = ( f"Call this tool to get the OpenAPI spec (and usage guide) " f"for interacting with the {plugin.name_for_human} API. " f"You should only call this ONCE! What is the " f"{plugin.name_for_human} API useful for? " ) + plugin.description_for_human open_api_spec_str = requests.get(plugin.api.url).text open_api_spec = marshal_spec(open_api_spec_str) api_spec = ( f"Usage Guide: {plugin.description_for_model}\n\n" f"OpenAPI Spec: {open_api_spec}" ) return cls( name=plugin.name_for_model, description=description, plugin=plugin, api_spec=api_spec, ) def _run( self, tool_input: Optional[str] = "", run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return self.api_spec async def _arun( self, tool_input: Optional[str] = None, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" return self.api_spec
https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
e70adbec46de-0
Source code for langchain.tools.ifttt """From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services. # Creating a webhook - Go to https://ifttt.com/create # Configuring the "If This" - Click on the "If This" button in the IFTTT interface. - Search for "Webhooks" in the search bar. - Choose the first option for "Receive a web request with a JSON payload." - Choose an Event Name that is specific to the service you plan to connect to. This will make it easier for you to manage the webhook URL. For example, if you're connecting to Spotify, you could use "Spotify" as your Event Name. - Click the "Create Trigger" button to save your settings and create your webhook. # Configuring the "Then That" - Tap on the "Then That" button in the IFTTT interface. - Search for the service you want to connect, such as Spotify. - Choose an action from the service, such as "Add track to a playlist". - Configure the action by specifying the necessary details, such as the playlist name, e.g., "Songs from AI". - Reference the JSON Payload received by the Webhook in your action. For the Spotify scenario, choose "{{JsonPayload}}" as your search query. - Tap the "Create Action" button to save your action settings. - Once you have finished configuring your action, click the "Finish" button to complete the setup. - Congratulations! You have successfully connected the Webhook to the desired service, and you're ready to start receiving data and triggering actions 🎉 # Finishing up - To get your webhook URL go to https://ifttt.com/maker_webhooks/settings
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
e70adbec46de-1
- To get your webhook URL go to https://ifttt.com/maker_webhooks/settings - Copy the IFTTT key value from there. The URL is of the form https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value. """ from typing import Optional import requests from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool [docs]class IFTTTWebhook(BaseTool): """IFTTT Webhook. Args: name: name of the tool description: description of the tool url: url to hit with the json event. """ url: str def _run( self, tool_input: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: body = {"this": tool_input} response = requests.post(self.url, data=body) return response.text async def _arun( self, tool_input: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: raise NotImplementedError("Not implemented.")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
80dd8652ea69-0
Source code for langchain.tools.convert_to_openai from typing import TypedDict from langchain.tools import BaseTool, StructuredTool class FunctionDescription(TypedDict): """Representation of a callable function to the OpenAI API.""" name: str """The name of the function.""" description: str """A description of the function.""" parameters: dict """The parameters of the function.""" [docs]def format_tool_to_openai_function(tool: BaseTool) -> FunctionDescription: """Format tool into the OpenAI function API.""" if isinstance(tool, StructuredTool): schema_ = tool.args_schema.schema() # Bug with required missing for structured tools. required = sorted(schema_["properties"]) # BUG WORKAROUND return { "name": tool.name, "description": tool.description, "parameters": { "type": "object", "properties": schema_["properties"], "required": required, }, } else: if tool.args_schema: parameters = tool.args_schema.schema() else: parameters = { # This is a hack to get around the fact that some tools # do not expose an args_schema, and expect an argument # which is a string. # And Open AI does not support an array type for the # parameters. "properties": { "__arg1": {"title": "__arg1", "type": "string"}, }, "required": ["__arg1"], "type": "object", } return { "name": tool.name, "description": tool.description, "parameters": parameters, }
https://api.python.langchain.com/en/latest/_modules/langchain/tools/convert_to_openai.html
866f8f636565-0
Source code for langchain.tools.base """Base implementation for tools or skills.""" from __future__ import annotations import warnings from abc import ABC, abstractmethod from inspect import signature from typing import Any, Awaitable, Callable, Dict, Optional, Tuple, Type, Union from pydantic import ( BaseModel, Extra, Field, create_model, root_validator, validate_arguments, ) from pydantic.main import ModelMetaclass from langchain.callbacks.base import BaseCallbackManager from langchain.callbacks.manager import ( AsyncCallbackManager, AsyncCallbackManagerForToolRun, CallbackManager, CallbackManagerForToolRun, Callbacks, ) class SchemaAnnotationError(TypeError): """Raised when 'args_schema' is missing or has an incorrect type annotation.""" class ToolMetaclass(ModelMetaclass): """Metaclass for BaseTool to ensure the provided args_schema doesn't silently ignored.""" def __new__( cls: Type[ToolMetaclass], name: str, bases: Tuple[Type, ...], dct: dict ) -> ToolMetaclass: """Create the definition of the new tool class.""" schema_type: Optional[Type[BaseModel]] = dct.get("args_schema") if schema_type is not None: schema_annotations = dct.get("__annotations__", {}) args_schema_type = schema_annotations.get("args_schema", None) if args_schema_type is None or args_schema_type == BaseModel: # Throw errors for common mis-annotations. # TODO: Use get_args / get_origin and fully # specify valid annotations. typehint_mandate = """ class ChildTool(BaseTool): ... args_schema: Type[BaseModel] = SchemaClass ..."""
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-1
... args_schema: Type[BaseModel] = SchemaClass ...""" raise SchemaAnnotationError( f"Tool definition for {name} must include valid type annotations" f" for argument 'args_schema' to behave as expected.\n" f"Expected annotation of 'Type[BaseModel]'" f" but got '{args_schema_type}'.\n" f"Expected class looks like:\n" f"{typehint_mandate}" ) # Pass through to Pydantic's metaclass return super().__new__(cls, name, bases, dct) def _create_subset_model( name: str, model: BaseModel, field_names: list ) -> Type[BaseModel]: """Create a pydantic model with only a subset of model's fields.""" fields = {} for field_name in field_names: field = model.__fields__[field_name] fields[field_name] = (field.type_, field.field_info) return create_model(name, **fields) # type: ignore def _get_filtered_args( inferred_model: Type[BaseModel], func: Callable, ) -> dict: """Get the arguments from a function's signature.""" schema = inferred_model.schema()["properties"] valid_keys = signature(func).parameters return {k: schema[k] for k in valid_keys if k not in ("run_manager", "callbacks")} class _SchemaConfig: """Configuration for the pydantic model.""" extra = Extra.forbid arbitrary_types_allowed = True def create_schema_from_function( model_name: str, func: Callable, ) -> Type[BaseModel]: """Create a pydantic schema from a function's signature.
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-2
"""Create a pydantic schema from a function's signature. Args: model_name: Name to assign to the generated pydandic schema func: Function to generate the schema from Returns: A pydantic model with the same arguments as the function """ # https://docs.pydantic.dev/latest/usage/validation_decorator/ validated = validate_arguments(func, config=_SchemaConfig) # type: ignore inferred_model = validated.model # type: ignore if "run_manager" in inferred_model.__fields__: del inferred_model.__fields__["run_manager"] if "callbacks" in inferred_model.__fields__: del inferred_model.__fields__["callbacks"] # Pydantic adds placeholder virtual fields we need to strip valid_properties = _get_filtered_args(inferred_model, func) return _create_subset_model( f"{model_name}Schema", inferred_model, list(valid_properties) ) class ToolException(Exception): """An optional exception that tool throws when execution error occurs. When this exception is thrown, the agent will not stop working, but will handle the exception according to the handle_tool_error variable of the tool, and the processing result will be returned to the agent as observation, and printed in red on the console. """ pass [docs]class BaseTool(ABC, BaseModel, metaclass=ToolMetaclass): """Interface LangChain tools must implement.""" name: str """The unique name of the tool that clearly communicates its purpose.""" description: str """Used to tell the model how/when/why to use the tool. You can provide few-shot examples as a part of the description. """
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-3
You can provide few-shot examples as a part of the description. """ args_schema: Optional[Type[BaseModel]] = None """Pydantic model class to validate and parse the tool's input arguments.""" return_direct: bool = False """Whether to return the tool's output directly. Setting this to True means that after the tool is called, the AgentExecutor will stop looping. """ verbose: bool = False """Whether to log the tool's progress.""" callbacks: Callbacks = Field(default=None, exclude=True) """Callbacks to be called during tool execution.""" callback_manager: Optional[BaseCallbackManager] = Field(default=None, exclude=True) """Deprecated. Please use callbacks instead.""" handle_tool_error: Optional[ Union[bool, str, Callable[[ToolException], str]] ] = False """Handle the content of the ToolException thrown.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def is_single_input(self) -> bool: """Whether the tool only accepts a single input.""" keys = {k for k in self.args if k != "kwargs"} return len(keys) == 1 @property def args(self) -> dict: if self.args_schema is not None: return self.args_schema.schema()["properties"] else: schema = create_schema_from_function(self.name, self._run) return schema.schema()["properties"] def _parse_input( self, tool_input: Union[str, Dict], ) -> Union[str, Dict[str, Any]]: """Convert tool input to pydantic model."""
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-4
"""Convert tool input to pydantic model.""" input_args = self.args_schema if isinstance(tool_input, str): if input_args is not None: key_ = next(iter(input_args.__fields__.keys())) input_args.validate({key_: tool_input}) return tool_input else: if input_args is not None: result = input_args.parse_obj(tool_input) return {k: v for k, v in result.dict().items() if k in tool_input} return tool_input @root_validator() def raise_deprecation(cls, values: Dict) -> Dict: """Raise deprecation warning if callback_manager is used.""" if values.get("callback_manager") is not None: warnings.warn( "callback_manager is deprecated. Please use callbacks instead.", DeprecationWarning, ) values["callbacks"] = values.pop("callback_manager", None) return values @abstractmethod def _run( self, *args: Any, **kwargs: Any, ) -> Any: """Use the tool. Add run_manager: Optional[CallbackManagerForToolRun] = None to child implementations to enable tracing, """ @abstractmethod async def _arun( self, *args: Any, **kwargs: Any, ) -> Any: """Use the tool asynchronously. Add run_manager: Optional[AsyncCallbackManagerForToolRun] = None to child implementations to enable tracing, """ def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]: # For backwards compatibility, if run_input is a string,
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-5
# For backwards compatibility, if run_input is a string, # pass as a positional argument. if isinstance(tool_input, str): return (tool_input,), {} else: return (), tool_input [docs] def run( self, tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = "green", color: Optional[str] = "green", callbacks: Callbacks = None, **kwargs: Any, ) -> Any: """Run the tool.""" parsed_input = self._parse_input(tool_input) if not self.verbose and verbose is not None: verbose_ = verbose else: verbose_ = self.verbose callback_manager = CallbackManager.configure( callbacks, self.callbacks, verbose=verbose_ ) # TODO: maybe also pass through run_manager is _run supports kwargs new_arg_supported = signature(self._run).parameters.get("run_manager") run_manager = callback_manager.on_tool_start( {"name": self.name, "description": self.description}, tool_input if isinstance(tool_input, str) else str(tool_input), color=start_color, **kwargs, ) try: tool_args, tool_kwargs = self._to_args_and_kwargs(parsed_input) observation = ( self._run(*tool_args, run_manager=run_manager, **tool_kwargs) if new_arg_supported else self._run(*tool_args, **tool_kwargs) ) except ToolException as e: if not self.handle_tool_error: run_manager.on_tool_error(e) raise e elif isinstance(self.handle_tool_error, bool):
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-6
raise e elif isinstance(self.handle_tool_error, bool): if e.args: observation = e.args[0] else: observation = "Tool execution error" elif isinstance(self.handle_tool_error, str): observation = self.handle_tool_error elif callable(self.handle_tool_error): observation = self.handle_tool_error(e) else: raise ValueError( f"Got unexpected type of `handle_tool_error`. Expected bool, str " f"or callable. Received: {self.handle_tool_error}" ) run_manager.on_tool_end( str(observation), color="red", name=self.name, **kwargs ) return observation except (Exception, KeyboardInterrupt) as e: run_manager.on_tool_error(e) raise e else: run_manager.on_tool_end( str(observation), color=color, name=self.name, **kwargs ) return observation [docs] async def arun( self, tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[str] = "green", color: Optional[str] = "green", callbacks: Callbacks = None, **kwargs: Any, ) -> Any: """Run the tool asynchronously.""" parsed_input = self._parse_input(tool_input) if not self.verbose and verbose is not None: verbose_ = verbose else: verbose_ = self.verbose callback_manager = AsyncCallbackManager.configure( callbacks, self.callbacks, verbose=verbose_ ) new_arg_supported = signature(self._arun).parameters.get("run_manager") run_manager = await callback_manager.on_tool_start(
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-7
run_manager = await callback_manager.on_tool_start( {"name": self.name, "description": self.description}, tool_input if isinstance(tool_input, str) else str(tool_input), color=start_color, **kwargs, ) try: # We then call the tool on the tool input to get an observation tool_args, tool_kwargs = self._to_args_and_kwargs(parsed_input) observation = ( await self._arun(*tool_args, run_manager=run_manager, **tool_kwargs) if new_arg_supported else await self._arun(*tool_args, **tool_kwargs) ) except ToolException as e: if not self.handle_tool_error: await run_manager.on_tool_error(e) raise e elif isinstance(self.handle_tool_error, bool): if e.args: observation = e.args[0] else: observation = "Tool execution error" elif isinstance(self.handle_tool_error, str): observation = self.handle_tool_error elif callable(self.handle_tool_error): observation = self.handle_tool_error(e) else: raise ValueError( f"Got unexpected type of `handle_tool_error`. Expected bool, str " f"or callable. Received: {self.handle_tool_error}" ) await run_manager.on_tool_end( str(observation), color="red", name=self.name, **kwargs ) return observation except (Exception, KeyboardInterrupt) as e: await run_manager.on_tool_error(e) raise e else: await run_manager.on_tool_end( str(observation), color=color, name=self.name, **kwargs ) return observation
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-8
) return observation def __call__(self, tool_input: str, callbacks: Callbacks = None) -> str: """Make tool callable.""" return self.run(tool_input, callbacks=callbacks) [docs]class Tool(BaseTool): """Tool that takes in function or coroutine directly.""" description: str = "" func: Callable[..., str] """The function to run when the tool is called.""" coroutine: Optional[Callable[..., Awaitable[str]]] = None """The asynchronous version of the function.""" @property def args(self) -> dict: """The tool's input arguments.""" if self.args_schema is not None: return self.args_schema.schema()["properties"] # For backwards compatibility, if the function signature is ambiguous, # assume it takes a single string input. return {"tool_input": {"type": "string"}} def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]: """Convert tool input to pydantic model.""" args, kwargs = super()._to_args_and_kwargs(tool_input) # For backwards compatibility. The tool must be run with a single input all_args = list(args) + list(kwargs.values()) if len(all_args) != 1: raise ToolException( f"Too many arguments to single-input tool {self.name}." f" Args: {all_args}" ) return tuple(all_args), {} def _run( self, *args: Any, run_manager: Optional[CallbackManagerForToolRun] = None, **kwargs: Any, ) -> Any: """Use the tool."""
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-9
**kwargs: Any, ) -> Any: """Use the tool.""" new_argument_supported = signature(self.func).parameters.get("callbacks") return ( self.func( *args, callbacks=run_manager.get_child() if run_manager else None, **kwargs, ) if new_argument_supported else self.func(*args, **kwargs) ) async def _arun( self, *args: Any, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, **kwargs: Any, ) -> Any: """Use the tool asynchronously.""" if self.coroutine: new_argument_supported = signature(self.coroutine).parameters.get( "callbacks" ) return ( await self.coroutine( *args, callbacks=run_manager.get_child() if run_manager else None, **kwargs, ) if new_argument_supported else await self.coroutine(*args, **kwargs) ) raise NotImplementedError("Tool does not support async") # TODO: this is for backwards compatibility, remove in future def __init__( self, name: str, func: Callable, description: str, **kwargs: Any ) -> None: """Initialize tool.""" super(Tool, self).__init__( name=name, func=func, description=description, **kwargs ) [docs] @classmethod def from_function( cls, func: Callable, name: str, # We keep these required to support backwards compatibility description: str, return_direct: bool = False, args_schema: Optional[Type[BaseModel]] = None,
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-10
args_schema: Optional[Type[BaseModel]] = None, **kwargs: Any, ) -> Tool: """Initialize tool from a function.""" return cls( name=name, func=func, description=description, return_direct=return_direct, args_schema=args_schema, **kwargs, ) [docs]class StructuredTool(BaseTool): """Tool that can operate on any number of inputs.""" description: str = "" args_schema: Type[BaseModel] = Field(..., description="The tool schema.") """The input arguments' schema.""" func: Callable[..., Any] """The function to run when the tool is called.""" coroutine: Optional[Callable[..., Awaitable[Any]]] = None """The asynchronous version of the function.""" @property def args(self) -> dict: """The tool's input arguments.""" return self.args_schema.schema()["properties"] def _run( self, *args: Any, run_manager: Optional[CallbackManagerForToolRun] = None, **kwargs: Any, ) -> Any: """Use the tool.""" new_argument_supported = signature(self.func).parameters.get("callbacks") return ( self.func( *args, callbacks=run_manager.get_child() if run_manager else None, **kwargs, ) if new_argument_supported else self.func(*args, **kwargs) ) async def _arun( self, *args: Any, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, **kwargs: Any, ) -> str:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-11
**kwargs: Any, ) -> str: """Use the tool asynchronously.""" if self.coroutine: new_argument_supported = signature(self.coroutine).parameters.get( "callbacks" ) return ( await self.coroutine( *args, callbacks=run_manager.get_child() if run_manager else None, **kwargs, ) if new_argument_supported else await self.coroutine(*args, **kwargs) ) raise NotImplementedError("Tool does not support async") [docs] @classmethod def from_function( cls, func: Callable, name: Optional[str] = None, description: Optional[str] = None, return_direct: bool = False, args_schema: Optional[Type[BaseModel]] = None, infer_schema: bool = True, **kwargs: Any, ) -> StructuredTool: """Create tool from a given function. A classmethod that helps to create a tool from a function. Args: func: The function from which to create a tool name: The name of the tool. Defaults to the function name description: The description of the tool. Defaults to the function docstring return_direct: Whether to return the result directly or as a callback args_schema: The schema of the tool's input arguments infer_schema: Whether to infer the schema from the function's signature **kwargs: Additional arguments to pass to the tool Returns: The tool Examples: ... code-block:: python def add(a: int, b: int) -> int: \"\"\"Add two numbers\"\"\" return a + b
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-12
\"\"\"Add two numbers\"\"\" return a + b tool = StructuredTool.from_function(add) tool.run(1, 2) # 3 """ name = name or func.__name__ description = description or func.__doc__ assert ( description is not None ), "Function must have a docstring if description not provided." # Description example: # search_api(query: str) - Searches the API for the query. description = f"{name}{signature(func)} - {description.strip()}" _args_schema = args_schema if _args_schema is None and infer_schema: _args_schema = create_schema_from_function(f"{name}Schema", func) return cls( name=name, func=func, args_schema=_args_schema, description=description, return_direct=return_direct, **kwargs, ) [docs]def tool( *args: Union[str, Callable], return_direct: bool = False, args_schema: Optional[Type[BaseModel]] = None, infer_schema: bool = True, ) -> Callable: """Make tools out of functions, can be used with or without arguments. Args: *args: The arguments to the tool. return_direct: Whether to return directly from the tool rather than continuing the agent loop. args_schema: optional argument schema for user to specify infer_schema: Whether to infer the schema of the arguments from the function's signature. This also makes the resultant tool accept a dictionary input to its `run()` function. Requires: - Function must be of type (str) -> str - Function must have a docstring
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-13
- Function must have a docstring Examples: .. code-block:: python @tool def search_api(query: str) -> str: # Searches the API for the query. return @tool("search", return_direct=True) def search_api(query: str) -> str: # Searches the API for the query. return """ def _make_with_name(tool_name: str) -> Callable: def _make_tool(func: Callable) -> BaseTool: if infer_schema or args_schema is not None: return StructuredTool.from_function( func, name=tool_name, return_direct=return_direct, args_schema=args_schema, infer_schema=infer_schema, ) # If someone doesn't want a schema applied, we must treat it as # a simple string->string function assert func.__doc__ is not None, "Function must have a docstring" return Tool( name=tool_name, func=func, description=f"{tool_name} tool", return_direct=return_direct, ) return _make_tool if len(args) == 1 and isinstance(args[0], str): # if the argument is a string, then we use the string as the tool name # Example usage: @tool("search", return_direct=True) return _make_with_name(args[0]) elif len(args) == 1 and callable(args[0]): # if the argument is a function, then we use the function name as the tool name # Example usage: @tool return _make_with_name(args[0].__name__)(args[0]) elif len(args) == 0:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
866f8f636565-14
elif len(args) == 0: # if there are no arguments, then we use the function name as the tool name # Example usage: @tool(return_direct=True) def _partial(func: Callable[[str], str]) -> BaseTool: return _make_with_name(func.__name__)(func) return _partial else: raise ValueError("Too many arguments for tool decorator")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
037bbcb12a8d-0
Source code for langchain.tools.playwright.extract_hyperlinks from __future__ import annotations import json from typing import TYPE_CHECKING, Any, Optional, Type from pydantic import BaseModel, Field, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import aget_current_page, get_current_page if TYPE_CHECKING: pass class ExtractHyperlinksToolInput(BaseModel): """Input for ExtractHyperlinksTool.""" absolute_urls: bool = Field( default=False, description="Return absolute URLs instead of relative URLs", ) [docs]class ExtractHyperlinksTool(BaseBrowserTool): """Extract all hyperlinks on the page.""" name: str = "extract_hyperlinks" description: str = "Extract all hyperlinks on the current webpage" args_schema: Type[BaseModel] = ExtractHyperlinksToolInput @root_validator def check_bs_import(cls, values: dict) -> dict: """Check that the arguments are valid.""" try: from bs4 import BeautifulSoup # noqa: F401 except ImportError: raise ValueError( "The 'beautifulsoup4' package is required to use this tool." " Please install it with 'pip install beautifulsoup4'." ) return values [docs] @staticmethod def scrape_page(page: Any, html_content: str, absolute_urls: bool) -> str: from urllib.parse import urljoin from bs4 import BeautifulSoup # Parse the HTML content with BeautifulSoup soup = BeautifulSoup(html_content, "lxml") # Find all the anchor elements and extract their href attributes
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
037bbcb12a8d-1
# Find all the anchor elements and extract their href attributes anchors = soup.find_all("a") if absolute_urls: base_url = page.url links = [urljoin(base_url, anchor.get("href", "")) for anchor in anchors] else: links = [anchor.get("href", "") for anchor in anchors] # Return the list of links as a JSON string return json.dumps(links) def _run( self, absolute_urls: bool = False, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) html_content = page.content() return self.scrape_page(page, html_content, absolute_urls) async def _arun( self, absolute_urls: bool = False, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) html_content = await page.content() return self.scrape_page(page, html_content, absolute_urls)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
2437374e48f0-0
Source code for langchain.tools.playwright.current_page from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import aget_current_page, get_current_page [docs]class CurrentWebPageTool(BaseBrowserTool): name: str = "current_webpage" description: str = "Returns the URL of the current page" args_schema: Type[BaseModel] = BaseModel def _run( self, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) return str(page.url) async def _arun( self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) return str(page.url)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/current_page.html
7845dd10ab5e-0
Source code for langchain.tools.playwright.extract_text from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import aget_current_page, get_current_page [docs]class ExtractTextTool(BaseBrowserTool): name: str = "extract_text" description: str = "Extract all the text on the current webpage" args_schema: Type[BaseModel] = BaseModel @root_validator def check_acheck_bs_importrgs(cls, values: dict) -> dict: """Check that the arguments are valid.""" try: from bs4 import BeautifulSoup # noqa: F401 except ImportError: raise ValueError( "The 'beautifulsoup4' package is required to use this tool." " Please install it with 'pip install beautifulsoup4'." ) return values def _run(self, run_manager: Optional[CallbackManagerForToolRun] = None) -> str: """Use the tool.""" # Use Beautiful Soup since it's faster than looping through the elements from bs4 import BeautifulSoup if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) html_content = page.content() # Parse the HTML content with BeautifulSoup soup = BeautifulSoup(html_content, "lxml") return " ".join(text for text in soup.stripped_strings) async def _arun( self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
7845dd10ab5e-1
self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") # Use Beautiful Soup since it's faster than looping through the elements from bs4 import BeautifulSoup page = await aget_current_page(self.async_browser) html_content = await page.content() # Parse the HTML content with BeautifulSoup soup = BeautifulSoup(html_content, "lxml") return " ".join(text for text in soup.stripped_strings)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
1236afdaa4f3-0
Source code for langchain.tools.playwright.get_elements from __future__ import annotations import json from typing import TYPE_CHECKING, List, Optional, Sequence, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import aget_current_page, get_current_page if TYPE_CHECKING: from playwright.async_api import Page as AsyncPage from playwright.sync_api import Page as SyncPage class GetElementsToolInput(BaseModel): """Input for GetElementsTool.""" selector: str = Field( ..., description="CSS selector, such as '*', 'div', 'p', 'a', #id, .classname", ) attributes: List[str] = Field( default_factory=lambda: ["innerText"], description="Set of attributes to retrieve for each element", ) async def _aget_elements( page: AsyncPage, selector: str, attributes: Sequence[str] ) -> List[dict]: """Get elements matching the given CSS selector.""" elements = await page.query_selector_all(selector) results = [] for element in elements: result = {} for attribute in attributes: if attribute == "innerText": val: Optional[str] = await element.inner_text() else: val = await element.get_attribute(attribute) if val is not None and val.strip() != "": result[attribute] = val if result: results.append(result) return results def _get_elements( page: SyncPage, selector: str, attributes: Sequence[str] ) -> List[dict]:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
1236afdaa4f3-1
) -> List[dict]: """Get elements matching the given CSS selector.""" elements = page.query_selector_all(selector) results = [] for element in elements: result = {} for attribute in attributes: if attribute == "innerText": val: Optional[str] = element.inner_text() else: val = element.get_attribute(attribute) if val is not None and val.strip() != "": result[attribute] = val if result: results.append(result) return results [docs]class GetElementsTool(BaseBrowserTool): name: str = "get_elements" description: str = ( "Retrieve elements in the current web page matching the given CSS selector" ) args_schema: Type[BaseModel] = GetElementsToolInput def _run( self, selector: str, attributes: Sequence[str] = ["innerText"], run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) # Navigate to the desired webpage before using this tool results = _get_elements(page, selector, attributes) return json.dumps(results, ensure_ascii=False) async def _arun( self, selector: str, attributes: Sequence[str] = ["innerText"], run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
1236afdaa4f3-2
raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) # Navigate to the desired webpage before using this tool results = await _aget_elements(page, selector, attributes) return json.dumps(results, ensure_ascii=False)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
8eb9f5bdb201-0
Source code for langchain.tools.playwright.navigate_back from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import ( aget_current_page, get_current_page, ) [docs]class NavigateBackTool(BaseBrowserTool): """Navigate back to the previous page in the browser history.""" name: str = "previous_webpage" description: str = "Navigate back to the previous page in the browser history" args_schema: Type[BaseModel] = BaseModel def _run(self, run_manager: Optional[CallbackManagerForToolRun] = None) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) response = page.go_back() if response: return ( f"Navigated back to the previous page with URL '{response.url}'." f" Status code {response.status}" ) else: return "Unable to navigate back; no previous page in the history" async def _arun( self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) response = await page.go_back() if response: return (
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
8eb9f5bdb201-1
response = await page.go_back() if response: return ( f"Navigated back to the previous page with URL '{response.url}'." f" Status code {response.status}" ) else: return "Unable to navigate back; no previous page in the history"
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
d6c1d18d5bb5-0
Source code for langchain.tools.playwright.click from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import ( aget_current_page, get_current_page, ) class ClickToolInput(BaseModel): """Input for ClickTool.""" selector: str = Field(..., description="CSS selector for the element to click") [docs]class ClickTool(BaseBrowserTool): name: str = "click_element" description: str = "Click on an element with the given CSS selector" args_schema: Type[BaseModel] = ClickToolInput visible_only: bool = True """Whether to consider only visible elements.""" playwright_strict: bool = False """Whether to employ Playwright's strict mode when clicking on elements.""" playwright_timeout: float = 1_000 """Timeout (in ms) for Playwright to wait for element to be ready.""" def _selector_effective(self, selector: str) -> str: if not self.visible_only: return selector return f"{selector} >> visible=1" def _run( self, selector: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) # Navigate to the desired webpage before using this tool
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
d6c1d18d5bb5-1
# Navigate to the desired webpage before using this tool selector_effective = self._selector_effective(selector=selector) from playwright.sync_api import TimeoutError as PlaywrightTimeoutError try: page.click( selector_effective, strict=self.playwright_strict, timeout=self.playwright_timeout, ) except PlaywrightTimeoutError: return f"Unable to click on element '{selector}'" return f"Clicked element '{selector}'" async def _arun( self, selector: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) # Navigate to the desired webpage before using this tool selector_effective = self._selector_effective(selector=selector) from playwright.async_api import TimeoutError as PlaywrightTimeoutError try: await page.click( selector_effective, strict=self.playwright_strict, timeout=self.playwright_timeout, ) except PlaywrightTimeoutError: return f"Unable to click on element '{selector}'" return f"Clicked element '{selector}'"
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
1757f6752e51-0
Source code for langchain.tools.playwright.navigate from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import ( aget_current_page, get_current_page, ) class NavigateToolInput(BaseModel): """Input for NavigateToolInput.""" url: str = Field(..., description="url to navigate to") [docs]class NavigateTool(BaseBrowserTool): name: str = "navigate_browser" description: str = "Navigate a browser to the specified URL" args_schema: Type[BaseModel] = NavigateToolInput def _run( self, url: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) response = page.goto(url) status = response.status if response else "unknown" return f"Navigating to {url} returned status code {status}" async def _arun( self, url: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) response = await page.goto(url)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
1757f6752e51-1
response = await page.goto(url) status = response.status if response else "unknown" return f"Navigating to {url} returned status code {status}"
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
f68699ebc3dc-0
Source code for langchain.tools.requests.tool # flake8: noqa """Tools for making requests to an API endpoint.""" import json from typing import Any, Dict, Optional from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.requests import TextRequestsWrapper from langchain.tools.base import BaseTool def _parse_input(text: str) -> Dict[str, Any]: """Parse the json string into a dict.""" return json.loads(text) def _clean_url(url: str) -> str: """Strips quotes from the url.""" return url.strip("\"'") [docs]class BaseRequestsTool(BaseModel): """Base class for requests tools.""" requests_wrapper: TextRequestsWrapper [docs]class RequestsGetTool(BaseRequestsTool, BaseTool): """Tool for making a GET request to an API endpoint.""" name = "requests_get" description = "A portal to the internet. Use this when you need to get specific content from a website. Input should be a url (i.e. https://www.google.com). The output will be the text response of the GET request." def _run( self, url: str, run_manager: Optional[CallbackManagerForToolRun] = None ) -> str: """Run the tool.""" return self.requests_wrapper.get(_clean_url(url)) async def _arun( self, url: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" return await self.requests_wrapper.aget(_clean_url(url)) [docs]class RequestsPostTool(BaseRequestsTool, BaseTool):
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
f68699ebc3dc-1
[docs]class RequestsPostTool(BaseRequestsTool, BaseTool): """Tool for making a POST request to an API endpoint.""" name = "requests_post" description = """Use this when you want to POST to a website. Input should be a json string with two keys: "url" and "data". The value of "url" should be a string, and the value of "data" should be a dictionary of key-value pairs you want to POST to the url. Be careful to always use double quotes for strings in the json string The output will be the text response of the POST request. """ def _run( self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None ) -> str: """Run the tool.""" try: data = _parse_input(text) return self.requests_wrapper.post(_clean_url(data["url"]), data["data"]) except Exception as e: return repr(e) async def _arun( self, text: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" try: data = _parse_input(text) return await self.requests_wrapper.apost( _clean_url(data["url"]), data["data"] ) except Exception as e: return repr(e) [docs]class RequestsPatchTool(BaseRequestsTool, BaseTool): """Tool for making a PATCH request to an API endpoint.""" name = "requests_patch" description = """Use this when you want to PATCH to a website. Input should be a json string with two keys: "url" and "data".
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
f68699ebc3dc-2
Input should be a json string with two keys: "url" and "data". The value of "url" should be a string, and the value of "data" should be a dictionary of key-value pairs you want to PATCH to the url. Be careful to always use double quotes for strings in the json string The output will be the text response of the PATCH request. """ def _run( self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None ) -> str: """Run the tool.""" try: data = _parse_input(text) return self.requests_wrapper.patch(_clean_url(data["url"]), data["data"]) except Exception as e: return repr(e) async def _arun( self, text: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" try: data = _parse_input(text) return await self.requests_wrapper.apatch( _clean_url(data["url"]), data["data"] ) except Exception as e: return repr(e) [docs]class RequestsPutTool(BaseRequestsTool, BaseTool): """Tool for making a PUT request to an API endpoint.""" name = "requests_put" description = """Use this when you want to PUT to a website. Input should be a json string with two keys: "url" and "data". The value of "url" should be a string, and the value of "data" should be a dictionary of key-value pairs you want to PUT to the url.
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
f68699ebc3dc-3
key-value pairs you want to PUT to the url. Be careful to always use double quotes for strings in the json string. The output will be the text response of the PUT request. """ def _run( self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None ) -> str: """Run the tool.""" try: data = _parse_input(text) return self.requests_wrapper.put(_clean_url(data["url"]), data["data"]) except Exception as e: return repr(e) async def _arun( self, text: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" try: data = _parse_input(text) return await self.requests_wrapper.aput( _clean_url(data["url"]), data["data"] ) except Exception as e: return repr(e) [docs]class RequestsDeleteTool(BaseRequestsTool, BaseTool): """Tool for making a DELETE request to an API endpoint.""" name = "requests_delete" description = "A portal to the internet. Use this when you need to make a DELETE request to a URL. Input should be a specific url, and the output will be the text response of the DELETE request." def _run( self, url: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Run the tool.""" return self.requests_wrapper.delete(_clean_url(url)) async def _arun( self, url: str,
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
f68699ebc3dc-4
async def _arun( self, url: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" return await self.requests_wrapper.adelete(_clean_url(url))
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
b649b48e8728-0
Source code for langchain.tools.steamship_image_generation.tool """This tool allows agents to generate images using Steamship. Steamship offers access to different third party image generation APIs using a single API key. Today the following models are supported: - Dall-E - Stable Diffusion To use this tool, you must first set as environment variables: STEAMSHIP_API_KEY ``` """ from __future__ import annotations from enum import Enum from typing import TYPE_CHECKING, Dict, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools import BaseTool from langchain.tools.steamship_image_generation.utils import make_image_public from langchain.utils import get_from_dict_or_env if TYPE_CHECKING: pass class ModelName(str, Enum): """Supported Image Models for generation.""" DALL_E = "dall-e" STABLE_DIFFUSION = "stable-diffusion" SUPPORTED_IMAGE_SIZES = { ModelName.DALL_E: ("256x256", "512x512", "1024x1024"), ModelName.STABLE_DIFFUSION: ("512x512", "768x768"), } [docs]class SteamshipImageGenerationTool(BaseTool): try: from steamship import Steamship except ImportError: pass """Tool used to generate images from a text-prompt.""" model_name: ModelName size: Optional[str] = "512x512" steamship: Steamship return_urls: Optional[bool] = False name = "GenerateImage" description = ( "Useful for when you need to generate an image."
https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html
b649b48e8728-1
description = ( "Useful for when you need to generate an image." "Input: A detailed text-2-image prompt describing an image" "Output: the UUID of a generated image" ) @root_validator(pre=True) def validate_size(cls, values: Dict) -> Dict: if "size" in values: size = values["size"] model_name = values["model_name"] if size not in SUPPORTED_IMAGE_SIZES[model_name]: raise RuntimeError(f"size {size} is not supported by {model_name}") return values @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" steamship_api_key = get_from_dict_or_env( values, "steamship_api_key", "STEAMSHIP_API_KEY" ) try: from steamship import Steamship except ImportError: raise ImportError( "steamship is not installed. " "Please install it with `pip install steamship`" ) steamship = Steamship( api_key=steamship_api_key, ) values["steamship"] = steamship if "steamship_api_key" in values: del values["steamship_api_key"] return values def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" image_generator = self.steamship.use_plugin( plugin_handle=self.model_name.value, config={"n": 1, "size": self.size} )
https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html
b649b48e8728-2
) task = image_generator.generate(text=query, append_output_to_file=True) task.wait() blocks = task.output.blocks if len(blocks) > 0: if self.return_urls: return make_image_public(self.steamship, blocks[0]) else: return blocks[0].id raise RuntimeError(f"[{self.name}] Tool unable to generate image!") async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotImplementedError("GenerateImageTool does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html
b47470c9450c-0
Source code for langchain.tools.ddg_search.tool """Tool for the DuckDuckGo search API.""" import warnings from typing import Any, Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper [docs]class DuckDuckGoSearchRun(BaseTool): """Tool that adds the capability to query the DuckDuckGo search API.""" name = "duckduckgo_search" description = ( "A wrapper around DuckDuckGo Search. " "Useful for when you need to answer questions about current events. " "Input should be a search query." ) api_wrapper: DuckDuckGoSearchAPIWrapper = Field( default_factory=DuckDuckGoSearchAPIWrapper ) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return self.api_wrapper.run(query) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotImplementedError("DuckDuckGoSearch does not support async") [docs]class DuckDuckGoSearchResults(BaseTool): """Tool that queries the Duck Duck Go Search API and get back json.""" name = "DuckDuckGo Results JSON" description = ( "A wrapper around Duck Duck Go Search. "
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html
b47470c9450c-1
description = ( "A wrapper around Duck Duck Go Search. " "Useful for when you need to answer questions about current events. " "Input should be a search query. Output is a JSON array of the query results" ) num_results: int = 4 api_wrapper: DuckDuckGoSearchAPIWrapper = Field( default_factory=DuckDuckGoSearchAPIWrapper ) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query, self.num_results)) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotImplementedError("DuckDuckGoSearchResults does not support async") def DuckDuckGoSearchTool(*args: Any, **kwargs: Any) -> DuckDuckGoSearchRun: """ Deprecated. Use DuckDuckGoSearchRun instead. Args: *args: **kwargs: Returns: DuckDuckGoSearchRun """ warnings.warn( "DuckDuckGoSearchTool will be deprecated in the future. " "Please use DuckDuckGoSearchRun instead.", DeprecationWarning, ) return DuckDuckGoSearchRun(*args, **kwargs)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html