2023-04-12 21:16:58 +00:00
|
|
|
import os
|
2023-05-11 23:15:23 +00:00
|
|
|
from typing import Any, Callable, Union
|
2023-04-12 21:16:58 +00:00
|
|
|
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
import langchain
|
|
|
|
from langchain.cache import GPTCache
|
2023-04-27 05:03:50 +00:00
|
|
|
from langchain.schema import Generation
|
2023-04-12 21:16:58 +00:00
|
|
|
from tests.unit_tests.llms.fake_llm import FakeLLM
|
|
|
|
|
|
|
|
try:
|
2023-04-27 05:03:50 +00:00
|
|
|
from gptcache import Cache # noqa: F401
|
|
|
|
from gptcache.manager.factory import get_data_manager
|
|
|
|
from gptcache.processor.pre import get_prompt
|
2023-04-12 21:16:58 +00:00
|
|
|
|
|
|
|
gptcache_installed = True
|
|
|
|
except ImportError:
|
|
|
|
gptcache_installed = False
|
|
|
|
|
|
|
|
|
2023-04-27 05:03:50 +00:00
|
|
|
def init_gptcache_map(cache_obj: Cache) -> None:
|
|
|
|
i = getattr(init_gptcache_map, "_i", 0)
|
|
|
|
cache_path = f"data_map_{i}.txt"
|
|
|
|
if os.path.isfile(cache_path):
|
|
|
|
os.remove(cache_path)
|
|
|
|
cache_obj.init(
|
|
|
|
pre_embedding_func=get_prompt,
|
|
|
|
data_manager=get_data_manager(data_path=cache_path),
|
|
|
|
)
|
|
|
|
init_gptcache_map._i = i + 1 # type: ignore
|
2023-04-12 21:16:58 +00:00
|
|
|
|
|
|
|
|
2023-05-11 23:15:23 +00:00
|
|
|
def init_gptcache_map_with_llm(cache_obj: Cache, llm: str) -> None:
|
|
|
|
cache_path = f"data_map_{llm}.txt"
|
|
|
|
if os.path.isfile(cache_path):
|
|
|
|
os.remove(cache_path)
|
|
|
|
cache_obj.init(
|
|
|
|
pre_embedding_func=get_prompt,
|
|
|
|
data_manager=get_data_manager(data_path=cache_path),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2023-04-27 05:03:50 +00:00
|
|
|
@pytest.mark.skipif(not gptcache_installed, reason="gptcache not installed")
|
2023-05-11 23:15:23 +00:00
|
|
|
@pytest.mark.parametrize(
|
|
|
|
"init_func", [None, init_gptcache_map, init_gptcache_map_with_llm]
|
|
|
|
)
|
|
|
|
def test_gptcache_caching(
|
|
|
|
init_func: Union[Callable[[Any, str], None], Callable[[Any], None], None]
|
|
|
|
) -> None:
|
2023-04-27 05:03:50 +00:00
|
|
|
"""Test gptcache default caching behavior."""
|
|
|
|
langchain.llm_cache = GPTCache(init_func)
|
2023-04-12 21:16:58 +00:00
|
|
|
llm = FakeLLM()
|
|
|
|
params = llm.dict()
|
|
|
|
params["stop"] = None
|
|
|
|
llm_string = str(sorted([(k, v) for k, v in params.items()]))
|
|
|
|
langchain.llm_cache.update("foo", llm_string, [Generation(text="fizz")])
|
2023-04-27 05:03:50 +00:00
|
|
|
_ = llm.generate(["foo", "bar", "foo"])
|
|
|
|
cache_output = langchain.llm_cache.lookup("foo", llm_string)
|
|
|
|
assert cache_output == [Generation(text="fizz")]
|
|
|
|
|
|
|
|
langchain.llm_cache.clear()
|
|
|
|
assert langchain.llm_cache.lookup("bar", llm_string) is None
|