如何将langchain文档添加到LCEL链?

问题描述 投票:0回答:1

我想在langchain中创建一条链。并简短地得到以下错误

TypeError: Expected a Runnable, callable or dict.Instead got an unsupported type: <class 'str'>

您可以在最后找到完整的错误消息。

我想做什么?

首先,我将查询传递给多个检索器,然后使用 RRF 进行重新排名。结果是

result_context
。这是一个元组列表
(<document>,<score>)
。 在下面的代码中,我定义了提示模板并将文档的 page_content 连接到一个字符串。 在链中,我想将我加入的上下文和查询传递给提示。此外,最终提示应传递到生成管道
llm

if self.prompt_template == None:
            template = """Use the following pieces of context to answer the question at the end.
            If you don't know the answer, just say that you don't know, don't try to make up an answer.
            Use three sentences maximum and keep the answer as concise as possible.
            Always say "thanks for asking!" at the end of the answer.

            {context}

            Question: {question}

            Helpful Answer:"""
            self.prompt_template = PromptTemplate.from_template(template)
        
        
prompt = ChatPromptTemplate.from_template(template)
context = "\n".join([doc.page_content for doc, score in result_context])
chain = (
            {"context":context, "question": RunnablePassthrough()}
            |prompt
            |llm
            |StrOutParser()
        )
            
inference = chain.invoke(query)
print(str(inference))

现在我收到以下错误,我不知道如何解决。我希望你能帮我解决这个问题,可以调用链上的查询。

提前致谢。

    169 prompt = ChatPromptTemplate.from_template(template)
    170 context = "\n".join([doc.page_content for doc, score in result_context])
    171 chain = (
--> 172     {"context":context, "question": RunnablePassthrough()}
    173     |prompt
    174     |llm
    175     |StrOutParser()
    176 )
    178 inference = chain.invoke(final_prompt)
    179 print(str(inference))

File /opt/conda/lib/python3.10/site-packages/langchain_core/runnables/base.py:433, in Runnable.__ror__(self, other)
    423 def __ror__(
    424     self,
    425     other: Union[
   (...)
    430     ],
    431 ) -> RunnableSerializable[Other, Output]:
    432     """Compose this runnable with another object to create a RunnableSequence."""
--> 433     return RunnableSequence(coerce_to_runnable(other), self)

File /opt/conda/lib/python3.10/site-packages/langchain_core/runnables/base.py:4373, in coerce_to_runnable(thing)
   4371     return RunnableLambda(cast(Callable[[Input], Output], thing))
   4372 elif isinstance(thing, dict):
-> 4373     return cast(Runnable[Input, Output], RunnableParallel(thing))
   4374 else:
   4375     raise TypeError(
   4376         f"Expected a Runnable, callable or dict."
   4377         f"Instead got an unsupported type: {type(thing)}"
   4378     )

File /opt/conda/lib/python3.10/site-packages/langchain_core/runnables/base.py:2578, in RunnableParallel.__init__(self, _RunnableParallel__steps, **kwargs)
   2575 merged = {**__steps} if __steps is not None else {}
   2576 merged.update(kwargs)
   2577 super().__init__(
-> 2578     steps={key: coerce_to_runnable(r) for key, r in merged.items()}
   2579 )

File /opt/conda/lib/python3.10/site-packages/langchain_core/runnables/base.py:2578, in <dictcomp>(.0)
   2575 merged = {**__steps} if __steps is not None else {}
   2576 merged.update(kwargs)
   2577 super().__init__(
-> 2578     steps={key: coerce_to_runnable(r) for key, r in merged.items()}
   2579 )

File /opt/conda/lib/python3.10/site-packages/langchain_core/runnables/base.py:4375, in coerce_to_runnable(thing)
   4373     return cast(Runnable[Input, Output], RunnableParallel(thing))
   4374 else:
-> 4375     raise TypeError(
   4376         f"Expected a Runnable, callable or dict."
   4377         f"Instead got an unsupported type: {type(thing)}"
   4378     )

TypeError: Expected a Runnable, callable or dict.Instead got an unsupported type: <class 'str'>
python langchain information-retrieval data-retrieval
1个回答
0
投票

引发错误是因为变量

context
是一个字符串,但它必须是
Runnable
类型。您可以通过像这样稍微修改链来确认这一点(此代码将成功运行):

chain = (
    {"context": RunnablePassthrough(), "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)
            
inference = chain.invoke({
    "question": query,
    "context": context,  # pass context as a string here
})

但是,典型的模式是将检索器(代码示例中未显示)传递给

"context"
键。因为您有多个检索器和一个重新排名步骤,所以使用所有这些步骤构建单个链可能会很麻烦。

参考资料:

  1. 通过>检索示例(LangChain)
  2. 传递数据
© www.soinside.com 2019 - 2024. All rights reserved.