首页 > 其他分享 >本地知识库回答问题

本地知识库回答问题

时间:2024-04-08 16:12:37浏览次数:13  
标签:self 知识库 回答 langchain 本地 kwargs import model history

import json
from langchain.llms.base import LLM
from transformers import AutoTokenizer, AutoModel, AutoConfig
from typing import List, Optional

class ChatGLM4(LLM):
    max_token: int = 8192
    do_sample: bool = True
    temperature: float = 0.8
    modelPath = "/home/cmcc/server/model/chatglm3-6b"
    top_p = 0.8
    tokenizer: object = AutoTokenizer.from_pretrained(modelPath, trust_remote_code=True)
    model: object = None
    history: List = []
    def __init__(self):
        super().__init__()
        print("--------------------------------")
        self.model = AutoModel.from_pretrained(self.modelPath, trust_remote_code=True).half().cuda().eval()

    @property
    def _llm_type(self) -> str:
        return "ChatGLM4"

    def _call(self, prompt: str, history: List = [], stop: Optional[List[str]] = ["<|user|>"]):
        if history is None:
            history = history
        history.append({"role": "user", "content": prompt})
        response, history = self.model.chat(self.tokenizer, prompt, history=history)
        return response
from langchain.chains import LLMChain, RetrievalQA
from langchain_community.document_loaders import TextLoader
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores.faiss import FAISS
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate, ChatPromptTemplate
from langchain_core.runnables import RunnableParallel, RunnablePassthrough
from langchain_text_splitters import RecursiveCharacterTextSplitter

from glm聊天客服 import ChatGLM4

embedding_model_dict = {
    "bge-large-zh-v1.5":"/home/cmcc/server/file/embFile/bge-large-zh-v1.5",
    "ebge-m3":"BAAI/bge-m3",
    "text2vec":"BAAI/text2vec-large-chinese",
    "text2vec2":"uer/sbert-base-chinese-nli",
    "text2vec3":"shibing624/text2vec-base-chinese"
}

def load_embedding_model(model_name="bge-large-zh-v1.5"):
    encode_kwargs = {"normalize_embeddings": False}
    model_kwargs = {"device": "cuda:0"}
    return HuggingFaceEmbeddings(
        model_name = embedding_model_dict[model_name],
        model_kwargs = model_kwargs,
        encode_kwargs = encode_kwargs
    )
embedding = load_embedding_model("bge-large-zh-v1.5")

llm = ChatGLM4()

loader = TextLoader("/home/cmcc/server/file/测试文档.txt", encoding="utf-8")

doc = loader.load()

text_splitter = RecursiveCharacterTextSplitter(chunk_size=3000, chunk_overlap=400)

docs = text_splitter.split_documents(doc)

docsearch = FAISS.from_documents(docs, embedding)
retriever = docsearch.as_retriever()

template = """只根据以下情境回答问题:
{context}

问题: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
# model = ChatOpenAI()
output_parser = StrOutputParser()

setup_and_retrieval = RunnableParallel(
    {"context": retriever, "question": RunnablePassthrough()}
)
chain = setup_and_retrieval | prompt | llm | output_parser

response = chain.invoke("小明和小红是什么关系")
print(response)

 

标签:self,知识库,回答,langchain,本地,kwargs,import,model,history
From: https://www.cnblogs.com/redhat0019/p/18121510

相关文章

  • 数据库导出数据至本地
    importjsonimportcalendarimportrefrombinimport*ismonthwrite=False#是否按月写入,数据量大时可开启start_time="2024-02-27"#开始时间end_time="2024-03-26"#结束时间wirte_path=r"C:\Users\isoftstone\Desktop\导出.xlsx"#写入的文件路径read_path=r"C:......
  • 「Mac」gitlab 更新了登录密码后,本地git仓库拉取推送等无法操作,提示无权限了 —— 解
    ​起因:公司git账户与oa账号关联,oa密码修改了,导致git远程密码修改了,本地的项目再做拉取推送时发现拉取不下来了解决办法:1、查看本地git配置cat.gitconfig2、删除git本地信息nano.gitconfig3、Mac应用程序钥匙串访问,找到对应git项,将其删除4、重新配置一下git邮箱、用......
  • Web API(五)之BOM操作&window对象&本地存储
    WebAPI(五)之BOM操作&window对象&本地存储js组成window对象定时器-延迟函数JS执行机制location对象navigator对象histroy对象本地存储localStoragesessionStorage(了解)localStorage存储复杂数据类型综合案例数组map方法数组join方法js组成JavaScript的组成ECMA......
  • 开源大模型本地私有化部署
    1、安装ollamaollma下载https://ollama.com/download/windowslinux安装curl-fsSLhttps://ollama.com/install.sh|sh运行ollamarungemma:2bollamarungemma:7b使用端口114342、下载open-webui代码https://github.com/open-webui/open-webui.git生成目录open-webuidoc......
  • 模型代码理解本地知识库
    importosfromlangchain.chainsimportRetrievalQAfromlangchain_community.document_loadersimportTextLoaderfromlangchain_community.embeddingsimportOllamaEmbeddingsfromlangchain_community.llms.ollamaimportOllamafromlangchain_community.vectors......
  • 本地运行大模型,需要什么样的配置?
    本地运行大模型有多爽?只有用过了才知道。那是一种顺畅、自由的感觉。比如使用那些主流大模型,最常见的就是网络问题,如IP受限,或者服务器压力过大导致的延迟等等。使用本地大模型,真的是像和人自然交谈那么顺畅。而且,再也不用心疼token的费用了。使用API调用大模型时,......
  • 将libc database下载到本地
    将libcdatabase下载到本地  这个是libc-database的网站,可以在线查找libc。libc-database  本文对自己下载使用libcdatabase做一个记录,详情请查看libcdatabase的官方文档:https://github.com/niklasb/libc-database下载  这个无需安装,从官方的github下载zip,放到liunx......
  • 本地知识库解锁答案
    fromlangchain.chainsimportRetrievalQAfromlangchain_community.document_loadersimportTextLoaderfromlangchain_community.embeddingsimportOllamaEmbeddingsfromlangchain_community.llms.ollamaimportOllamafromlangchain_community.vectorstores.faiss......
  • 构筑智能未来的开源 .Net AI知识库/智能体项目
        在这个信息爆炸的时代,我们如何快速准确地从汪洋大海的数据中抽取真正有价值的知识呢?AntSK,一个基于.NET开发的人工智能知识库和智能体项目,似乎给出了一个新颖的答案。今天,就让我们一起深入了解AntSK项目,探索它如何帮助我们更高效地处理信息和知识。 项目进展   ......
  • 通过历史记录运行本地模型
    fromtransformersimportAutoTokenizer,AutoModelmodelPath="/home/cmcc/server/model/chatglm3-6b"tokenizer=AutoTokenizer.from_pretrained(modelPath,trust_remote_code=True)model=AutoModel.from_pretrained(modelPath,trust_remote_code=True......