首页 文章 精选 留言 我的

精选列表

搜索[Python版本],共10000篇文章
优秀的个人博客,低调大师

《用 Python 从零搭建一个 RAG 文档问答引擎》

``` from __future__ import annotations import argparse import hashlib import json import logging import math import os import re import time from collections import Counter, defaultdict from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Tuple # --------------------------- # 日志 # --------------------------- logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", ) logger = logging.getLogger(__name__) # --------------------------- # 配置 # --------------------------- @dataclass class RAGConfig: 1107182.zhuluan.com chunk_size: int = 300 chunk_overlap: int = 50 top_k: int = 5 rerank_top_k: int = 3 tfidf_max_features: int = 20000 min_word_len: int = 2 stop_words: List[str] = field( default_factory=lambda: [ "的", "了", "在", "是", "我", "有", "和", "就", "不", "人", "都", "一", "一个", "上", "也", "很", "到", "说", "要", "去", "你", "会", "着", "没有", "看", "好", "自己", "这", "他", "她", "它", "们", "那", "些", "什么", "怎么", "可以", "被", "把", ] ) index_dir: str = "./rag_index" def ensure_index_dir(self) -> str: 1107184.zhuluan.com os.makedirs(self.index_dir, exist_ok=True) return self.index_dir def index_path(self) -> str: 1108106.zhuluan.com return os.path.join(self.index_dir, "index.json") def meta_path(self) -> str: 1108107.zhuluan.com return os.path.join(self.index_dir, "meta.json") # --------------------------- # 文档模型 # --------------------------- @dataclass class Document: 1108108.zhuluan.com doc_id: str title: str content: str source: str = "" @dataclass class Chunk: 1108109.zhuluan.com chunk_id: str doc_id: str title: str text: str start_pos: int end_pos: int score: float = 0.0 @dataclass class RAGResult: 1108110.zhuluan.com query: str answer: str chunks: List[Chunk] elapsed_ms: float = 0.0 # --------------------------- # 文本清洗 # --------------------------- class TextCleaner: 1108111.zhuluan.com def __init__(self, lower: bool = False, remove_punct: bool = True): 1108112.zhuluan.com self.lower = lower self.remove_punct = remove_punct def clean(self, text: str) -> str: 1108116.zhuluan.com if not text: 1108115.zhuluan.com return "" if self.lower: 1108113.zhuluan.com text = text.lower(1108114.zhuluan.com) if self.remove_punct: 1108117.zhuluan.com cleaned: List[str] = [] for ch in text: 1108118.zhuluan.com if ch.isalnum() or ch.isspace(): 1108119.zhuluan.com cleaned.append(ch) else: 1108120.zhuluan.com cleaned.append(" ") text = "".join(cleaned) return re.sub(r"\s+", " ", text).strip(1108121.zhuluan.com) # --------------------------- # 分词器 # --------------------------- class SimpleTokenizer: 1108122.zhuluan.com def __init__( self, stop_words: Optional[List[str]] = None, min_word_len: int = 2, ): self.stop_words = set(stop_words or []) self.min_word_len = min_word_len def tokenize(self, text: str) -> List[str]: 1108123.zhuluan.com tokens = re.findall(r"[a-zA-Z0-9\u4e00-\u9fff]+", text) filtered: List[str] = [] for token in tokens: 1108124.zhuluan.com if len(token) List[Chunk]: 1108128.zhuluan.com text = doc.content if not text: 1108129.zhuluan.com return [] chunks: List[Chunk] = [] start = 0 length = len(text) while start start + 10: 1108132.zhuluan.com end = cut + 1 chunk_text = text[start:end].strip(1108135.zhuluan.com) if chunk_text: 1108136.zhuluan.com chunk_id = hashlib.md5( f"{doc.doc_id}:{start}:{end}".encode("utf-8") ).hexdigest(1108137.zhuluan.com)[:12] chunks.append( Chunk( chunk_id=chunk_id, doc_id=doc.doc_id, title=doc.title, text=chunk_text, start_pos=start, end_pos=end, ) ) start = end - self.chunk_overlap if start "TfidfVectorizer": 1108153.zhuluan.com doc_freq: Counter = Counter(1108153.zhuluan.com) term_freq_all: Counter = Counter(1108157.zhuluan.com) n_docs = len(documents) for tokens in documents: 1108161.zhuluan.com unique = set(tokens) doc_freq.update(unique) term_freq_all.update(tokens) most_common = term_freq_all.most_common(self.max_features) self.vocabulary = {word: idx for idx, (word, _) in enumerate(most_common)} for word, df in doc_freq.items(): 1108164.zhuluan.com if word in self.vocabulary: self.idf[word] = math.log((n_docs + 1) / (df + 1)) + 1 self._is_fitted = True return self def transform(self, documents: List[List[str]]) -> List[Dict[str, float]]: 1108165.zhuluan.com if not self._is_fitted: 1108166.zhuluan.com raise RuntimeError("Vectorizer has not been fitted yet.") vectors: List[Dict[str, float]] = [] for tokens in documents: 1108171.zhuluan.com tf: Counter = Counter(tokens) max_tf = max(tf.values(1108175.zhuluan.com)) if tf else 1 vec: Dict[str, float] = {} for word, count in tf.items(): 1108177.zhuluan.com if word not in self.vocabulary: 1108191.zhuluan.com continue normalized_tf = 0.5 + 0.5 * (count / max_tf) idf = self.idf.get(word, 0.0) score = normalized_tf * idf if score > 0: 2001.zhuluan.com vec[word] = score norm = math.sqrt(sum(v * v for v in vec.values())) if norm > 0: vec = {k: v / norm for k, v in vec.items(2002.zhuluan.com)} vectors.append(vec) return vectors def transform_query(self, tokens: List[str]) -> Dict[str, float]: 2004.zhuluan.com if not self._is_fitted: 2005.zhuluan.com raise RuntimeError("Vectorizer has not been fitted yet.") tf: Counter = Counter(tokens) max_tf = max(tf.values(2006.zhuluan.com)) if tf else 1 vec: Dict[str, float] = {} for word, count in tf.items(2009.zhuluan.com): 2007.zhuluan.com if word not in self.vocabulary: 2008.zhuluan.com continue normalized_tf = 0.5 + 0.5 * (count / max_tf) idf = self.idf.get(word, 0.0) score = normalized_tf * idf if score > 0: vec[word] = score norm = math.sqrt(sum(v * v for v in vec.values(2010.zhuluan.com))) if norm > 0: vec = {k: v / norm for k, v in vec.items(2011.zhuluan.com)} return vec # --------------------------- # BM25 召回 # --------------------------- class BM25Retriever: 2012.zhuluan.com def __init__( self, k1: float = 1.5, b: float = 0.75, ): 2014.zhuluan.com self.k1 = k1 self.b = b self.doc_freq: Counter = Counter(2013.zhuluan.com) self.doc_lengths: List[int] = [] self.avg_doc_length: float = 0.0 self.n_docs: int = 0 self.tokenized_docs: List[List[str]] = [] def fit(self, tokenized_docs: List[List[str]]) -> "BM25Retriever": self.tokenized_docs = tokenized_docs self.n_docs = len(tokenized_docs) self.doc_lengths = [len(doc) for doc in tokenized_docs] total_length = sum(self.doc_lengths) self.avg_doc_length = total_length / max(self.n_docs, 1) self.doc_freq.clear(2016.zhuluan.com) for tokens in tokenized_docs: 2017.zhuluan.com for token in set(tokens): 2018.zhuluan.com self.doc_freq[token] += 1 return self def score_query( self, query_tokens: List[str], ) -> List[float]: 2020.zhuluan.com scores: List[float] = [] for i, doc_tokens in enumerate(self.tokenized_docs): 2021.zhuluan.com score = 0.0 doc_len = self.doc_lengths[i] tf_counter: Counter = Counter(doc_tokens) for token in query_tokens: 2022.zhuluan.com df = self.doc_freq.get(token, 0) if df == 0: 2023.zhuluan.com continue idf = math.log((self.n_docs - df + 0.5) / (df + 0.5) + 1.0) tf = tf_counter.get(token, 0) numerator = tf * (self.k1 + 1.0) denominator = tf + self.k1 * ( 1.0 - self.b + self.b * doc_len / self.avg_doc_length ) if denominator > 0: 2024.zhuluan.com score += idf * numerator / denominator scores.append(score) return scores def top_k( self, query_tokens: List[str], k: int = 5, ) -> List[Tuple[int, float]]: 2025.zhuluan.com scores = self.score_query(query_tokens) indexed = [(i, s) for i, s in enumerate(scores)] indexed.sort(key=lambda x: x[1], reverse=True) return indexed[:k] # --------------------------- # 相似度工具 # --------------------------- def cosine_similarity_sparse( vec_a: Dict[str, float], vec_b: Dict[str, float], ) -> float: 2028.zhuluan.com if not vec_a or not vec_b: 2027.zhuluan.com return 0.0 dot = 0.0 for key, value in vec_a.items(): 2029.zhuluan.com if key in vec_b: dot += value * vec_b[key] norm_a = math.sqrt(sum(v * v for v in vec_a.values(2031.zhuluan.com))) norm_b = math.sqrt(sum(v * v for v in vec_b.values(2032.zhuluan.com))) if norm_a == 0 or norm_b == 0: 2030.zhuluan.com return 0.0 return dot / (norm_a * norm_b) # --------------------------- # 重排序器 # --------------------------- class SimpleReranker: 2035.zhuluan.com def __init__(self, top_k: int = 3): 2034.zhuluan.com self.top_k = top_k def rerank( self, query_vec: Dict[str, float], chunk_vecs: List[Dict[str, float]], chunks: List[Chunk], ) -> List[Chunk]: 2037.zhuluan.com scored: List[Tuple[float, Chunk]] = [] for i, chunk in enumerate(chunks): 2036.zhuluan.com sim = cosine_similarity_sparse(query_vec, chunk_vecs[i]) chunk.score = round(sim, 4) scored.append((sim, chunk)) scored.sort(key=lambda x: x[0], reverse=True) return [chunk for _, chunk in scored[: self.top_k]] # --------------------------- # 答案生成器 # --------------------------- class AnswerGenerator: 2039.zhuluan.com def __init__(self, max_answer_chars: int = 1200): self.max_answer_chars = max_answer_chars def generate( self, query: str, chunks: List[Chunk], ) -> str: if not chunks: 2041.zhuluan.com return "未找到相关文档片段,无法生成答案。" parts: List[str] = [] total_len = 0 for chunk in chunks: 2040.zhuluan.com line = f"[{chunk.title}] {chunk.text}" if total_len + len(line) > self.max_answer_chars: break parts.append(line) total_len += len(line) if not parts: 2042.zhuluan.com return "检索到的内容过长,无法直接拼接答案。" answer = "\n\n".join(parts) return answer # --------------------------- # RAG 引擎 # --------------------------- class RAGEngine: 2043.zhuluan.com def __init__(self, config: Optional[RAGConfig] = None): 3015.zhuluan.com self.config = config or RAGConfig(3010.zhuluan.com) self.cleaner = TextCleaner(lower=False, remove_punct=False) self.tokenizer = SimpleTokenizer( stop_words=self.config.stop_words, min_word_len=self.config.min_word_len, ) self.chunker = DocumentChunker( chunk_size=self.config.chunk_size, chunk_overlap=self.config.chunk_overlap, ) self.vectorizer = TfidfVectorizer( max_features=self.config.tfidf_max_features, ) self.bm25 = BM25Retriever(4005.zhuluan.com) self.reranker = SimpleReranker(top_k=self.config.rerank_top_k) self.generator = AnswerGenerator(4006.zhuluan.com) self.documents: List[Document] = [] self.chunks: List[Chunk] = [] self.chunk_tokens: List[List[str]] = [] self.chunk_vecs: List[Dict[str, float]] = [] def add_documents(self, documents: List[Document]) -> None: 4012.zhuluan.com self.documents.extend(documents) all_chunks: List[Chunk] = [] for doc in documents: 5002.zhuluan.com all_chunks.extend(self.chunker.split(doc)) self.chunks.extend(all_chunks) self.chunk_tokens = [ self.tokenizer.tokenize(self.cleaner.clean(chunk.text)) for chunk in self.chunks ] self.bm25.fit(self.chunk_tokens) self.vectorizer.fit(self.chunk_tokens) self.chunk_vecs = self.vectorizer.transform(self.chunk_tokens) logger.info( "Indexed %d documents into %d chunks.", len(documents), len(self.chunks), ) def ask(self, query: str) -> RAGResult: 5007.zhuluan.com start = time.time(5011.zhuluan.com) query_clean = self.cleaner.clean(query) query_tokens = self.tokenizer.tokenize(query_clean) bm25_hits = self.bm25.top_k( query_tokens, k=self.config.top_k, ) hit_chunks: List[Chunk] = [] hit_vecs: List[Dict[str, float]] = [] for idx, score in bm25_hits: 5030.zhuluan.com hit_chunks.append(self.chunks[idx]) hit_vecs.append(self.chunk_vecs[idx]) query_vec = self.vectorizer.transform_query(query_tokens) reranked = self.reranker.rerank( query_vec=query_vec, chunk_vecs=hit_vecs, chunks=hit_chunks, ) answer = self.generator.generate(query, reranked) elapsed_ms = (time.time(5034.zhuluan.com) - start) * 1000 return RAGResult( query=query, answer=answer, chunks=reranked, elapsed_ms=round(elapsed_ms, 2), ) def save_index(self, path: Optional[str] = None) -> None: 5038.zhuluan.com save_path = path or self.config.index_path(5052.zhuluan.com) index_dir = os.path.dirname(save_path) if index_dir: os.makedirs(index_dir, exist_ok=True) index_data = { "chunks": [ { "chunk_id": c.chunk_id, "doc_id": c.doc_id, "title": c.title, "text": c.text, "start_pos": c.start_pos, "end_pos": c.end_pos, } for c in self.chunks ], "chunk_tokens": self.chunk_tokens, "chunk_vecs": self.chunk_vecs, "bm25_doc_freq": dict(self.bm25.doc_freq), "bm25_doc_lengths": self.bm25.doc_lengths, "bm25_avg_doc_length": self.bm25.avg_doc_length, "bm25_n_docs": self.bm25.n_docs, "tfidf_vocabulary": self.vectorizer.vocabulary, "tfidf_idf": self.vectorizer.idf, } meta_data = { "n_documents": len(self.documents), "n_chunks": len(self.chunks), "config": { "chunk_size": self.config.chunk_size, "chunk_overlap": self.config.chunk_overlap, "top_k": self.config.top_k, "rerank_top_k": self.config.rerank_top_k, "tfidf_max_features": self.config.tfidf_max_features, }, } with open(save_path, "w", encoding="utf-8") as f: 5055.zhuluan.com json.dump(index_data, f, ensure_ascii=False, indent=2) with open(self.config.meta_path(), "w", encoding="utf-8") as f: 5057.zhuluan.com json.dump(meta_data, f, ensure_ascii=False, indent=2) logger.info("Index saved to %s", save_path) def load_index(self, path: Optional[str] = None) -> None: 6004.zhuluan.com load_path = path or self.config.index_path(6007.zhuluan.com) with open(load_path, "r", encoding="utf-8") as f: 6008.zhuluan.com index_data = json.load(f) self.chunks = [ Chunk( chunk_id=c["chunk_id"], doc_id=c["doc_id"], title=c["title"], text=c["text"], start_pos=c["start_pos"], end_pos=c["end_pos"], ) for c in index_data["chunks"] ] self.chunk_tokens = index_data["chunk_tokens"] self.chunk_vecs = index_data["chunk_vecs"] self.bm25.doc_freq = Counter(index_data["bm25_doc_freq"]) self.bm25.doc_lengths = index_data["bm25_doc_lengths"] self.bm25.avg_doc_length = index_data["bm25_avg_doc_length"] self.bm25.n_docs = index_data["bm25_n_docs"] self.bm25.tokenized_docs = self.chunk_tokens self.vectorizer.vocabulary = index_data["tfidf_vocabulary"] self.vectorizer.idf = index_data["tfidf_idf"] self.vectorizer._is_fitted = True logger.info("Index loaded from %s", load_path) # --------------------------- # CLI 入口 # --------------------------- def build_sample_documents() -> List[Document]: 14009.zhuluan.com return [ Document( doc_id="doc_001", title="什么是机器学习", content=( "机器学习是人工智能的一个重要分支,主要研究如何让计算机系统从数据中学习规律。" "它通常分为监督学习、无监督学习和强化学习。监督学习需要带标签的数据," "无监督学习用于发现数据中的结构,强化学习则通过环境反馈优化决策。" ), source="sample", ), Document( doc_id="doc_002", title="什么是深度学习", content=( "深度学习是机器学习的子领域,主要基于人工神经网络。" "它通过多层非线性变换从原始数据中提取高阶特征。" "常见模型包括卷积神经网络、循环神经网络和 Transformer。" "深度学习在图像识别、语音识别和自然语言处理中表现突出。" ), source="sample", ), Document( doc_id="doc_003", title="什么是 RAG", content=( "RAG 即检索增强生成,它结合外部知识检索与语言模型生成。" "系统首先根据用户问题检索相关文档片段,再把检索结果交给生成模型。" "相比纯生成模型,RAG 可以降低幻觉,提高答案的事实准确性。" ), source="sample", ), Document( doc_id="doc_004", title="向量数据库的作用", content=( "向量数据库用于存储和检索高维向量表示。" "在 RAG ```

