LangChain中如何创建一个PromptTemplate

本文介绍了如何在Python中利用Langchain库,如LLMChain和Tongyi模块,结合PromptTemplate创建有趣的笑话,同时设置了环境变量DASHSCOPE_API_KEY来调用服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# !pip install langchain langchainhub dashscope 

from langchain.chains import LLMChain
from langchain_community.llms import Tongyi
from langchain import hub
import os

from langchain.prompts import PromptTemplate

prompt1 = PromptTemplate.from_template(
    "Tell me a {
   {adjective}} joke about {content}."
### 集成文心一言到LangChain 为了在LangChain中集成或使用文心一言,需要注意的是文心一言并不直接支持通过LangChain进行调用,而是依赖于`qianfan`这个特定的Python包来实现API交互[^3]。 #### 安装必要的库 首先需要确保已经安装了`qianfan`库。可以通过pip命令轻松完成这一操作: ```bash pip install qianfan ``` 接着对于LangChain本身的安装也必不可少,这同样可通过pip简单处理: ```bash pip install langchain ``` #### 创建对话链并设置记忆功能 定义一个基于PromptTemplate的对象作为模板,并利用ConversationBufferWindowMemory为会话提供短期记忆能力。不过这里的重点在于替换默认的语言模型接口至文心一言所使用的ChatWenxin类实例化对象。 ```python from langchain import ConversationChain, LLMChain, PromptTemplate from langchain.memory import ConversationBufferWindowMemory from langchain_wenxin import ChatWenxin template = "你是一个AI助手,能够帮助人们解决问题。\n\n历史对话:\n{history}\n\n当前输入:{input}\n你应答:" prompt_template = PromptTemplate(input_variables=["history", "input"], template=template) memory = ConversationBufferWindowMemory(k=2) # 设置窗口大小为最近两次交流记录 conversation_chain = LLMChain(prompt=prompt_template, llm=ChatWenxin(), memory=memory) ``` 上述代码片段展示了如何构建一个带有上下文感知的记忆机制的支持中文自然语言处理的任务流程,其中特别指定了采用来自百度的预训练模型——文心一言来进行实际的回答生成工作[^1]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值