记录一次用大模型LLM和向量数据库,搭建垂直领域的知识库问答实践。上文已经介绍了文本如何转换成向量,存储到向量数据库中。本文将介绍大语言模型LLM+提示工程+向量数据库作为背景知识,回答用户的提问。
LangChain 是一个用于开发由语言模型驱动的应用程序的框架。我们相信,和不同的应用程序结合,不仅通过 API 调用语言模型,还应结合:
LangChain 框架的设计目标就是为了实现这些类型的应用程序。它提供了两个主要的价值主张:
环境:python3.9
langchain
unstructured
markdown
qdrant-client
lark
modelscope
torch
transformers
dashscopeembedding = ModelScopeEmbeddings(
model_id="./ai_model/nlp_corom_sentence-embedding_chinese-base-ecom") # 加载模型 不需要外网
def search_from_vector_stores(collection, question):
query_db_docs = []
print(f"""原始的向量数据库查询相关文档""")
client = qdrant_client.QdrantClient(
url=qdrant_url,
port=qdrant_port,
api_key=qdrant_api_key
)
qdrant = Qdrant(
client=client,
collection_name="自己定义的向量数据库中的集合名称",
embeddings=embedding,
)
found_docs = qdrant.similarity_search_with_score(question)
for doc in found_docs:
print(doc)
query_db_docs.append(doc[0].page_content)
return query_db_docs基于上一步检索出的相似文本为背景知识,加上提示工程,向大语言模型提问。
def get_knowledge_based_answer(question, base_docs):
llm = Tongyi(model_name="qwen-7b-chat")
prompt_template = """基于以下已知信息,简洁和专业的来回答用户的问题。如果有相关链接,请同时输出链接。如果无法从中得到答案,请说 "根据已知信息无法回答该问题" 或 "没有提供足够的相关信息",不允许在答案中添加编造成分,答案请使用中文。已知内容:{context},问题:{question}"""
prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
chain = prompt | llm
print("通义千问基于本地知识库的回答:")
answer = chain.invoke({"context": base_docs, "question": question})
print(answer)
return answer原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。