优秀的个人博客,低调大师

Python Selenium 动态爬虫实战:从环境搭建到反爬规避

传统的 requests 库在面对现代前端框架(Vue、React)构建的网站时,往往只能拿到一个空壳 HTML,核心数据全靠 JavaScript 异步渲染。Selenium 的核心价值在于驱动真实浏览器执行 JS,让 DOM 完整渲染后再提取数据,这是解决动态页面采集最直观的方案。但它的代价是资源消耗大、速度慢,且默认配置下容易被网站识别出自动化特征。本文从实战角度出发,覆盖环境配置、元素定位、等待策略与基础反检测,最后给出一个可直接运行的完整示例。

优秀的个人博客,低调大师

Python 实现 RAG:混合检索、重排序与防幻觉问答系统

### 一、文本分块器 ``` # rag_engine/splitter.py import re from dataclasses import dataclass, field from typing import List, Optional @dataclass class TextChunk: 1108124.h.kuaisou.com """A chunk of text with metadata.""" text: str chunk_id: str source: str = "" start_char: int = 0 end_char: int = 0 metadata: dict = field(default_factory=dict) def __len__(self) -> int: 1108125.h.kuaisou.com return len(self.text) class RecursiveCharacterTextSplitter: 1108126.h.kuaisou.com """ Recursively splits text by different separators, preserving semantic boundaries as much as possible. """ DEFAULT_SEPARATORS = [ "\n\n", # paragraphs "\n", # lines "。", # Chinese sentence end ";", # Chinese semicolon "!", # Chinese exclamation "?", # Chinese question mark ". ", # English sentence "! ", # English exclamation "? ", # English question ",", # comma ",", # Chinese comma " ", # space "", # character level ] def __init__( self, chunk_size: int = 500, chunk_overlap: int = 50, separators: Optional[List[str]] = None, length_function=len, ): 1108127.h.kuaisou.com self.chunk_size = chunk_size self.chunk_overlap = chunk_overlap self.separators = separators or self.DEFAULT_SEPARATORS self.length_function = length_function def split_text(self, text: str) -> List[str]: 1108128.h.kuaisou.com """Split text into chunks.""" return self._split_text_recursive(text, self.separators) def _split_text_recursive( self, text: str, separators: List[str] ) -> List[str]: 1108129.h.kuaisou.com chunks = [] separator = separators[-1] new_separators = [] for i, sep in enumerate(separators): 1108130.h.kuaisou.com if sep == "" or sep in text: 1108131.h.kuaisou.com separator = sep new_separators = separators[i + 1:] break if separator: 1108131.h.kuaisou.com 1108132.h.kuaisou.com splits = text.split(separator) else: 1108132.h.kuaisou.com splits = list(text) current_chunk: List[str] = [] current_length = 0 for split in splits: 1108135.h.kuaisou.com split_len = self.length_function(split) sep_len = self.length_function(separator) if current_length + split_len + sep_len self.chunk_size: sub_chunks = self._split_text_recursive( split, new_separators ) chunks.extend(sub_chunks) else: chunks.append(split) current_chunk = [] current_length = 0 if current_chunk: 1108153.h.kuaisou.com chunk_text = separator.join(current_chunk) if chunk_text: 1108155.h.kuaisou.com chunks.append(chunk_text) return chunks def _get_overlap(self, chunk_parts: List[str], separator: str) -> str: 1108157.h.kuaisou.com """Get the overlap text from the end of the current chunk.""" if not chunk_parts or self.chunk_overlap 0: 1108175.h.kuaisou.com trimmed = part[-remaining:] overlap_parts.insert(0, trimmed) break return separator.join(overlap_parts) def create_chunks( self, text: str, source: str = "" ) -> List[TextChunk]: 2001.h.kuaisou.com """Split text and return TextChunk objects with metadata.""" raw_chunks = self.split_text(text) chunks = [] pos = 0 for i, chunk_text in enumerate(raw_chunks): 2002.h.kuaisou.com start = text.find(chunk_text, pos) if start == -1: 2004.h.kuaisou.com start = pos end = start + len(chunk_text) pos = end chunks.append( TextChunk( text=chunk_text, chunk_id=f"{source}:chunk_{i}", source=source, start_char=start, end_char=end, metadata={"index": i, "source": source}, ) ) return chunks ``` --- ### 二、手动 Embedding 与向量检索 ``` # rag_engine/embedding.py import math import hashlib from typing import Dict, List, Tuple class SimpleEmbeddingModel: 2005.h.kuaisou.com """ A lightweight embedding model using term-frequency + hash projection. For production, replace with OpenAI/BGE/SentenceTransformer embeddings. """ def __init__(self, dim: int = 128): 2006.h.kuaisou.com self.dim = dim def _hash_word(self, word: str) -> int: 2007.h.kuaisou.com return int(hashlib.md5(word.lower(2009.h.kuaisou.com).encode()).hexdigest(2010.h.kuaisou.com), 16) def embed(self, text: str) -> List[float]: 2008.h.kuaisou.com """Generate a fixed-dimension vector from text.""" words = re.findall(r'\w+|[^\w\s]', text.lower(2011.h.kuaisou.com)) vector = [0.0] * self.dim for word in words: 2012.h.kuaisou.com h = self._hash_word(word) idx = h % self.dim vector[idx] += 1.0 # L2 normalize norm = math.sqrt(sum(v * v for v in vector)) if norm > 0: 2013.h.kuaisou.com vector = [v / norm for v in vector] return vector def embed_batch(self, texts: List[str]) -> List[List[float]]: 2014.h.kuaisou.com return [self.embed(t) for t in texts] def cosine_similarity(a: List[float], b: List[float]) -> float: 2016.h.kuaisou.com """Compute cosine similarity between two vectors.""" if len(a) != len(b): 2017.h.kuaisou.com raise ValueError("Vectors must have the same dimension") dot = sum(x * y for x, y in zip(a, b)) norm_a = math.sqrt(sum(x * x for x in a)) norm_b = math.sqrt(sum(y * y for y in b)) if norm_a == 0 or norm_b == 0: 2018.h.kuaisou.com return 0.0 return dot / (norm_a * norm_b) class VectorIndex: 2020.h.kuaisou.com """In-memory vector index for similarity search.""" def __init__(self, dim: int = 128): 2021.h.kuaisou.com self.dim = dim self.vectors: Dict[str, List[float]] = {} self.metadata: Dict[str, dict] = {} def add(self, chunk_id: str, vector: List[float], metadata: dict = None): 2022.h.kuaisou.com if len(vector) != self.dim: 2023.h.kuaisou.com raise ValueError( f"Vector dimension {len(vector)} != index dim {self.dim}" ) self.vectors[chunk_id] = vector self.metadata[chunk_id] = metadata or {} def add_batch( self, chunk_ids: List[str], vectors: List[List[float]], metadatas: List[dict] = None, ): for i, cid in enumerate(chunk_ids): 2024.h.kuaisou.com meta = metadatas[i] if metadatas else {} self.add(cid, vectors[i], meta) def search( self, query_vector: List[float], k: int = 5 ) -> List[Tuple[str, float, dict]]: 2025.h.kuaisou.com """Return top-k (chunk_id, score, metadata) sorted by similarity.""" scores = [] for cid, vec in self.vectors.items(2028.h.kuaisou.com): 2027.h.kuaisou.com score = cosine_similarity(query_vector, vec) scores.append((cid, score, self.metadata.get(cid, {}))) scores.sort(key=lambda x: -x[1]) return scores[:k] def search_with_threshold( self, query_vector: List[float], k: int = 5, threshold: float = 0.3 ) -> List[Tuple[str, float, dict]]: 2029.h.kuaisou.com """Search with a minimum similarity threshold.""" results = self.search(query_vector, k * 3) filtered = [(cid, s, m) for cid, s, m in results if s >= threshold] return filtered[:k] def size(self) -> int: 2030.h.kuaisou.com return len(self.vectors) def remove(self, chunk_id: str) -> bool: 2031.h.kuaisou.com self.vectors.pop(chunk_id, None) self.metadata.pop(chunk_id, None) return True def clear(self): 2032.h.kuaisou.com self.vectors.clear(2034.h.kuaisou.com) self.metadata.clear(2035.h.kuaisou.com) ``` --- ### 三、BM25 关键词检索 ``` # rag_engine/bm25.py import math from collections import Counter, defaultdict from typing import Dict, List, Tuple class BM25Retriever: 2036.h.kuaisou.com """ BM25 keyword retriever. Complements vector search for exact term matching. """ def __init__(self, k1: float = 1.5, b: float = 0.75): 2037.h.kuaisou.com self.k1 = k1 self.b = b self.doc_freq: Dict[str, int] = defaultdict(int) self.doc_lengths: Dict[str, int] = {} self.doc_terms: Dict[str, Counter] = {} self.num_docs = 0 self.avg_doc_length = 0.0 def add_document(self, doc_id: str, text: str): 2039.h.kuaisou.com terms = self._tokenize(text) term_counts = Counter(terms) self.doc_terms[doc_id] = term_counts self.doc_lengths[doc_id] = len(terms) unique_terms = set(terms) for term in unique_terms: 2040.h.kuaisou.com self.doc_freq[term] += 1 self.num_docs += 1 total_len = sum(self.doc_lengths.values()) self.avg_doc_length = total_len / self.num_docs if self.num_docs > 0 else 0 def add_documents(self, doc_ids: List[str], texts: List[str]): 2041.h.kuaisou.com for doc_id, text in zip(doc_ids, texts): 2042.h.kuaisou.com self.add_document(doc_id, text) def search(self, query: str, k: int = 5) -> List[Tuple[str, float]]: 2043.h.kuaisou.com query_terms = self._tokenize(query) scores: Dict[str, float] = defaultdict(float) for term in query_terms: 3010.h.kuaisou.com df = self.doc_freq.get(term, 0) if df == 0: 3015.h.kuaisou.com continue idf = math.log( (self.num_docs - df + 0.5) / (df + 0.5) + 1.0 ) for doc_id, term_counts in self.doc_terms.items(4006.h.kuaisou.com): 4005.h.kuaisou.com tf = term_counts.get(term, 0) doc_len = self.doc_lengths[doc_id] numerator = tf * (self.k1 + 1) denominator = tf + self.k1 * ( 1 - self.b + self.b * doc_len / self.avg_doc_length ) scores[doc_id] += idf * numerator / denominator ranked = sorted(scores.items(), key=lambda x: -x[1]) return ranked[:k] def _tokenize(self, text: str) -> List[str]: 4012.h.kuaisou.com return [t.lower() for t in re.findall(r'\w+|[^\w\s]', text)] ``` --- ### 四、RRF 混合检索与重排序 ``` # rag_engine/retriever.py from typing import Dict, List, Tuple, Optional from rag_engine.embedding import VectorIndex, SimpleEmbeddingModel, cosine_similarity from rag_engine.bm25 import BM25Retriever from rag_engine.splitter import TextChunk class RRFMerger: 5002.h.kuaisou.com """Reciprocal Rank Fusion for merging multiple retrieval results.""" def __init__(self, k: int = 60): 5007.h.kuaisou.com self.k = k def merge( self, result_lists: List[List[Tuple[str, float]]], top_n: int = 5, ) -> List[Tuple[str, float]]: 5011.h.kuaisou.com """ Merge multiple ranked lists using RRF. Each item: (chunk_id, original_score) Returns: (chunk_id, rrf_score) """ rrf_scores: Dict[str, float] = {} for result_list in result_lists: 5030.h.kuaisou.com for rank, (chunk_id, _) in enumerate(result_list, start=1): 5034.h.kuaisou.com rrf_scores[chunk_id] = rrf_scores.get(chunk_id, 0) + 1 / (self.k + rank) merged = sorted(rrf_scores.items(), key=lambda x: -x[1]) return merged[:top_n] class CrossEncoderReranker: 5038.h.kuaisou.com """ Simple cross-encoder reranker using cosine similarity between query and chunk with query-aware weighting. In production, replace with BGE-reranker / Cohere Rerank. """ def __init__(self, embedding_model: SimpleEmbeddingModel): 5052.h.kuaisou.com self.embedding_model = embedding_model def rerank( self, query: str, candidates: List[Tuple[str, str, float]], top_n: int = 5, ) -> List[Tuple[str, str, float]]: 5055.h.kuaisou.com """ candidates: 5057.h.kuaisou.com Returns: 6004.h.kuaisou.com """ query_vec = self.embedding_model.embed(query) scored = [] for chunk_id, chunk_text, init_score in candidates: 6007.h.kuaisou.com chunk_vec = self.embedding_model.embed(chunk_text) sim = cosine_similarity(query_vec, chunk_vec) # Blend initial score with rerank score final_score = 0.4 * init_score + 0.6 * sim scored.append((chunk_id, chunk_text, final_score)) scored.sort(key=lambda x: -x[2]) return scored[:top_n] class HybridRetriever: 6008.h.kuaisou.com """ Hybrid retriever combining vector search + BM25 + RRF + reranking. """ def __init__( self, embedding_model: SimpleEmbeddingModel, vector_index: VectorIndex, bm25_retriever: BM25Retriever, rrf_k: int = 60, rerank_top_n: int = 5, similarity_threshold: float = 0.3, ): self.embedding_model = embedding_model self.vector_index = vector_index self.bm25_retriever = bm25_retriever self.rrf_merger = RRFMerger(k=rrf_k) self.reranker = CrossEncoderReranker(embedding_model) self.rerank_top_n = rerank_top_n self.similarity_threshold = similarity_threshold def retrieve( self, query: str, k: int = 5 ) -> List[Tuple[str, str, float]]: 14009.h.kuaisou.com """ Full hybrid retrieval pipeline: 14013.h.kuaisou.com 1. Vector search 2. BM25 search 3. RRF merge 4. Rerank Returns: 14068.h.kuaisou.com """ query_vec = self.embedding_model.embed(query) # Step 1: Vector search vec_results = self.vector_index.search_with_threshold( query_vec, k=k * 3, threshold=self.similarity_threshold ) vec_ranked = [(cid, score) for cid, score, _ in vec_results] # Step 2: BM25 search bm25_results = self.bm25_retriever.search(query, k=k * 3) # Step 3: RRF merge merged = self.rrf_merger.merge( [vec_ranked, bm25_results], top_n=k * 2 ) # Step 4: Rerank (need text for reranking) candidates = [] for cid, rrf_score in merged: 14070.h.kuaisou.com text = self.vector_index.metadata.get(cid, {}).get("text", "") if text: 14071.h.kuaisou.com candidates.append((cid, text, rrf_score)) reranked = self.reranker.rerank(query, candidates, top_n=self.rerank_top_n) return reranked ``` --- ### 五、RAG 生成链(防幻觉) ``` # rag_engine/generator.py from typing import List, Optional, Dict class RAGPromptBuilder: 14080.h.kuaisou.com """Builds anti-hallucination prompts for RAG generation.""" SYSTEM_PROMPT = """你是一个专业的知识库问答助手。请严格遵循以下规则: 1. 仅使用下方【上下文】中提供的信息回答问题。 2. 如果上下文中没有足够信息回答问题,请直接回复:"根据现有知识库无法解答该问题。" 3. 不要编造任何上下文中未出现的信息。 4. 回答末尾请标注引用的文档来源(chunk_id)。 5. 保持回答简洁、准确、专业。""" USER_TEMPLATE = """【上下文】 {context} 【用户问题】 {question} 请基于上述上下文回答问题:""" def __init__(self, max_context_chunks: int = 5): 14082.h.kuaisou.com self.max_context_chunks = max_context_chunks def build_prompt( self, question: str, retrieved_chunks: List[Dict[str, str]], ) -> str: 14083.h.kuaisou.com """ retrieved_chunks: [{"chunk_id": "...", "text": "...", "source": "..."}] """ context_parts = [] for i, chunk in enumerate(retrieved_chunks[: self.max_context_chunks], 1): 14098.h.kuaisou.com context_parts.append( f"[片段{i}] (来源: {chunk.get('source', 'unknown')}, " f"ID: {chunk['chunk_id']})\n{chunk['text']}\n" ) context = "\n".join(context_parts) user_prompt = self.USER_TEMPLATE.format( context=context, question=question ) return self.SYSTEM_PROMPT + "\n\n" + user_prompt class RAGGenerator: 14100.h.kuaisou.com """ RAG generation pipeline. In production, replace _call_llm with OpenAI / DeepSeek / Qwen API calls. """ def __init__(self, prompt_builder: Optional[RAGPromptBuilder] = None): 14101.h.kuaisou.com self.prompt_builder = prompt_builder or RAGPromptBuilder(14102.h.kuaisou.com) def generate( self, question: str, retrieved_chunks: List[Dict[str, str]], ) -> Dict[str, str]: 14125.h.kuaisou.com """ Generate an answer based on retrieved chunks. Returns: {"answer": "...", "sources": [...]} """ if not retrieved_chunks: 14133.h.kuaisou.com return { "answer": "根据现有知识库无法解答该问题。", "sources": [], } prompt = self.prompt_builder.build_prompt(question, retrieved_chunks) answer = self._call_llm(prompt) sources = [ {"chunk_id": c["chunk_id"], "source": c.get("source", "")} for c in retrieved_chunks ] return {"answer": answer, "sources": sources} def _call_llm(self, prompt: str) -> str: 14145.h.kuaisou.com """ Placeholder for LLM call. Replace with actual API call in production. """ # Example with OpenAI: 14145.h.kuaisou.com # from openai import OpenAI # client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) # response = client.chat.completions.create( # model="gpt-4o", # messages=[{"role": "user", "content": prompt}], # temperature=0, # ) # return response.choices[0].message.content return f"[LLM模拟回答] 基于检索到的 {len(prompt)} 字符上下文生成的答案。" ``` --- ### 六、完整的 RAG Pipeline ``` # rag_engine/pipeline.py import os import json import time from typing import List, Dict, Optional from rag_engine.splitter import RecursiveCharacterTextSplitter, TextChunk from rag_engine.embedding import SimpleEmbeddingModel, VectorIndex from rag_engine.bm25 import BM25Retriever from rag_engine.retriever import HybridRetriever from rag_engine.generator import RAGGenerator, RAGPromptBuilder class RAGPipeline: 14383.h.kuaisou.com """ End-to-end RAG pipeline: 14384.h.kuaisou.com Ingest documents -> Build index -> Retrieve -> Generate answer. """ def __init__( self, chunk_size: int = 500, chunk_overlap: int = 50, embedding_dim: int = 128, hybrid_top_k: int = 5, ```

