欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > LangChain——管道提示词 缓存

LangChain——管道提示词 缓存

2025/5/15 0:38:46 来源:https://blog.csdn.net/cancer_s/article/details/144026804  浏览:    关键词:LangChain——管道提示词 缓存

管道提示词

管道提示词可以将多个提示组合在一起。当我们想要使用部分提示时,这会很有用。这里可以通过PipelinePrompt来完成。
PipelinePrompt由两部分组成:

  • 最终提示:返回的最终提示;
  • 管道提示:元组列表,由字符串名称和提示模板组成。每个提示模板将被格式化,然后作为具有相同名称的变量传递到未来的提示模板;
from langchain.prompts.pipeline import PipelinePromptTemplate
from langchain.prompts.prompt import PromptTemplatefull_template = """{introduction}{example}{start}"""
full_prompt = PromptTemplate.from_template(full_template)	# 简介模板
introduction_template = """你正在冒充{person}。"""
introduction_prompt = PromptTemplate.from_template(introduction_template)# 案例模板
example_template = """
下面是一个交互示例:Q:{example_q}
A:{example_a}"""
example_prompt = PromptTemplate.from_template(example_template)# 开始模板
start_template = """现在正式开始!Q:{input}
A:"""
start_prompt = PromptTemplate.from_template(start_template)# 最终提示词
input_prompts = [("introduction", introduction_prompt),("example", example_prompt),("start", start_prompt),
]
pipeline_prompt = PipelinePromptTemplate(final_prompt=full_prompt, pipeline_prompts=input_prompts
)print(pipeline_prompt.format(person="Elon Musk",example_q="你最喜欢什么车?",example_a="Tesla",input="您最喜欢的社交媒体网站是什么?",)
)

Caching 缓存

LangChain为LLMs提供了可选的缓存层。

  • 如果经常多次请求相同的问题等,可以通过减少对LLM提供程序进行的API调用来节约资金;
  • 它可以通过减少对LLM提供程序进行的API调用次数来加速应用程序;
%%time
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_template("请根据下面的主题写一篇小红书营销的短文: {topic}")
output_parser = StrOutputParser()chain = prompt | chat | output_parserchain.invoke({"topic": "康师傅绿茶"})

输出结果:
CPU times: total: 109 ms
Wall time: 22.6 s

SQLite缓存

# 我们使用SQLite缓存
from langchain.cache import SQLiteCache
# 设置缓存地址
set_llm_cache(SQLiteCache(database_path="./db/langchain.db"))

第一次

%%time
chain.invoke({"topic": "旺仔小馒头"})

结果:
CPU times: total: 15.6 ms
Wall time: 15.8 s

第二次调用输出结果
CPU times: total: 391 ms
Wall time: 417 ms

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词