相信国内绝大多数LLM应用个人开发者最头疼的事情就是ChatGPT的API key的问题,一个是获取问题,一个是费用问题(因为充值不易)。LangChain的llm_cache是缓解(或者部分解决)这个问题一个方案。
典型的场景就是有api-key的同学使用llm cache跑一遍llm的ipynb,这个场景(ipynb+cache.db)分享给没有api-key的同学,也能运行起来,有助于LLM学习。
api key的问题是国内llm开发的大碍,这个方法起码使代码能够跑得起来,调试的起来。
实际应用开发,一个Task/Chain有多次LLM API调用,有bad-case的时候,但是llm交互不能复现。
有了llm-cache就能够稳定的复现,帮助分析Pipeline其中某个环节/块的问题;并且修改其中一个block的prompt以改善鲁棒其输出,渐进式开发复杂的LLM chain。
工具库:llm.py
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
使用的场景
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)
在第二次运行的情况,可以看到
langchain的llm cache的基类(langchain/cache.py):
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方法
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 删除。