智能客服系统需要快速检索历史 QA 对来回答用户问题。Milvus 作为核心检索引擎,能支撑高并发的客服场景。

from pymilvus import Collection, FieldSchema, CollectionSchema, DataType schema = CollectionSchema(fields=[ FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True), FieldSchema(name="question", dtype=DataType.VARCHAR, max_length=1024), FieldSchema(name="answer", dtype=DataType.VARCHAR, max_length=65535), FieldSchema(name="category", dtype=DataType.VARCHAR, max_length=64), FieldSchema(name="product_line", dtype=DataType.VARCHAR, max_length=64), FieldSchema(name="hit_count", dtype=DataType.INT64), # 命中次数(用于热度排序) FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=768), ]) collection = Collection(name="faq_knowledge", schema=schema) collection.create_index( "embedding", {"index_type": "HNSW", "params": {"M": 24, "efConstruction": 200}, "metric_type": "COSINE"}, ) collection.load()
import pandas as pd def index_faq_from_csv(csv_path: str): """从 CSV 导入历史 FAQ""" df = pd.read_csv(csv_path) questions = df["question"].tolist() embeddings = embed_texts(questions) data = [ df["question"].tolist(), df["answer"].tolist(), df.get("category", ["general"] * len(df)).tolist(), df.get("product_line", ["default"] * len(df)).tolist(), df.get("hit_count", [0] * len(df)).tolist(), embeddings, ] # 分批插入 batch_size = 2000 for i in range(0, len(data[0]), batch_size): batch = [col[i:i+batch_size] for col in data] collection.insert(batch) print(f"索引完成,共 {len(df)} 条 FAQ")
def answer_question( user_question: str, product_line: str = None, similarity_threshold: float = 0.75, top_k: int = 3, ): """回答用户问题""" query_vec = embed_texts([user_question])[0] expr = None if product_line: expr = f'product_line == "{product_line}"' results = collection.search( data=[query_vec], anns_field="embedding", param={"metric_type": "COSINE", "params": {"ef": 100}}, limit=top_k, expr=expr, output_fields=["question", "answer", "category", "hit_count"], ) answers = [] for hit in results[0]: if hit.score >= similarity_threshold: # 更新命中计数 collection.delete(f"id == {hit.id}") # 简化处理 # 实际应用中可以用 update 接口 answers.append({ "question": hit.entity.get("question"), "answer": hit.entity.get("answer"), "confidence": hit.score, "category": hit.entity.get("category"), }) return answers
智能客服通常是多轮对话,需要利用上下文优化搜索:
class ChatSession: def __init__(self): self.history = [] def ask(self, user_question: str, product_line: str = None): """带上下文的多轮问答""" self.history.append(user_question) # 利用历史构造更精确的 query if len(self.history) > 1: # 把最近几轮对话拼接成搜索 query context = " ".join(self.history[-3:]) enhanced_query = context else: enhanced_query = user_question # 搜索 answers = answer_question(enhanced_query, product_line=product_line) if answers: return { "source": "faq", "answer": answers[0]["answer"], "confidence": answers[0]["confidence"], "candidates": answers, } else: return { "source": "llm", "answer": self._call_llm(user_question), "confidence": 0.0, } def _call_llm(self, question: str) -> str: """FAQ 未命中时调用 LLM""" # ... LLM 调用逻辑 pass
新部署的客服系统没有历史 QA 数据,冷启动策略:
def learn_new_qa(question: str, answer: str, category: str = "general"): """将新问答存入知识库""" embedding = embed_texts([question])[0] data = [ [question], [answer], [category], ["default"], [0], embedding, ] collection.insert(data)
客服系统的搜索延迟要求很高(P99 < 200ms),性能优化要点:
客服知识库是动态资产,需要建立更新机制:
高并发场景下,给热门 QA 对加一层缓存,命中后直接返回,减轻搜索压力。
智能客服系统的核心流程:用户问题 → Embedding → Milvus 搜索 → 匹配判断 → 返回答案或转 LLM。多轮对话需要利用历史上下文。冷启动通过导入文档和人工标注解决。性能上要注意延迟预算的分配,Embedding 和 Milvus 搜索是主要耗时环节。