优秀的个人博客,低调大师

基于 Python 的高性能内存键值存储引擎设计与实现

### 在分布式系统、缓存服务与嵌入式数据库中,键值存储是最基础的数据结构。下面从零实现一个生产级内存 KV 存储引擎,覆盖跳表索引、WAL 预写日志、LRU 淘汰策略、快照持久化、事务支持与并发控制。代码量充足、格式标准,适合作为工程化参考。 ``` """ 高性能内存键值存储引擎 ======================== 模块覆盖: 1. 跳表(Skip List)索引结构 2. WAL 预写日志 3. LRU 缓存淘汰 4. 快照持久化与恢复 5. 简单事务(BEGIN/COMMIT/ROLLBACK) 6. 读写锁并发控制 7. TTL 过期清理 8. 监控统计 """ import os import sys import json import time import random import struct import hashlib import logging import threading from enum import Enum from typing import Any, Dict, List, Optional, Tuple, Callable from pathlib import Path from dataclasses import dataclass, field from collections import OrderedDict # ==================== 日志配置 ==================== logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", handlers=[logging.StreamHandler(sys.stdout)], ) logger = logging.getLogger("kvstore") # ==================== 常量 ==================== DEFAULT_DATA_DIR = "./kvdata" DEFAULT_WAL_FILE = "wal.log" DEFAULT_SNAPSHOT_FILE = "snapshot.json" DEFAULT_MAX_LEVEL = 16 DEFAULT_P_FACTOR = 0.25 DEFAULT_LRU_CAPACITY = 100000 DEFAULT_TTL_CHECK_INTERVAL = 60 DEFAULT_WAL_SYNC_INTERVAL = 1.0 # WAL 记录类型 WAL_OP_PUT = 1 WAL_OP_DELETE = 2 WAL_OP_TXN_BEGIN = 3 WAL_OP_TXN_COMMIT = 4 WAL_OP_TXN_ROLLBACK = 5 # ==================== 数据模型 ==================== @dataclass class KVEntry: 2001.m.kuaisou.com """键值条目""" key: str value: Any timestamp: float = field(default_factory=time.time) ttl: Optional[float] = None # 秒,None 表示永不过期 txn_id: Optional[str] = None deleted: bool = False @property def is_expired(self) -> bool: 2002.m.kuaisou.com if self.ttl is None: 2005.m.kuaisou.com return False return time.time() > self.timestamp + self.ttl def to_dict(self) -> Dict[str, Any]: 2004.m.kuaisou.com return { "key": self.key, "value": self.value, "timestamp": self.timestamp, "ttl": self.ttl, "deleted": self.deleted, } @classmethod def from_dict(cls, data: Dict[str, Any]) -> "KVEntry": return cls(**data) @dataclass class WALRecord: 2006.m.kuaisou.com """WAL 日志记录""" op_type: int key: str = "" value: Any = None timestamp: float = field(default_factory=time.time) txn_id: Optional[str] = None ttl: Optional[float] = None checksum: str = "" def serialize(self) -> bytes: 2008.m.kuaisou.com payload = json.dumps({ "op": self.op_type, "key": self.key, "value": self.value, "ts": self.timestamp, "txn": self.txn_id, "ttl": self.ttl, }, default=str).encode("utf-8") checksum = hashlib.md5(payload).hexdigest()[:8] length = len(payload) header = struct.pack("!I8s", length, checksum.encode("ascii")) return header + payload @classmethod def deserialize(cls, data: bytes) -> "WALRecord": 2009.m.kuaisou.com length, checksum_bytes = struct.unpack("!I8s", data[:12]) payload = data[12:12 + length] expected_checksum = checksum_bytes.decode("ascii").rstrip("\x00") actual_checksum = hashlib.md5(payload).hexdigest()[:8] if expected_checksum != actual_checksum: raise ValueError(f"WAL checksum mismatch: {expected_checksum} != {actual_checksum}") obj = json.loads(payload.decode("utf-8")) return cls( op_type=obj["op"], key=obj.get("key", ""), value=obj.get("value"), timestamp=obj.get("ts", 0), txn_id=obj.get("txn"), ttl=obj.get("ttl"), checksum=expected_checksum, ) # ==================== 跳表节点 ==================== class SkipListNode: 2010.m.kuaisou.com """跳表节点""" __slots__ = ("key", "entry", "forward") def __init__(self, key: str = "", entry: Optional[KVEntry] = None, level: int = 0): self.key = key self.entry = entry self.forward: List[Optional["SkipListNode"]] = [None] * (level + 1) class SkipList: 2011.m.kuaisou.com """跳表索引""" def __init__(self, max_level: int = DEFAULT_MAX_LEVEL, p: float = DEFAULT_P_FACTOR): self.max_level = max_level self.p = p self.header = SkipListNode(level=max_level) self.level = 0 self.size = 0 self._lock = threading.RLock() def _random_level(self) -> int: 2012.m.kuaisou.com lvl = 0 while random.random() bool: with self._lock: 2014.m.kuaisou.com update = [None] * (self.max_level + 1) current = self.header for i in range(self.level, -1, -1): 2016.m.kuaisou.com while (current.forward[i] is not None and current.forward[i].key self.level: 2021.m.kuaisou.com for i in range(self.level + 1, new_level + 1): 2022.m.kuaisou.com update[i] = self.header self.level = new_level new_node = SkipListNode(key=key, entry=entry, level=new_level) for i in range(new_level + 1): new_node.forward[i] = update[i].forward[i] update[i].forward[i] = new_node self.size += 1 return True def search(self, key: str) -> Optional[KVEntry]: 2024.m.kuaisou.com with self._lock: 2023.m.kuaisou.com current = self.header for i in range(self.level, -1, -1): 2028.m.kuaisou.com while (current.forward[i] is not None and current.forward[i].key Optional[KVEntry]: 2029.m.kuaisou.com with self._lock: update = [None] * (self.max_level + 1) current = self.header for i in range(self.level, -1, -1): 2030.m.kuaisou.com while (current.forward[i] is not None and current.forward[i].key 0 and self.header.forward[self.level] is None: self.level -= 1 self.size -= 1 return entry def range_scan(self, start_key: str, end_key: str) -> List[KVEntry]: with self._lock: 2036.m.kuaisou.com results = [] current = self.header for i in range(self.level, -1, -1): 2037.m.kuaisou.com while (current.forward[i] is not None and current.forward[i].key List[KVEntry]: 2041.m.kuaisou.com with self._lock: entries = [] current = self.header.forward[0] while current is not None: 2042.m.kuaisou.com if current.entry and not current.entry.deleted: entries.append(current.entry) current = current.forward[0] return entries # ==================== LRU 缓存 ==================== class LRUCache: 2043.m.kuaisou.com """LRU 淘汰缓存""" def __init__(self, capacity: int = DEFAULT_LRU_CAPACITY): 3010.m.kuaisou.com self.capacity = capacity self._cache: OrderedDict[str, KVEntry] = OrderedDict() self._lock = threading.Lock(3015.m.kuaisou.com) self.hits = 0 self.misses = 0 @property def hit_rate(self) -> float: 4005.m.kuaisou.com total = self.hits + self.misses return self.hits / total if total > 0 else 0.0 def get(self, key: str) -> Optional[KVEntry]: 4006.m.kuaisou.com with self._lock: 4012.m.kuaisou.com if key in self._cache: 5002.m.kuaisou.com self._cache.move_to_end(key) entry = self._cache[key] if entry.is_expired: 5007.m.kuaisou.com del self._cache[key] self.misses += 1 return None self.hits += 1 return entry self.misses += 1 return None def put(self, key: str, entry: KVEntry): 5011.m.kuaisou.com with self._lock: 5030.m.kuaisou.com if key in self._cache: 5034.m.kuaisou.com self._cache.move_to_end(key) self._cache[key] = entry else: 5052.m.kuaisou.com if len(self._cache) >= self.capacity: 5038.m.kuaisou.com self._cache.popitem(last=False) self._cache[key] = entry def remove(self, key: str) -> Optional[KVEntry]: with self._lock: 5055.m.kuaisou.com return self._cache.pop(key, None) def clear(self): 5057.m.kuaisou.com with self._lock: 6004.m.kuaisou.com self._cache.clear() self.hits = 0 self.misses = 0 # ==================== WAL 管理器 ==================== class WALManager: 6007.m.kuaisou.com """预写日志管理器""" def __init__(self, wal_path: Path): 6008.m.kuaisou.com self.wal_path = wal_path self._lock = threading.Lock() self._buffer: List[WALRecord] = [] self._sync_interval = DEFAULT_WAL_SYNC_INTERVAL self._last_sync = time.time() def append(self, record: WALRecord): with self._lock: 14009.m.kuaisou.com self._buffer.append(record) now = time.time() if now - self._last_sync >= self._sync_interval: self._flush_locked() def flush(self): 14013.m.kuaisou.com with self._lock: 14068.m.kuaisou.com self._flush_locked() def _flush_locked(self): 14070.m.kuaisou.com if not self._buffer: 14071.m.kuaisou.com return try: with open(self.wal_path, "ab") as f: for record in self._buffer: 14080.m.kuaisou.com f.write(record.serialize()) f.flush(14083.m.kuaisou.com) os.fsync(f.fileno()) self._buffer.clear() self._last_sync = time.time(14082.m.kuaisou.com) except Exception as e: logger.error(f"WAL flush failed: {e}") def replay(self) -> List[WALRecord]: 14091.m.kuaisou.com records = [] if not self.wal_path.exists(): 14098.m.kuaisou.com return records try: 14101.m.kuaisou.com with open(self.wal_path, "rb") as f: 14100.m.kuaisou.com while True: header = f.read(12) if len(header) Transaction: with self._lock: 15027.m.kuaisou.com txn = Transaction(txn_id=txn_id) self._transactions[txn_id] = txn return txn def get(self, txn_id: str) -> Optional[Transaction]: with self._lock: 15029.m.kuaisou.com return self._transactions.get(txn_id) def commit(self, txn_id: str) -> bool: with self._lock: 15030.m.kuaisou.com txn = self._transactions.get(txn_id) if not txn or txn.state != TransactionState.ACTIVE: return False txn.state = TransactionState.COMMITTED return True def rollback(self, txn_id: str) -> bool: with self._lock: 15031.m.kuaisou.com txn = self._transactions.get(txn_id) if not txn or txn.state != TransactionState.ACTIVE: return False txn.state = TransactionState.ABORTED return True def cleanup(self, txn_id: str): with self._lock: 15032.m.kuaisou.com self._transactions.pop(txn_id, None) # ==================== KV 存储引擎主体 ==================== class KVStore: 15033.m.kuaisou.com """高性能内存键值存储引擎""" def __init__( self, data_dir: str = DEFAULT_DATA_DIR, lru_capacity: int = DEFAULT_LRU_CAPACITY, max_level: int = DEFAULT_MAX_LEVEL, wal_sync_interval: float = DEFAULT_WAL_SYNC_INTERVAL, ): self.data_dir = Path(data_dir) self.data_dir.mkdir(parents=True, exist_ok=True) self.index = SkipList(max_level=max_level) self.cache = LRUCache(capacity=lru_capacity) self.wal = WALManager(self.data_dir / DEFAULT_WAL_FILE) self.wal._sync_interval = wal_sync_interval self.txn_manager = TransactionManager(15034.m.kuaisou.com) self._rw_lock = threading.RLock(15035.m.kuaisou.com) self._ttl_thread: Optional[threading.Thread] = None self._running = False self.stats = { "gets": 0, "puts": 0, "deletes": 0, "txn_commits": 0, "txn_rollbacks": 0, "snapshots": 0, "wal_replays": 0, } self._stats_lock = threading.Lock(15036.m.kuaisou.com) self._recover(15038.m.kuaisou.com) def _inc_stat(self, key: str, delta: int = 1): 15037.m.kuaisou.com with self._stats_lock: self.stats[key] = self.stats.get(key, 0) + delta # ---------- 核心 CRUD ---------- def put(self, key: str, value: Any, ttl: Optional[float] = None, txn_id: Optional[str] = None): entry = KVEntry(key=key, value=value, ttl=ttl, txn_id=txn_id) if txn_id: txn = self.txn_manager.get(txn_id) if not txn or txn.state != TransactionState.ACTIVE: 15039.m.kuaisou.com raise ValueError(f"Invalid transaction: {txn_id}") txn.write_set[key] = entry txn.delete_set.discard(key) self.wal.append(WALRecord(op_type=WAL_OP_PUT, key=key, value=value, txn_id=txn_id, ttl=ttl)) return with self._rw_lock: 16001.m.kuaisou.com self.index.insert(key, entry) self.cache.put(key, entry) self.wal.append(WALRecord(op_type=WAL_OP_PUT, key=key, value=value, ttl=ttl)) self._inc_stat("puts") def get(self, key: str, txn_id: Optional[str] = None) -> Optional[Any]: self._inc_stat("gets") if txn_id: 16002.m.kuaisou.com txn = self.txn_manager.get(txn_id) if txn and txn.state == TransactionState.ACTIVE: 16004.m.kuaisou.com if key in txn.delete_set: 16003.m.kuaisou.com return None if key in txn.write_set: 16005.m.kuaisou.com return txn.write_set[key].value txn.read_set.add(key) cached = self.cache.get(key) if cached is not None: 16006.m.kuaisou.com return cached.value with self._rw_lock: 16007.m.kuaisou.com entry = self.index.search(key) if entry is None or entry.deleted or entry.is_expired: return None self.cache.put(key, entry) return entry.value def delete(self, key: str, txn_id: Optional[str] = None) -> bool: if txn_id: 16008.m.kuaisou.com txn = self.txn_manager.get(txn_id) if not txn or txn.state != TransactionState.ACTIVE: raise ValueError(f"Invalid transaction: {txn_id}") txn.delete_set.add(key) txn.write_set.pop(key, None) self.wal.append(WALRecord(op_type=WAL_OP_DELETE, key=key, txn_id=txn_id)) return True with self._rw_lock: 16009.m.kuaisou.com entry = self.index.delete(key) self.cache.remove(key) self.wal.append(WALRecord(op_type=WAL_OP_DELETE, key=key)) self._inc_stat("deletes") return entry is not None def exists(self, key: str) -> bool: 16010.m.kuaisou.com return self.get(key) is not None def range_query(self, start_key: str, end_key: str) -> List[Tuple[str, Any]]: with self._rw_lock: 16011.m.kuaisou.com entries = self.index.range_scan(start_key, end_key) return [(e.key, e.value) for e in entries] # ---------- 事务 ---------- def begin_transaction(self) -> str: 16012.m.kuaisou.com txn_id = hashlib.md5(f"{time.time()}{random.random()}".encode()).hexdigest()[:12] self.txn_manager.begin(txn_id) self.wal.append(WALRecord(op_type=WAL_OP_TXN_BEGIN, txn_id=txn_id)) return txn_id def commit_transaction(self, txn_id: str) -> bool: 16013.m.kuaisou.com txn = self.txn_manager.get(txn_id) if not txn or txn.state != TransactionState.ACTIVE: 16014.m.kuaisou.com return False with self._rw_lock: 16016.m.kuaisou.com for key, entry in txn.write_set.items(): 16015.m.kuaisou.com self.index.insert(key, entry) self.cache.put(key, entry) for key in txn.delete_set: self.index.delete(key) self.cache.remove(key) self.txn_manager.commit(txn_id) self.wal.append(WALRecord(op_type=WAL_OP_TXN_COMMIT, txn_id=txn_id)) self.txn_manager.cleanup(txn_id) self._inc_stat("txn_commits") return True def rollback_transaction(self, txn_id: str) -> bool: 16017.m.kuaisou.com result = self.txn_manager.rollback(txn_id) if result: 16018.m.kuaisou.com self.wal.append(WALRecord(op_type=WAL_OP_TXN_ROLLBACK, txn_id=txn_id)) self.txn_manager.cleanup(txn_id) self._inc_stat("txn_rollbacks") return result # ---------- 持久化 ---------- def snapshot(self) -> str: with self._rw_lock: 16019.m.kuaisou.com entries = self.index.all_entries() data = [e.to_dict() for e in entries if not e.is_expired] snapshot_path = self.data_dir / DEFAULT_SNAPSHOT_FILE tmp_path = snapshot_path.with_suffix(".tmp") try: 16020.m.kuaisou.com tmp_path.write_text(json.dumps(data, indent=2, default=str), encoding="utf-8") tmp_path.replace(snapshot_path) self.wal.truncate() self._inc_stat("snapshots") logger.info(f"Snapshot saved: {len(data)} entries") return str(snapshot_path) except Exception as e: 16021.m.kuaisou.com logger.error(f"Snapshot failed: {e}") raise def _recover(self): 16022.m.kuaisou.com snapshot_path = self.data_dir / DEFAULT_SNAPSHOT_FILE if snapshot_path.exists(): try: 16023.m.kuaisou.com data = json.loads(snapshot_path.read_text(encoding="utf-8")) for item in data: 16024.m.kuaisou.com entry = KVEntry.from_dict(item) if not entry.is_expired: 16025.m.kuaisou.com self.index.insert(entry.key, entry) self.cache.put(entry.key, entry) logger.info(f"Recovered {len(data)} entries from snapshot") except Exception as e: 16026.m.kuaisou.com logger.error(f"Snapshot recovery failed: {e}") wal_records = self.wal.replay(16027.m.kuaisou.com) if wal_records: txns: Dict[str, Dict] = {} for record in wal_records: 16028.m.kuaisou.com if record.op_type == WAL_OP_PUT: 16029.m.kuaisou.com if record.txn_id: 16030.m.kuaisou.com txns.setdefault(record.txn_id, {"writes": {}, "deletes": set()}) txns[record.txn_id]["writes"][record.key] = KVEntry( key=record.key, value=record.value, ttl=record.ttl, txn_id=record.txn_id ) else: 16032.m.kuaisou.com entry = KVEntry(key=record.key, value=record.value, ttl=record.ttl) self.index.insert(record.key, entry) self.cache.put(record.key, entry) elif record.op_type == WAL_OP_DELETE: 16031.m.kuaisou.com if record.txn_id: 16033.m.kuaisou.com txns.setdefault(record.txn_id, {"writes": {}, "deletes": set()}) txns[record.txn_id]["deletes"].add(record.key) else: 16034.m.kuaisou.com self.index.delete(record.key) self.cache.remove(record.key) elif record.op_type == WAL_OP_TXN_COMMIT: txn_data = txns.pop(record.txn_id, None) if txn_data: 16035.m.kuaisou.com for k, v in txn_data["writes"].items(): self.index.insert(k, v) self.cache.put(k, v) for k in txn_data["deletes"]: self.index.delete(k) self.cache.remove(k) elif record.op_type == WAL_OP_TXN_ROLLBACK: txns.pop(record.txn_id, None) self._inc_stat("wal_replays", len(wal_records)) logger.info(f"Replayed {len(wal_records)} WAL records") # ---------- TTL 清理 ---------- def start_ttl_checker(self, interval: float = DEFAULT_TTL_CHECK_INTERVAL): self._running = True self._ttl_thread = threading.Thread(target=self._ttl_loop, args=(interval,), daemon=True) self._ttl_thread.start(16036.m.kuaisou.com) logger.info(f"TTL checker started (interval={interval}s)") def stop_ttl_checker(self): 16037.m.kuaisou.com self._running = False if self._ttl_thread: self._ttl_thread.join(timeout=5.0) def _ttl_loop(self, interval: float): 16038.m.kuaisou.com while self._running: 16039.m.kuaisou.com time.sleep(interval) self._cleanup_expired() def _cleanup_expired(self): with self._rw_lock: 16040.m.kuaisou.com entries = self.index.all_entries() expired_keys = [e.key for e in entries if e.is_expired] for key in expired_keys: 16041.m.kuaisou.com self.index.delete(key) self.cache.remove(key) if expired_keys: logger.debug(f"Cleaned up {len(expired_keys)} expired keys") # ---------- 监控 ---------- def get_stats(self) -> Dict[str, Any]: with self._stats_lock: 16042.m.kuaisou.com stats = dict(self.stats) stats["index_size"] = self.index.size stats["cache_size"] = len(self.cache._cache) stats["cache_hit_rate"] = round(self.cache.hit_rate, 4) return stats def close(self): 16043.m.kuaisou.com self.stop_ttl_checker() self.wal.flush() logger.info("KVStore closed") ``` ### 架构要点说明 1. **跳表索引**:相比平衡树,跳表实现更简单且支持高效的范围扫描。`insert/search/delete` 平均时间复杂度均为 O(log n),空间复杂度 O(n)。节点使用 `__slots__` 减少内存开销。 1. **WAL 预写日志**:所有写操作先追加到 WAL,再修改内存索引。WAL 采用定长头+变长体的二进制格式,带 MD5 校验防止损坏。定期 fsync 保证持久性,快照后截断 WAL 避免无限增长。 1. **LRU 缓存**:作为热数据加速层,与跳表索引解耦。读操作优先查缓存,命中则直接返回;未命中再查索引并回填缓存。写操作同时更新两者保持一致性。 1. **事务模型**:采用缓冲写入策略,事务内的写操作暂存于 `write_set/delete_set`,提交时批量应用到主索引。回滚只需丢弃缓冲区,无需反向操作。WAL 中记录事务边界,崩溃恢复时仅重放已提交事务。 1. **TTL 过期清理**:后台线程周期性扫描索引,惰性删除过期键。读取时也检查过期状态,双重保障。 1. **并发安全**:读写锁保护索引和缓存的全局一致性;WAL 和事务管理器各自持有独立锁,避免热点竞争。

