如何将Langchain文档添加到LCEL链?
我想在langchain中创建一个链条,但遇到了一个错误,简而言之就是这样。
TypeError: Expected a Runnable, callable or dict.Instead got an unsupported type: <class 'str'>
完整的错误信息在最后可以找到。
我想做什么?
首先,我会把我的查询通过几个检索器,然后用RRF来重新排序。得到的结果是result_context
,它是一个包含元组(<document>,<score>)
的列表。
在下面的代码中,我定义了我的提示模板,并将文档的内容合并成一个字符串。
在这个链条中,我想把合并后的内容和查询一起传递给提示。最后,这个提示应该传递给生成管道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'>
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"
这个键。因为你有几个检索器和一个重新排序的步骤,把所有这些步骤放在一个链中可能会比较麻烦。
参考资料: