1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
| import chromadb from ollama import Client from chromadb.config import Settings from langchain_text_splitters import RecursiveCharacterTextSplitter
from models import *
with open('../Data/deepseek百度百科.txt', 'r', encoding='utf-8') as f: content = f.read() print(len(content))
class MyVectorDBConnector: def __init__(self, collection_name): chroma_client = chromadb.Client(Settings(allow_reset=True))
self.collection = chroma_client.get_or_create_collection(name=collection_name, metadata={'hnsw:space': 'l2'})
self.client = Client(host="http://127.0.0.1:11434")
def get_embeddings(self, texts, model=ALI_TONGYI_EMBEDDING_V4, dimensions=1024):
data = self.client.embed(input=texts, model="bge-m3", dimensions=dimensions)['embeddings'] return data
def get_embeddings_batch(self, texts, model=ALI_TONGYI_EMBEDDING_V4, batch_size=10, dimensions=1024): all_embeddings = [] for i in range(0, len(texts), batch_size): batch_text = texts[i : i+batch_size]
data = self.client.embed(input=batch_text, model="bge-m3", dimensions=dimensions)['embeddings'] all_embeddings.extend(data)
return all_embeddings
def add_documents(self, documents): '''向 collection 中添加文档与向量''' embeddings = self.get_embeddings_batch(documents)
self.collection.add( embeddings=embeddings, documents=documents, ids=[f"id{i}" for i in range(len(documents))], ) print("self.collection.count():", self.collection.count())
def search(self, query, top_k): ''' 检索向量数据库 query是用户的查询, top_k指查出top_k个相似高的记录 ''' results = self.collection.query( query_embeddings=self.get_embeddings_batch([query]), n_results=top_k ) return results
def get(self,count): results = self.collection.get(include=["documents", "embeddings", "metadatas"], limit=count) return results
vector_db = MyVectorDBConnector("demo")
splitter = RecursiveCharacterTextSplitter( chunk_size=500, chunk_overlap=50, separators=["\n\n", "\n", "。", "?", ",", ""], ) texts = splitter.split_text(content)
vector_db.add_documents(texts)
alldata = vector_db.get(count=1) print("数据库内的数据为:\n" + str(alldata)) print('-' * 100)
user_query = "deepseek相继发布了哪些模型"
results = vector_db.search(user_query, 5) print(results) print('-' * 100)
for i in results['documents'][0]: print(i + "\n----\n")
contents = '\n'.join(results['documents'][0])
prompt = f""" 你是一个问答机器人。 你的任务是根据下述给定的已知信息回答用户问题。 确保你的回复完全依据下述已知信息。不要编造答案。 如果下述已知信息不足以回答用户的问题,请直接回复"我无法回答您的问题"。
已知信息: {contents}
---- 用户问: {user_query}
请用中文回答用户问题。 """ print(prompt) print('-' * 100)
def get_completion(prompt, model=ALI_TONGYI_MAX_MODEL): '''封装 openai 接口''' messages = [{"role": "user", "content": prompt}]
client = get_normal_client() response = client.chat.completions.create( model=model, messages=messages, temperature=0, ) return response.choices[0].message.content
response = get_completion(prompt) print(response)
|