|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1. RunnableLambda是什么?
RunnableLambda类是LangChain内置的,将普通函数等转换为Runnable接口实例,方便自定义函数加入chain。
跳过RunnableLambda类,直接让函数加入链也是可以的。
2. 代码实战
①调用RunnableLambda将函数转换为Runnable接口
- from langchain_core.output_parsers import StrOutputParser
- from langchain_core.prompts import PromptTemplate
- from langchain_community.chat_models.tongyi import ChatTongyi
- model = ChatTongyi(model="qwen3-max")
- str_parser = StrOutputParser()
- first_prompt = PromptTemplate.from_template(
- "我邻居姓:{lastname},刚生了{gender},请帮忙起名字,仅生成一个名字,并告知我名字,不要额外信息。"
- )
- second_prompt = PromptTemplate.from_template(
- "姓名{name},请帮我解析含义。"
- )
- # 函数的入参:AIMessage -> dict ({"name": "xxx"})
- my_func = RunnableLambda(lambda ai_msg: {"name": ai_msg.content})
- chain = first_prompt | model | my_func | second_prompt | model | str_parser
- for chunk in chain.stream({"lastname": "曹", "gender": "女孩"}):
- print(chunk, end="", flush=True)
复制代码 ②直接将函数加入链
- from langchain_core.output_parsers import StrOutputParser
- from langchain_core.prompts import PromptTemplate
- from langchain_community.chat_models.tongyi import ChatTongyi
- model = ChatTongyi(model="qwen3-max")
- str_parser = StrOutputParser()
- first_prompt = PromptTemplate.from_template(
- "我邻居姓:{lastname},刚生了{gender},请帮忙起名字,仅生成一个名字,并告知我名字,不要额外信息。"
- )
- second_prompt = PromptTemplate.from_template(
- "姓名{name},请帮我解析含义。"
- )
- chain = first_prompt | model | (lambda ai_msg: {"name": ai_msg.content}) | second_prompt | model | str_parser
- for chunk in chain.stream({"lastname": "曹", "gender": "女孩"}):
- print(chunk, end="", flush=True)
复制代码
学习视频:【黑马程序员大模型RAG与Agent智能体项目实战教程,基于主流的LangChain技术从大模型提示词到实战项目】 https://www.bilibili.com/video/BV1yjz5BLEoY/?p=36&share_source=copy_web&vd_source=792a2cb63a1882bff4ed856eadc41a71
|
|