# import ollama
# import chromadb
# from pathlib import Path
# import os
# import sys
# import io
# sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# base_dir = Path(__file__).absolute().parent
# ollama_client = ollama.Client(host="http://localhost:11434")
# # client = chromadb.PersistentClient(path = os.path.join(base_dir,"ellis.db"))
# client = chromadb.HttpClient(
# host="192.168.214.133",
# port=31800
# )
# def analysis_doc(collectionname):
# if collectionname in client.list_collections():
# client.delete_collection(collectionname)
# collection = client.create_collection(name=collectionname)
# documents = [
# "Ellis 今年33岁,性别男,是一个编程狂热爱好者,他也喜欢耍抖音,通常夜深人静了也在耍抖音",
# ]
# # store each document in a vector embedding database
# for i, d in enumerate(documents):
# response = ollama_client.embeddings(model="mxbai-embed-large", prompt=d)
# embedding = response["embedding"]
# if embedding:
# collection.add(
# ids=[str(i)],
# embeddings=[embedding],
# documents=[d]
# )
# def ask_question(prompt="Ellis喜欢干什么",collectionname="docs"):
# collection = client.get_collection(name=collectionname)
# # generate an embedding for the prompt and retrieve the most relevant doc
# response = ollama_client.embeddings(
# prompt=prompt,
# model="mxbai-embed-large"
# )
# results = collection.query(
# query_embeddings=[response["embedding"]],
# n_results=1
# )
# data = results['documents'][0][0]
# # generate a response combining the prompt and data
# output = ollama_client.generate(
# model="llama3.2",
# prompt=f"Using this data: {data}. Respond to this prompt: {prompt}"
# )
# print(output['response'])
# if __name__=='__main__':
# analysis_doc("ellis")
# ask_question(collectionname="ellis",prompt="ellis今年多大,爱好是什么")
import threading
class Singleton(type):
_instances = {}
_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
key = '&&'.join([str(i) for i in args])
# 使用双重检查锁机制
if key not in cls._instances:
with cls._instance_lock: # 确保线程安全
if key not in cls._instances: # 再次检查
cls._instances[key] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[key]
class MyClass(metaclass=Singleton):
def __init__(self, username):
print(f"Initializing instance for {username}")
self.username = username
def get_username(self):
return self.username
# 测试
a1 = MyClass("test")
print(a1.get_username())
a2 = MyClass("test")
print(a2.get_username())
debug可以发现,MyClass只实例化了一次
https://stackoverflow.com/questions/6760685/what-is-the-best-way-of-implementing-singleton-in-python