LangChain表达式(LCEL)实操案例1

案例1:写一篇短文,然后对这篇短文进行打分

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnableWithMessageHistory, RunnableLambda
from langchain_openai import ChatOpenAI

llm_zhipu = ChatOpenAI(
    temperature=0.9,
    model='glm-4-air-0111',
    api_key='****',
    base_url='https://open.bigmodel.cn/api/paas/v4/'
)

parser = StrOutputParser()

prompt1 = ChatPromptTemplate.from_template('给我写一篇关于{key_word}的{type},字数不超过{count}。')
prompt2 = ChatPromptTemplate.from_template('请简单评价一下这篇短文,如果总分是10分,请给这篇短文打分:{text_context}。')

chain1 = prompt1 | llm_zhipu | StrOutputParser()
#这样组装,不会输出chain1的内容
# chain2 = {'text_context':chain1} | prompt2 | llm_zhipu | StrOutputParser()


def print_chain1(input):
    print(input)
    print('*'*30)
    return {'text_context':input}
chain2 = chain1 | RunnableLambda(print_chain1) | prompt2 | llm_zhipu | parser


print(chain2.invoke({'key_word': '请写一篇关于春天的文章', 'type': '散文', 'count': 500}))

输出:

案例2:根据用户输入的点餐偏好,推荐2-3家餐厅,并给出推荐理由

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnableWithMessageHistory, RunnableLambda
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    temperature=1,
    model='deepseek-r1',
    api_key='****',
    base_url='https://dashscope.aliyuncs.com/compatible-mode/v1'
)

parser = StrOutputParser()
user_preperences_prompt = ChatPromptTemplate.from_template('用户输入了一些餐厅偏好:\n{user_input}\n,请将用户的偏好总结为清晰的需求:')

recommend_preperences_prompt = ChatPromptTemplate.from_template('基于用户的需求:\n{recommend_input}\n,请推荐3家适合的餐厅,并说明推荐的理由:')

summarize_preperences_prompt = ChatPromptTemplate.from_template('以下是餐厅推荐和推荐的理由:\n{summarize_input}\n,请总结成2-3句话,供用户参考:')

chain = user_preperences_prompt | llm | recommend_preperences_prompt | llm | summarize_preperences_prompt | llm | parser
print(chain.invoke({'user_input': '我喜欢吃辣,环境要安静点的餐厅,价格要实惠,又好吃的菜'}))

输出:

案例3:用户会问到各个领域的问题,根据不同的领域定义不同的提示词模板,动态的选择合适的任务模板去完成

from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnableWithMessageHistory, RunnableLambda, RouterRunnable, RunnableSequence
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    temperature=1,
    model='deepseek-r1',
    api_key='*****',
    base_url='https://dashscope.aliyuncs.com/compatible-mode/v1'
)

#用户会问到各个领域的问题,根据不同的领域定义不同的提示词模板,动态的选择合适的任务模板去完成
parser = StrOutputParser()

math_prompt = ChatPromptTemplate.from_template('你是一位数学家,擅长分步骤解决各种数学问题,以下是问题的内容:{input}')
physics_prompt = ChatPromptTemplate.from_template('你是一位物理教授,擅长用通俗易懂的语言回答各种物理问题,以下是问题的内容:{input}')
history_prompt = ChatPromptTemplate.from_template('你是一位历史研究学家,对历史事件和背景很精通,以下是问题的内容:{input}')
computer_prompt = ChatPromptTemplate.from_template('你是一位非常自身的计算机科学家,擅长算法,大数据,编程问题,以下是问题的内容:{input}')
default_prompt = ChatPromptTemplate.from_template('输入内容无法归类,请直接回答:{input}')

default_chain = default_prompt | llm
computer_chain = computer_prompt | llm
history_chain = history_prompt | llm
physics_chain = physics_prompt | llm
math_chain = math_prompt | llm

def route(input):
    """
    根据大模型第一次处理的值输出来,动态判断各种领域的任务
    :param input:
    :return:
    """
    if '物理' in input['type']:
        print('1号路由')
        return {'key':'physics','input':input['input']}
    elif '数学' in input['type']:
        print('2号路由')
        return {'key':'math','input':input['input']}
    elif '历史' in input['type']:
        print('3号路由')
        return {'key':'history','input':input['input']}
    elif '计算机' in input['type']:
        print('4号路由')
        return {'key':'computer','input':input['input']}
    else :
        print('5号路由')
        return {'key':'default','input':input['input']}

#创建一个路由的节点
route_runnable = RunnableLambda(route)
router = RouterRunnable(runnables={
    'physics':physics_chain,
    'math':math_chain,
    'history': history_chain,
    'computer': computer_chain,
    'default': default_chain
})

