【LangChain】不同的调用方式(Different call methods)

28 篇文章 12 订阅

LangChain学习文档

Chains(链)

【LangChain】不同的调用方式(Different call methods)

概述

本笔记:讲述Chain的不同调用方式。

所有从 Chain 继承的类中都提供了几种运行链逻辑的方法。最直接的方法是使用 __call__
说明:__call__这个是python版中的方法已经实现了。

内容

chat = ChatOpenAI(temperature=0)
prompt_template = "Tell me a {adjective} joke"
llm_chain = LLMChain(llm=chat, prompt=PromptTemplate.from_template(prompt_template))

llm_chain(inputs={"adjective": "corny"})

结果:

    {'adjective': 'corny',
     'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}

默认情况下,__call__返回的是键值对:输入和输出。我们可以通过将return_only_outputs设置为True:仅返回输出键值对。

只有一个输出key的情况

如果我们想Chain只输出一个key(即:output_keys中只有一个元素),则可以使用run方法。
请注意:run方法输出一个字符串而不是键值对(或者叫:字典)。

# llm_chain only has one output key, so we can use run
# llm_chain 输出只有一个key的情况下,我们可以使用run方法。
llm_chain.output_keys
# 结果
    ['text']

则,使用run方法:

llm_chain.run({"adjective": "corny"})
# 结果
'Why did the tomato turn red? Because it saw the salad dressing!'

只有一个输入key的情况

在只有一个输入key的情况下,可以直接输入字符串,无需指定输入映射:

# These two are equivalent 这两个是等价的
llm_chain.run({"adjective": "corny"})
llm_chain.run("corny")

# These two are also equivalent 这两个也是等价的
llm_chain("corny")
llm_chain({"adjective": "corny"})

结果:

    {'adjective': 'corny',
     'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}

我们可以通过其run方法轻松地将Chain对象作为Tool集成Agent中。请参阅此处的示例。

这里给个理解代码:

tools.append(
    Tool.from_function(
        func=llm_math_chain.run,
        name="Calculator",
        description="useful for when you need to answer questions about math",
        args_schema=CalculatorInput
        # coroutine= ... <- you can specify an async method if desired as well
    )
)
# Construct the agent. We will use the default agent type here.
# See documentation for a full list of options.
# 集成到了agent中
agent = initialize_agent(
    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)
agent.run(
    "Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"
)

总结

要调用Chain的方法。

  1. 先构造llm_chain
llm_chain = LLMChain(llm=chat, prompt=PromptTemplate.from_template(prompt_template))
  1. 执行llm_chain(xxx),即可。默认情况下,输入和输出都会打印出来
llm_chain(inputs={"adjective": "corny"})
# 结果
    {'adjective': 'corny',
     'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}
  1. 单个输出就使用run方法。
  2. 单个输入,可以不用写key:llm_chain("corny")
  3. 单个输入和输出的简写:llm_chain.run("corny")

参考地址:

Different call methods

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山鬼谣me

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值