Add read only shared memory (#1491)

Provide shared memory capability for the Agent.
Inspired by #1293 .

## Problem

If both Agent and Tools (i.e., LLMChain) use the same memory, both of
them will save the context. It can be annoying in some cases.


## Solution

Create a memory wrapper that ignores the save and clear, thereby
preventing updates from Agent or Tools.
This commit is contained in:
yakigac
2023-03-13 01:34:36 +09:00
committed by GitHub
parent 9707eda83c
commit acd86d33bc
5 changed files with 609 additions and 3 deletions

View File

@@ -34,7 +34,7 @@ def test_conversation_chain_works() -> None:
def test_conversation_chain_errors_bad_prompt() -> None:
"""Test that conversation chain works in basic setting."""
"""Test that conversation chain raise error with bad prompt."""
llm = FakeLLM()
prompt = PromptTemplate(input_variables=[], template="nothing here")
with pytest.raises(ValueError):
@@ -42,7 +42,7 @@ def test_conversation_chain_errors_bad_prompt() -> None:
def test_conversation_chain_errors_bad_variable() -> None:
"""Test that conversation chain works in basic setting."""
"""Test that conversation chain raise error with bad variable."""
llm = FakeLLM()
prompt = PromptTemplate(input_variables=["foo"], template="{foo}")
memory = ConversationBufferMemory(memory_key="foo")

View File

@@ -1,4 +1,13 @@
from langchain.memory.simple import SimpleMemory
import pytest
from langchain.chains.conversation.memory import (
ConversationBufferMemory,
ConversationBufferWindowMemory,
ConversationSummaryMemory,
)
from langchain.memory import ReadOnlySharedMemory, SimpleMemory
from langchain.schema import BaseMemory
from tests.unit_tests.llms.fake_llm import FakeLLM
def test_simple_memory() -> None:
@@ -9,3 +18,20 @@ def test_simple_memory() -> None:
assert output == {"baz": "foo"}
assert ["baz"] == memory.memory_variables
@pytest.mark.parametrize(
"memory",
[
ConversationBufferMemory(memory_key="baz"),
ConversationSummaryMemory(llm=FakeLLM(), memory_key="baz"),
ConversationBufferWindowMemory(memory_key="baz"),
],
)
def test_readonly_memory(memory: BaseMemory) -> None:
read_only_memory = ReadOnlySharedMemory(memory=memory)
memory.save_context({"input": "bar"}, {"output": "foo"})
assert read_only_memory.load_memory_variables({}) == memory.load_memory_variables(
{}
)