#第一个提示词模板:
first_prompt = ChatPromptTemplate.from_template(
    '不要回答下面用户的问题,只要根据用主呢的输入来判断分类,一共有【物理、历顺、计算机、数学、其他】5种类别\n\n\
    用户的输入:{input}\n\n\
    最后的输出包含分类的类别和用户输入的内容,输出的格式为json,其中类别的key为type,用户输入内容的key为input'
)

chain1 = first_prompt | llm | JsonOutputParser()
chain2 = RunnableSequence(chain1,route_runnable,router) # chain1 | route_runnable | router

inputs = [
    {'input':'什么是黑体辐射?'},
    {'input':'1+1真的等于2吗?'},
    {'input':'介绍一下第一次世界大战的背景?'},
    {'input':'如何快速实现冒泡算法?'}
]

for inp in inputs:
    result = chain2.invoke(inp)
    print(f'问题:{inp}\n 回答:{result.content}\n')


输出:

### LangChain LCEL 实现多链顺序调用 LangChain 提供了一种灵活的方式来组合多个链条(Chains),并通过其表达语言(LCEL)实现复杂的逻辑操作。以下是关于如何通过 LangChain 的 `SimpleSequentialChain` 和其他组件来实现多链顺序调用的具体方法。 #### 使用 SimpleSequentialChain 组合两条 Chain 可以通过 `SimpleSequentialChain` 将多个链条按顺序连接起来,从而形成一个多阶段的工作流程。以下是一个具体的代码示例: ```python from langchain.chains import SimpleSequentialChain, LLMChain from langchain.prompts import PromptTemplate from langchain.llms import OpenAI # 定义第一个 Chain (Synopsis Chain) synopsis_template = """You are a helpful assistant that generates movie synopses. Title: {title} Genre: {genre} Write a brief synopsis for this movie:""" synopsis_prompt = PromptTemplate(input_variables=["title", "genre"], template=synopsis_template) llm = OpenAI(temperature=0.7) synopsis_chain = LLMChain(llm=llm, prompt=synopsis_prompt) # 定义第二个 Chain (Review Chain) review_template = """You are a helpful assistant that writes reviews about movies. Movie Synopsis: {movie_synopsis} Write a short review of this movie.""" review_prompt = PromptTemplate(input_variables=["movie_synopsis"], template=review_template) review_chain = LLMChain(llm=llm, prompt=review_prompt) # 创建 Sequential Chain 来串联这两个 Chains overall_chain = SimpleSequentialChain(chains=[synopsis_chain, review_chain], verbose=True) # 执行整体 Chain result = overall_chain.run({"title": "The Matrix", "genre": "Science Fiction"}) print(result) ``` 上述代码展示了如何使用 `SimpleSequentialChain` 将两个链条按顺序执行[^1]。首先生成电影简介 (`synopsis_chain`),然后基于该简介撰写评论 (`review_chain`)。 --- #### 利用 Runnable 协议扩展功能 除了 `SimpleSequentialChain`,还可以利用 LangChain 中的 `Runnable` 协议来自定义更复杂的行为。例如,如果需要支持批量处理或流式传输数据,则可以借助 `Runnable` 接口中的 `stream` 或 `batch` 方法[^3]。下面展示一个简单的例子: ```python from langchain.schema.runnable import RunnableLambda # 自定义函数作为 Chain 的一部分 def process_input(text): return f"Processed Input: {text}" custom_chain = RunnableLambda(process_input) # 结合之前的 Chains 构建新的 Sequence complex_chain = synopsis_chain | custom_chain | review_chain # 调用 Complex Chain 并查看结果 output = complex_chain.invoke({"title": "Inception", "genre": "Thriller"}) print(output) ``` 在这个例子中,我们引入了 `RunnableLambda` 来封装自定义函数,并将其与其他链条结合起来,形成了一个新的工作流。 --- #### 声明式的 LangChain 表达语言(LCEL) 对于更加高级的需求,可以直接采用 LangChain 表达语言(LCEL)。它允许开发者以声明的方式描述整个流水线结构,而无需显式编写 Python 代码。这种模式非常适合大规模部署以及动态调整配置场景下的应用开发[^2]。 虽然官方文档尚未提供完整的 LCEL 示例脚本,但可以根据现有 API 文档推测其实现形式如下所示: ```yaml pipeline: steps: - name: generate_synopsis type: llm_chain config: prompt: | You are an AI writer who creates engaging summaries... input_vars: title: string genre: string - name: write_review type: llm_chain depends_on: [generate_synopsis] config: prompt: | Based on the provided summary, craft a compelling critique... input_vars: movie_synopsis: string ``` 此 YAML 文件定义了一个两步管道:第一步生成摘要;第二步依据前一步的结果撰写影评。实际运行时会由框架解析这些指令并完成相应任务。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值