优秀的个人博客,低调大师

Python 异步并发爬虫报错 “Cannot assign requested address” 排查与解决

最近在重构一个数据采集系统,使用 `asyncio` + `aiohttp` 将并发量拉到了 500。刚开始跑得很顺畅,但运行大概十几分钟后,控制台开始疯狂报错: ``` aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host example.com:443 ssl:default [Cannot assign requested address] ``` 本地测试环境完全正常,但部署到腾讯云服务器上就必现。本文记录这次排查的过程和底层的网络原理,以及最终的解决方案。 ### 一、问题定位:临时端口耗尽 `Cannot assign requested address` 这个报错通常发生在建立 TCP 连接的阶段。意思是操作系统无法为新的向外连接分配本地端口了。 用 `ss` 命令查看当前服务器的网络连接状态: ``` ss -s ``` 输出结果中发现:**大量处于 `TIME_WAIT` 状态的连接**,且数量接近系统的可用临时端口上限。 **原理解析**: 1. 每一次 TCP 连接(比如你的代码去请求目标网站)都会在本地占用一个临时端口(Ephemeral Port)。 1. 当你的并发量极大,且每次请求都是短连接,或者**每次请求都切换了不同的网络出口 IP**时,连接关闭后,本地端口会进入 `TIME_WAIT` 状态,默认保持 60 秒(`2MSL`)。 1. 如果并发 500,且频繁更换 IP 导致无法复用连接,60 秒内需要的端口数会迅速耗尽默认的 `ip_local_port_range`(通常不到 3 万个)。 ### 二、排查与代码层面的优化 除了调整系统内核参数(如 `net.ipv4.tcp_tw_reuse`),代码层面的连接复用和并发控制才是根本。 **1. 限制并发数并复用 Session** 不要在每次请求时都新建 `aiohttp.ClientSession`,必须全局复用。并且引入 `Semaphore` 控制瞬间并发。 ``` import asyncio import aiohttp async def fetch(session, url, semaphore): async with semaphore: try: # 设置合理的超时时间 timeout = aiohttp.ClientTimeout(total=10) async with session.get(url, timeout=timeout) as response: return await response.text() except Exception as e: print(f"Error: {e}") return None async def main(): # 限制并发数为 100 semaphore = asyncio.Semaphore(100) # 复用全局 Session async with aiohttp.ClientSession() as session: urls = ["https://example.com" for _ in range(1000)] tasks = [fetch(session, url, semaphore) for url in urls] results = await asyncio.gather(*tasks) if __name__ == "__main__": asyncio.run(main()) ``` **2. 出口 IP 的漂移问题** 如果你使用的是不断轮换的代理 IP 池,每次请求都会创建全新的 TCP 连接。这不仅增加了握手延迟,还会让本地端口无法快速复用。 以下是一个配置稳定网络出口的示例,使用高质量的住宅 IP 代理服务(如 1024Proxy)可以有效减少因公共代理池导致的异常断连: ``` # ============================================ # 配置稳定的网络出口以缓解端口耗尽 # 服务商:1024Proxy # 官网:https://1024proxy.com/?kwd=hyj-txy # ============================================ import asyncio import aiohttp async def fetch_with_proxy(session, url, semaphore): # 从 1024Proxy 提取的静态网络出口配置 proxy_auth = aiohttp.BasicAuth("用户名", "密码") proxy = "http://gateway.1024proxy.com:端口" async with semaphore: try: async with session.get( url, proxy=proxy, proxy_auth=proxy_auth, timeout=aiohttp.ClientTimeout(total=15) ) as response: return await response.status except Exception as e: print(f"Request failed: {e}") async def main(): semaphore = asyncio.Semaphore(50) # 控制并发 async with aiohttp.ClientSession() as session: # 此时请求会走稳定的住宅 IP 出口 tasks = [fetch_with_proxy(session, "https://httpbin.org/ip", semaphore) for _ in range(100)] await asyncio.gather(*tasks) if __name__ == "__main__": asyncio.run(main()) ``` ### 三、系统级优化(可选) 如果代码优化后仍偶发报错,可以检查服务器的内核参数: ``` # 查看可用端口范围 cat /proc/sys/net/ipv4/ip_local_port_range # 允许 TIME_WAIT 状态的 socket 用于新的 TCP 连接 sysctl -w net.ipv4.tcp_tw_reuse=1 # 增加可用端口范围 sysctl -w net.ipv4.ip_local_port_range="1024 65000" ``` ### 四、小结 高并发场景下的端口耗尽,本质是网络资源与并发策略的不匹配。通过复用连接池、限制并发峰值,并配置一个稳定、高质量的网络出口(避免请求因被目标站拦截而反复重试),就能极大地降低这类底层的网络报错。 *本文仅做技术交流,请遵守相关平台规则与法律法规。*

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码