mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-16 14:49:21 +03:00
Optimize the initialization method of GPTCache, so that users can use GPTCache more quickly.
22 KiB
22 KiB
In [1]:
from langchain.llms import OpenAIIn [2]:
import langchain
from langchain.cache import InMemoryCache
langchain.llm_cache = InMemoryCache()In [5]:
# To make the caching really obvious, lets use a slower model.
llm = OpenAI(model_name="text-davinci-002", n=2, best_of=2)In [6]:
%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")Out [6]:
CPU times: user 26.1 ms, sys: 21.5 ms, total: 47.6 ms Wall time: 1.68 s
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'
In [7]:
%%time
# The second time it is, so it goes faster
llm("Tell me a joke")Out [7]:
CPU times: user 238 µs, sys: 143 µs, total: 381 µs Wall time: 1.76 ms
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'
In [9]:
!rm .langchain.dbIn [10]:
# We can do the same thing with a SQLite cache
from langchain.cache import SQLiteCache
langchain.llm_cache = SQLiteCache(database_path=".langchain.db")In [11]:
%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")Out [11]:
CPU times: user 17 ms, sys: 9.76 ms, total: 26.7 ms Wall time: 825 ms
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'
In [12]:
%%time
# The second time it is, so it goes faster
llm("Tell me a joke")Out [12]:
CPU times: user 2.46 ms, sys: 1.23 ms, total: 3.7 ms Wall time: 2.67 ms
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'
In [8]:
# We can do the same thing with a Redis cache
# (make sure your local Redis instance is running first before running this example)
from redis import Redis
from langchain.cache import RedisCache
langchain.llm_cache = RedisCache(redis_=Redis())In [9]:
%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")Out [9]:
CPU times: user 6.88 ms, sys: 8.75 ms, total: 15.6 ms Wall time: 1.04 s
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side!'
In [14]:
%%time
# The second time it is, so it goes faster
llm("Tell me a joke")Out [14]:
CPU times: user 1.59 ms, sys: 610 µs, total: 2.2 ms Wall time: 5.58 ms
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side!'
In [15]:
from langchain.embeddings import OpenAIEmbeddings
from langchain.cache import RedisSemanticCache
langchain.llm_cache = RedisSemanticCache(
redis_url="redis://localhost:6379",
embedding=OpenAIEmbeddings()
)In [16]:
%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")Out [16]:
CPU times: user 351 ms, sys: 156 ms, total: 507 ms Wall time: 3.37 s
"\n\nWhy don't scientists trust atoms?\nBecause they make up everything."
In [27]:
%%time
# The second time, while not a direct hit, the question is semantically similar to the original question,
# so it uses the cached result!
llm("Tell me one joke")Out [27]:
CPU times: user 6.25 ms, sys: 2.72 ms, total: 8.97 ms Wall time: 262 ms
"\n\nWhy don't scientists trust atoms?\nBecause they make up everything."
In [6]:
from gptcache import Cache
from gptcache.manager.factory import manager_factory
from gptcache.processor.pre import get_prompt
from langchain.cache import GPTCache
# Avoid multiple caches using the same file, causing different llm model caches to affect each other
def init_gptcache(cache_obj: Cache, llm str):
cache_obj.init(
pre_embedding_func=get_prompt,
data_manager=manager_factory(manager="map", data_dir=f"map_cache_{llm}"),
)
langchain.llm_cache = GPTCache(init_gptcache)In [7]:
%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")Out [7]:
CPU times: user 8.6 ms, sys: 3.82 ms, total: 12.4 ms Wall time: 881 ms
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'
In [8]:
%%time
# The second time it is, so it goes faster
llm("Tell me a joke")Out [8]:
CPU times: user 286 µs, sys: 21 µs, total: 307 µs Wall time: 316 µs
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'
In [9]:
from gptcache import Cache
from gptcache.adapter.api import init_similar_cache
from langchain.cache import GPTCache
# Avoid multiple caches using the same file, causing different llm model caches to affect each other
def init_gptcache(cache_obj: Cache, llm str):
init_similar_cache(cache_obj=cache_obj, data_dir=f"similar_cache_{llm}")
langchain.llm_cache = GPTCache(init_gptcache)In [10]:
%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")Out [10]:
CPU times: user 1.01 s, sys: 153 ms, total: 1.16 s Wall time: 2.49 s
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'
In [11]:
%%time
# This is an exact match, so it finds it in the cache
llm("Tell me a joke")Out [11]:
CPU times: user 745 ms, sys: 13.2 ms, total: 758 ms Wall time: 136 ms
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'
In [12]:
%%time
# This is not an exact match, but semantically within distance so it hits!
llm("Tell me joke")Out [12]:
CPU times: user 737 ms, sys: 7.79 ms, total: 745 ms Wall time: 135 ms
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'
In [ ]:
# You can use SQLAlchemyCache to cache with any SQL database supported by SQLAlchemy.
# from langchain.cache import SQLAlchemyCache
# from sqlalchemy import create_engine
# engine = create_engine("postgresql://postgres:postgres@localhost:5432/postgres")
# langchain.llm_cache = SQLAlchemyCache(engine)In [ ]:
# You can define your own declarative SQLAlchemyCache child class to customize the schema used for caching. For example, to support high-speed fulltext prompt indexing with Postgres, use:
from sqlalchemy import Column, Integer, String, Computed, Index, Sequence
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_utils import TSVectorType
from langchain.cache import SQLAlchemyCache
Base = declarative_base()
class FulltextLLMCache(Base): # type: ignore
"""Postgres table for fulltext-indexed LLM Cache"""
__tablename__ = "llm_cache_fulltext"
id = Column(Integer, Sequence('cache_id'), primary_key=True)
prompt = Column(String, nullable=False)
llm = Column(String, nullable=False)
idx = Column(Integer)
response = Column(String)
prompt_tsv = Column(TSVectorType(), Computed("to_tsvector('english', llm || ' ' || prompt)", persisted=True))
__table_args__ = (
Index("idx_fulltext_prompt_tsv", prompt_tsv, postgresql_using="gin"),
)
engine = create_engine("postgresql://postgres:postgres@localhost:5432/postgres")
langchain.llm_cache = SQLAlchemyCache(engine, FulltextLLMCache)In [13]:
llm = OpenAI(model_name="text-davinci-002", n=2, best_of=2, cache=False)In [14]:
%%time
llm("Tell me a joke")Out [14]:
CPU times: user 5.8 ms, sys: 2.71 ms, total: 8.51 ms Wall time: 745 ms
'\n\nWhy did the chicken cross the road?\n\nTo get to the other side!'
In [15]:
%%time
llm("Tell me a joke")Out [15]:
CPU times: user 4.91 ms, sys: 2.64 ms, total: 7.55 ms Wall time: 623 ms
'\n\nTwo guys stole a calendar. They got six months each.'
In [16]:
llm = OpenAI(model_name="text-davinci-002")
no_cache_llm = OpenAI(model_name="text-davinci-002", cache=False)In [17]:
from langchain.text_splitter import CharacterTextSplitter
from langchain.chains.mapreduce import MapReduceChain
text_splitter = CharacterTextSplitter()In [18]:
with open('../../../state_of_the_union.txt') as f:
state_of_the_union = f.read()
texts = text_splitter.split_text(state_of_the_union)In [19]:
from langchain.docstore.document import Document
docs = [Document(page_content=t) for t in texts[:3]]
from langchain.chains.summarize import load_summarize_chainIn [20]:
chain = load_summarize_chain(llm, chain_type="map_reduce", reduce_llm=no_cache_llm)In [21]:
%%time
chain.run(docs)Out [21]:
CPU times: user 452 ms, sys: 60.3 ms, total: 512 ms Wall time: 5.09 s
'\n\nPresident Biden is discussing the American Rescue Plan and the Bipartisan Infrastructure Law, which will create jobs and help Americans. He also talks about his vision for America, which includes investing in education and infrastructure. In response to Russian aggression in Ukraine, the United States is joining with European allies to impose sanctions and isolate Russia. American forces are being mobilized to protect NATO countries in the event that Putin decides to keep moving west. The Ukrainians are bravely fighting back, but the next few weeks will be hard for them. Putin will pay a high price for his actions in the long run. Americans should not be alarmed, as the United States is taking action to protect its interests and allies.'
In [22]:
%%time
chain.run(docs)Out [22]:
CPU times: user 11.5 ms, sys: 4.33 ms, total: 15.8 ms Wall time: 1.04 s
'\n\nPresident Biden is discussing the American Rescue Plan and the Bipartisan Infrastructure Law, which will create jobs and help Americans. He also talks about his vision for America, which includes investing in education and infrastructure.'
In [ ]:
!rm .langchain.db sqlite.db