前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LangChain Tips: llm_cache

LangChain Tips: llm_cache

原创
作者头像
flavorfan
发布2023-08-10 16:57:22
5.3K0
发布2023-08-10 16:57:22
举报
文章被收录于专栏:范传康的专栏范传康的专栏

相信国内绝大多数LLM应用个人开发者最头疼的事情就是ChatGPT的API key的问题,一个是获取问题,一个是费用问题(因为充值不易)。LangChain的llm_cache是缓解(或者部分解决)这个问题一个方案。

1. llm_cache好处 & 有用场景

1) 节约API Call,节约money

2)加速,节约调用时间

3)没有api key的情况下,能够运行起来

典型的场景就是有api-key的同学使用llm cache跑一遍llm的ipynb,这个场景(ipynb+cache.db)分享给没有api-key的同学,也能运行起来,有助于LLM学习。

api key的问题是国内llm开发的大碍,这个方法起码使代码能够跑得起来,调试的起来。

4)严格LLM复现,便于调试

实际应用开发,一个Task/Chain有多次LLM API调用,有bad-case的时候,但是llm交互不能复现。

有了llm-cache就能够稳定的复现,帮助分析Pipeline其中某个环节/块的问题;并且修改其中一个block的prompt以改善鲁棒其输出,渐进式开发复杂的LLM chain。

2. 设置使用llm_cache

工具库:llm.py

代码语言:javascript
复制
from langchain.cache import SQLiteCache

def setup_langchain(llm_cache_path, debug=True):
    langchain.llm_cache = SQLiteCache(database_path=llm_cache_path)
    langchain.debug = debug

使用的场景

代码语言:javascript
复制
from pathlib import Path

CUR_DIR: Path = Path(__file__).parent if "__file__" in locals() else Path.cwd()
cache_db_path: Path = CUR_DIR.parent.parent / "cache/langchain.db"
setup_langchain(cache_db_path)

在第二次运行的情况,可以看到

3. 实现机理

1)langchain内部实现

langchain的llm cache的基类(langchain/cache.py):

代码语言:javascript
复制
class BaseCache(ABC):
    """Base interface for cache."""

    @abstractmethod
    def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:
        """Look up based on prompt and llm_string."""

    @abstractmethod
    def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:
        """Update cache based on prompt and llm_string."""

    @abstractmethod
    def clear(self, **kwargs: Any) -> None:
        """Clear cache that can take additional keyword arguments."""

定义本质是一个lookup表(dict),key是Tuple[prompt, llm_string)],value是llm返回的response (string)。

使用的使用(langchain/llms/base.py) get_prompts方法

代码语言:javascript
复制
def get_prompts(
    params: Dict[str, Any], prompts: List[str]
) -> Tuple[Dict[int, List], str, List[int], List[str]]:
    """Get prompts that are already cached."""
    llm_string = str(sorted([(k, v) for k, v in params.items()]))
    <---省略--->
    for i, prompt in enumerate(prompts):
        if langchain.llm_cache is not None:
            cache_val = langchain.llm_cache.lookup(prompt, llm_string)
            if isinstance(cache_val, list):
                existing_prompts[i] = cache_val
            else:
                missing_prompts.append(prompt)
                missing_prompt_idxs.append(i)
    return existing_prompts, llm_string, missing_prompt_idxs, missing_prompts

为了保证llm_string的唯一性,需要llm的调用params(dict)展开排序成字符串

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. llm_cache好处 & 有用场景
    • 1) 节约API Call,节约money
      • 2)加速,节约调用时间
        • 3)没有api key的情况下,能够运行起来
          • 4)严格LLM复现,便于调试
          • 2. 设置使用llm_cache
          • 3. 实现机理
            • 1)langchain内部实现
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档