"""Test Momento cache functionality.

To run tests, set the environment variable MOMENTO_AUTH_TOKEN to a valid
Momento auth token. This can be obtained by signing up for a free
Momento account at https://gomomento.com/.
"""
from __future__ import annotations

import uuid
from datetime import timedelta
from typing import Iterator

import pytest

import langchain
from langchain.cache import MomentoCache
from langchain.schema import Generation, LLMResult
from tests.unit_tests.llms.fake_llm import FakeLLM


def random_string() -> str:
    return str(uuid.uuid4())


@pytest.fixture(scope="module")
def momento_cache() -> Iterator[MomentoCache]:
    from momento import CacheClient, Configurations, CredentialProvider

    cache_name = f"langchain-test-cache-{random_string()}"
    client = CacheClient(
        Configurations.Laptop.v1(),
        CredentialProvider.from_environment_variable("MOMENTO_AUTH_TOKEN"),
        default_ttl=timedelta(seconds=30),
    )
    try:
        llm_cache = MomentoCache(client, cache_name)
        langchain.llm_cache = llm_cache
        yield llm_cache
    finally:
        client.delete_cache(cache_name)


def test_invalid_ttl() -> None:
    from momento import CacheClient, Configurations, CredentialProvider

    client = CacheClient(
        Configurations.Laptop.v1(),
        CredentialProvider.from_environment_variable("MOMENTO_AUTH_TOKEN"),
        default_ttl=timedelta(seconds=30),
    )
    with pytest.raises(ValueError):
        MomentoCache(client, cache_name=random_string(), ttl=timedelta(seconds=-1))


def test_momento_cache_miss(momento_cache: MomentoCache) -> None:
    llm = FakeLLM()
    stub_llm_output = LLMResult(generations=[[Generation(text="foo")]])
    assert llm.generate([random_string()]) == stub_llm_output


@pytest.mark.parametrize(
    "prompts,  generations",
    [
        # Single prompt, single generation
        ([random_string()], [[random_string()]]),
        # Single prompt, multiple generations
        ([random_string()], [[random_string(), random_string()]]),
        # Single prompt, multiple generations
        ([random_string()], [[random_string(), random_string(), random_string()]]),
        # Multiple prompts, multiple generations
        (
            [random_string(), random_string()],
            [[random_string()], [random_string(), random_string()]],
        ),
    ],
)
def test_momento_cache_hit(
    momento_cache: MomentoCache, prompts: list[str], generations: list[list[str]]
) -> None:
    llm = FakeLLM()
    params = llm.dict()
    params["stop"] = None
    llm_string = str(sorted([(k, v) for k, v in params.items()]))

    llm_generations = [
        [
            Generation(text=generation, generation_info=params)
            for generation in prompt_i_generations
        ]
        for prompt_i_generations in generations
    ]
    for prompt_i, llm_generations_i in zip(prompts, llm_generations):
        momento_cache.update(prompt_i, llm_string, llm_generations_i)

    assert llm.generate(prompts) == LLMResult(
        generations=llm_generations, llm_output={}
    )

langchain.cache.MomentoCache langchain.schema.LLMResult langchain.schema.Generation
[((569, 599), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (583, 599), False, 'import pytest\n'), ((1637, 1646), 'tests.unit_tests.llms.fake_llm.FakeLLM', 'FakeLLM', ([], {}), '()\n', (1644, 1646), False, 'from tests.unit_tests.llms.fake_llm import FakeLLM\n'), ((2507, 2516), 'tests.unit_tests.llms.fake_llm.FakeLLM', 'FakeLLM', ([], {}), '()\n', (2514, 2516), False, 'from tests.unit_tests.llms.fake_llm import FakeLLM\n'), ((552, 564), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (562, 564), False, 'import uuid\n'), ((813, 839), 'momento.Configurations.Laptop.v1', 'Configurations.Laptop.v1', ([], {}), '()\n', (837, 839), False, 'from momento import CacheClient, Configurations, CredentialProvider\n'), ((849, 915), 'momento.CredentialProvider.from_environment_variable', 'CredentialProvider.from_environment_variable', (['"""MOMENTO_AUTH_TOKEN"""'], {}), "('MOMENTO_AUTH_TOKEN')\n", (893, 915), False, 'from momento import CacheClient, Configurations, CredentialProvider\n'), ((995, 1027), 'langchain.cache.MomentoCache', 'MomentoCache', (['client', 'cache_name'], {}), '(client, cache_name)\n', (1007, 1027), False, 'from langchain.cache import MomentoCache\n'), ((1286, 1312), 'momento.Configurations.Laptop.v1', 'Configurations.Laptop.v1', ([], {}), '()\n', (1310, 1312), False, 'from momento import CacheClient, Configurations, CredentialProvider\n'), ((1322, 1388), 'momento.CredentialProvider.from_environment_variable', 'CredentialProvider.from_environment_variable', (['"""MOMENTO_AUTH_TOKEN"""'], {}), "('MOMENTO_AUTH_TOKEN')\n", (1366, 1388), False, 'from momento import CacheClient, Configurations, CredentialProvider\n'), ((1448, 1473), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1461, 1473), False, 'import pytest\n'), ((3024, 3077), 'langchain.schema.LLMResult', 'LLMResult', ([], {'generations': 'llm_generations', 'llm_output': '{}'}), '(generations=llm_generations, llm_output={})\n', (3033, 3077), False, 'from langchain.schema import Generation, LLMResult\n'), ((937, 958), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(30)'}), '(seconds=30)\n', (946, 958), False, 'from datetime import timedelta\n'), ((1410, 1431), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(30)'}), '(seconds=30)\n', (1419, 1431), False, 'from datetime import timedelta\n'), ((2680, 2731), 'langchain.schema.Generation', 'Generation', ([], {'text': 'generation', 'generation_info': 'params'}), '(text=generation, generation_info=params)\n', (2690, 2731), False, 'from langchain.schema import Generation, LLMResult\n'), ((1536, 1557), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(-1)'}), '(seconds=-1)\n', (1545, 1557), False, 'from datetime import timedelta\n'), ((1693, 1715), 'langchain.schema.Generation', 'Generation', ([], {'text': '"""foo"""'}), "(text='foo')\n", (1703, 1715), False, 'from langchain.schema import Generation, LLMResult\n')]