GPTCache icon indicating copy to clipboard operation
GPTCache copied to clipboard

[Bug]: Incompatibility of GPTCache and Langchain framework

Open dequeueing opened this issue 1 year ago • 0 comments

Current Behavior

Overview

The GPTCache default returned result is incompatible with the langchain framework. Specifically, Langchain expects str while the returned type of GPTCache adapt() is list, leading to runtime error.

Detail

The program to run is at the end. The progran will result in error. GPTCache returns a list while Langchain expects a str.

Traceback (most recent call last):
  File "/home/52748a8b-5b19-4c4f-bda3-2c6792d8cef8/GPTCache/langchain_cache.py", line 98, in <module>
    answer = cached_llm.invoke("What is the longest river in the world?", cache_obj=the_cache)
  File "/home/taojie_wang/miniconda3/envs/gptcache/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 387, in invoke
    self.generate_prompt(
  File "/home/taojie_wang/miniconda3/envs/gptcache/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 760, in generate_prompt
    return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs)
  File "/home/52748a8b-5b19-4c4f-bda3-2c6792d8cef8/GPTCache/gptcache/adapter/langchain_models.py", line 100, in generate
    return super().generate(prompts, stop=stop, callbacks=callbacks)
  File "/home/taojie_wang/miniconda3/envs/gptcache/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 963, in generate
    output = self._generate_helper(
  File "/home/taojie_wang/miniconda3/envs/gptcache/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 784, in _generate_helper
    self._generate(
  File "/home/taojie_wang/miniconda3/envs/gptcache/lib/python3.10/site-packages/langchain_core/language_models/llms.py", line 1527, in _generate
    generations.append([Generation(text=text)])
  File "/home/taojie_wang/miniconda3/envs/gptcache/lib/python3.10/site-packages/langchain_core/load/serializable.py", line 125, in __init__
    super().__init__(*args, **kwargs)
  File "/home/taojie_wang/miniconda3/envs/gptcache/lib/python3.10/site-packages/pydantic/main.py", line 214, in __init__
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
pydantic_core._pydantic_core.ValidationError: 1 validation error for Generation
text
  Input should be a valid string [type=string_type, input_value=['  The longest river in ... the Atlantic Ocean.\n'], input_type=list]
    For further information visit https://errors.pydantic.dev/2.10/v/string_type

Suggested correction

The error can be addressed by extrcting str from the list.

# gptcache/adapter/langchain_models.py
def _cache_data_convert(cache_data):
    if isinstance(cache_data, list) and len(cache_data) == 1:
        cache_data = cache_data[0]
    return cache_data

However, this is just a workaround. We can discuss some better approach to this problem.

Appendix: program to run

import time
import torch
import shutil

from langchain_huggingface import HuggingFacePipeline
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, BitsAndBytesConfig

from gptcache.processor.post import temperature_softmax
from gptcache.adapter.langchain_models import LangChainLLMs
from gptcache.adapter.api import init_similar_cache
from gptcache.core import Cache, Config
from gptcache.processor.pre import get_prompt
from gptcache.processor.post import nop


shutil.rmtree('./attack')
model_path = "meta-llama/Llama-2-7b-chat-hf"

# Load the tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    device_map="cuda:0",
    quantization_config = BitsAndBytesConfig(load_in_4bit=True),
    trust_remote_code=True
)

# Create a Hugging Face pipeline for text generation
pipe = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
    max_new_tokens=200,
    do_sample=True,
    temperature=0.6,
    top_p=0.9,
    return_full_text=False  # Only return the generated text, not the input
)

messages = [
    {"role": "user", "content": "Tell me what is the longest river in the world?"},
]
tokenize_chat_template = False
prompt_temp = tokenizer.apply_chat_template(messages, tokenize=tokenize_chat_template, add_generation_prompt=True)
prompt_temp = torch.tensor(prompt_temp).unsqueeze(0).to(model.device) if tokenize_chat_template else prompt_temp


llm = HuggingFacePipeline(pipeline=pipe)
cached_llm = LangChainLLMs(llm=llm)

the_cache = Cache()
init_similar_cache(
    data_dir="attack" ,cache_obj=the_cache, post_func=nop, config=Config(similarity_threshold=0)
)

answer = cached_llm.invoke(prompt_temp, cache_obj=the_cache)
print("------------------the initial answer----------------")
print(answer)
print("------------------------------------------------\n")


for _ in range(3):
    start = time.time()
    answer = cached_llm.invoke("What is the longest river in the world?", cache_obj=the_cache)
    print("Time elapsed:", round(time.time() - start, 3))
    print("Answer:", answer)
    print('\n-----------------------------------\n')    

Expected Behavior

No response

Steps To Reproduce


Environment

gptcache                 0.1.44
langchain                0.3.19
langchain-community      0.3.18
langchain-core           0.3.37
langchain-huggingface    0.1.2
langchain-mistralai      0.2.6
langchain-text-splitters 0.3.6

Anything else?

No response

dequeueing avatar Feb 25 '25 12:02 dequeueing