# 提示词 template = """Answer the question based only on the following context: {context} Question: {question} """ prompt = ChatPromptTemplate.from_template(template)
chain = ( {"context": retriever, "question": RunnablePassthrough()} | prompt | model | output_parser ) res = chain.invoke("how can langsmith help with testing?") print(res)
# 问题 下面这样可以么? res = chain.invoke({"question": "how can langsmith help with testing?"})
不行,相当于:"question":{"question": "how can langsmith help with testing?"}
defformat_docs_into_text2(docs): doc_size = len(docs) print('收到 {} 个文档'.format(doc_size)) return"\n\n".join(doc.page_content for doc in docs)
生成的提示词不同
直接返回docs 的情况
[HumanMessage(content=”Answer the question based only on the following context:\n [Document(page_content=’LangSmith User Guide | \uf8ffü¶úÔ∏è\uf8ffüõ†Ô …
返回字符串的情况
[HumanMessage(content=’Answer the question based only on the following context:\n LangSmith User Guide | \uf8ffü¶úÔ∏è\uf8ffüõ†Ô∏è LangSmith\n\nLangSmith User Guide | \uf8ffü¶úÔ∏è\uf8ffüõ
from langchain_community.chat_models.baidu_qianfan_endpoint import QianfanChatEndpoint from langchain_community.embeddings import QianfanEmbeddingsEndpoint from langchain_community.vectorstores.chroma import Chroma from langchain_core.messages import HumanMessage from langchain_core.output_parsers import StrOutputParser from langchain_core.prompt_values import ChatPromptValue from langchain_core.prompts import ChatPromptTemplate, PromptTemplate from langchain_core.runnables import RunnablePassthrough, RunnableParallel, RunnableLambda
# 提示词 template = """Answer the question based only on the following context: {context} Question: {question} """ prompt = ChatPromptTemplate.from_template(template)
chain = ( # 原来是这样 {"context": retriever, "question": RunnablePassthrough()} { "context": itemgetter("question") | retriever, "question": itemgetter("question"), } | prompt | model | StrOutputParser() ) # res = chain.invoke("how can langsmith help with testing?") # print(res)
# 并行执行 joke_chain = ChatPromptTemplate.from_template("告诉我一个关于 {topic}的笑话") | model topic_chain = ( ChatPromptTemplate.from_template("告诉我一个关于{topic}的话题") | model )