|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 糖逗 于 2026-3-7 19:41 编辑
1. Chain的作用是什么?
将组件串联,上一个组件的输出作为下一个组件的输入,实现数据的自动化流转与组件的协同工作
chain= prompt_template | model
核心前提:Runnable子类对象才能入链(以及Callable、Mapping接口子类对象也可加入(后续了解用的不多))
chain变量是RunnableSequence (RunnableSerializable子类)类型
2.代码实战
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
- from langchain_community.chat_models.tongyi import ChatTongyi
- chat_prompt_template = ChatPromptTemplate.from_messages(
- [
- ("system", "你是一个边塞诗人,可以作诗。"),
- MessagesPlaceholder("history"),
- ("human", "请再来一首唐诗"),
- ]
- )
- history_data = [
- ("human", "你来写一个唐诗"),
- ("ai", "床前明月光,疑是地上霜,举头望明月,低头思故乡"),
- ("human", "好诗再来一个"),
- ("ai", "锄禾日当午,汗滴禾下锄,谁知盘中餐,粒粒皆辛苦"),
- ]
- model = ChatTongyi(model="qwen3-max")
- # 组成链,要求每一个组件都是Runnable接口的子类
- chain = chat_prompt_template | model
- # 通过链去调用invoke或stream
- # res = chain.invoke({"history": history_data})
- # print(res.content)
- # 通过stream流式输出
- for chunk in chain.stream({"history": history_data}):
- print(chunk.content, end="", flush=True)
复制代码
学习视频:【黑马程序员大模型RAG与Agent智能体项目实战教程,基于主流的LangChain技术从大模型提示词到实战项目】[url=https://www.bilibili.com/video/B ... 2bff4ed856eadc41a71]https://www.bilibili.com/video/BV1yjz5BLEoY/?p=31&share_source=copy_web&vd_source=792a2cb63a1882bff4ed856eadc41a71[/url]
|
|