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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from sentence_transformers import SentenceTransformer, util
|
| 3 |
+
|
| 4 |
+
# 1. 使用已经下载过的语义模型
|
| 5 |
+
MODEL_NAME = "intfloat/multilingual-e5-small"
|
| 6 |
+
|
| 7 |
+
# 2. 模拟企业知识库(每份文档都有 ID)
|
| 8 |
+
documents = [
|
| 9 |
+
{
|
| 10 |
+
"id": "WMS-001",
|
| 11 |
+
"text": "库存管理系统记录商品入库、出库和剩余库存数量。",
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"id": "ERP-001",
|
| 15 |
+
"text": "ERP 采购订单系统负责供应商报价、采购审批和付款流程。",
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"id": "JAVA-001",
|
| 19 |
+
"text": "Java Spring Boot 通过 REST Controller 实现 HTTP API。",
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"id": "DEVICE-001",
|
| 23 |
+
"text": "设备运维系统负责设备巡检、维修工单与故障记录。",
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"id": "JAVA-002",
|
| 27 |
+
"text": "Java 中的 inventoryTransaction 用于库存事务处理。",
|
| 28 |
+
},
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
# 3. 提取检索词:中文双字组合 + 英文单词
|
| 32 |
+
def tokenize(text):
|
| 33 |
+
text = text.lower()
|
| 34 |
+
tokens = set(re.findall(r"[a-z][a-z0-9_]*", text))
|
| 35 |
+
|
| 36 |
+
for segment in re.findall(r"[\u4e00-\u9fff]+", text):
|
| 37 |
+
for i in range(len(segment) - 1):
|
| 38 |
+
tokens.add(segment[i:i + 2])
|
| 39 |
+
|
| 40 |
+
return tokens
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# 4. 关键词检索(简化实验版)
|
| 44 |
+
def keyword_search(query):
|
| 45 |
+
query_tokens = tokenize(query)
|
| 46 |
+
results = []
|
| 47 |
+
|
| 48 |
+
for doc in documents:
|
| 49 |
+
doc_tokens = tokenize(doc["text"])
|
| 50 |
+
score = len(query_tokens & doc_tokens)
|
| 51 |
+
|
| 52 |
+
if score > 0:
|
| 53 |
+
results.append((doc["id"], score))
|
| 54 |
+
|
| 55 |
+
return sorted(
|
| 56 |
+
results,
|
| 57 |
+
key=lambda item: item[1],
|
| 58 |
+
reverse=True,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# 5. 加载语义模型
|
| 63 |
+
print("正在加载 Embedding 模型...")
|
| 64 |
+
model = SentenceTransformer(MODEL_NAME)
|
| 65 |
+
|
| 66 |
+
passages = [
|
| 67 |
+
"passage: " + doc["text"]
|
| 68 |
+
for doc in documents
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
doc_vectors = model.encode(
|
| 72 |
+
passages,
|
| 73 |
+
convert_to_tensor=True,
|
| 74 |
+
normalize_embeddings=True,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# 6. 语义检索
|
| 79 |
+
def semantic_search(query):
|
| 80 |
+
query_vector = model.encode(
|
| 81 |
+
"query: " + query,
|
| 82 |
+
convert_to_tensor=True,
|
| 83 |
+
normalize_embeddings=True,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
similarities = util.cos_sim(
|
| 87 |
+
query_vector, doc_vectors
|
| 88 |
+
)[0]
|
| 89 |
+
|
| 90 |
+
results = [
|
| 91 |
+
(doc["id"], float(similarities[i]))
|
| 92 |
+
for i, doc in enumerate(documents)
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
return sorted(
|
| 96 |
+
results,
|
| 97 |
+
key=lambda item: item[1],
|
| 98 |
+
reverse=True,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# 7. 混合检索:按排名融合
|
| 103 |
+
def hybrid_search(query):
|
| 104 |
+
keyword_results = keyword_search(query)
|
| 105 |
+
semantic_results = semantic_search(query)
|
| 106 |
+
|
| 107 |
+
# RRF:排名越靠前,得分越高
|
| 108 |
+
scores = {}
|
| 109 |
+
k = 60
|
| 110 |
+
|
| 111 |
+
for rank, (doc_id, _) in enumerate(
|
| 112 |
+
keyword_results, start=1
|
| 113 |
+
):
|
| 114 |
+
scores[doc_id] = (
|
| 115 |
+
scores.get(doc_id, 0) + 1 / (k + rank)
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
for rank, (doc_id, _) in enumerate(
|
| 119 |
+
semantic_results, start=1
|
| 120 |
+
):
|
| 121 |
+
scores[doc_id] = (
|
| 122 |
+
scores.get(doc_id, 0) + 1 / (k + rank)
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
results = sorted(
|
| 126 |
+
scores.items(),
|
| 127 |
+
key=lambda item: item[1],
|
| 128 |
+
reverse=True,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
return keyword_results, semantic_results, results
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# 8. 展示搜索结果
|
| 135 |
+
def display(query):
|
| 136 |
+
kw, sem, hybrid = hybrid_search(query)
|
| 137 |
+
|
| 138 |
+
print("\n" + "=" * 55)
|
| 139 |
+
print("用户问题:", query)
|
| 140 |
+
|
| 141 |
+
print("\n【关键词检索 Top 3】")
|
| 142 |
+
for doc_id, score in kw[:3]:
|
| 143 |
+
print(doc_id, "词项得分:", score)
|
| 144 |
+
|
| 145 |
+
print("\n【语义检索 Top 3】")
|
| 146 |
+
for doc_id, score in sem[:3]:
|
| 147 |
+
print(doc_id, "相似度:", round(score, 4))
|
| 148 |
+
|
| 149 |
+
print("\n【混合检索 Top 3】")
|
| 150 |
+
for doc_id, score in hybrid[:3]:
|
| 151 |
+
doc = next(
|
| 152 |
+
d for d in documents if d["id"] == doc_id
|
| 153 |
+
)
|
| 154 |
+
print(doc_id, "RRF:", round(score, 5))
|
| 155 |
+
print(" 文档:", doc["text"])
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# 9. 测试三个场景
|
| 159 |
+
questions = [
|
| 160 |
+
"如何追踪商品的进出及剩余数量?",
|
| 161 |
+
"怎样管理供应商报价和采购审批?",
|
| 162 |
+
"Spring Boot 如何编写 REST API?",
|
| 163 |
+
]
|
| 164 |
+
|
| 165 |
+
for question in questions:
|
| 166 |
+
display(question)
|
experiments/knowledge_integration_test.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
"""
|
| 3 |
+
ZKCoding Knowledge + Embedding 集成实验
|
| 4 |
+
|
| 5 |
+
使用原项目的 KnowledgeCatalog 和 SQLite Repository,
|
| 6 |
+
然后调用自己编写的 KnowledgeReranker。
|
| 7 |
+
|
| 8 |
+
运行:
|
| 9 |
+
python -m experiments.knowledge_integration_test
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import tempfile
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
from src.adapters.indexes.knowledge_sqlite import (
|
| 16 |
+
SqliteKnowledgeRepository,
|
| 17 |
+
)
|
| 18 |
+
from src.modules.knowledge.application.catalog import (
|
| 19 |
+
KnowledgeCatalog,
|
| 20 |
+
)
|
| 21 |
+
from src.modules.skill.domain.models import Actor
|
| 22 |
+
|
| 23 |
+
from experiments.knowledge_reranker import KnowledgeReranker
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
# 1. 创建测试用户
|
| 28 |
+
actor = Actor(
|
| 29 |
+
tenant_id="test-tenant",
|
| 30 |
+
user_id="developer",
|
| 31 |
+
roles=[],
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# 2. 创建临时数据库
|
| 35 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 36 |
+
folder = Path(temp_dir)
|
| 37 |
+
|
| 38 |
+
repo = SqliteKnowledgeRepository(
|
| 39 |
+
folder / "index.sqlite"
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
# 3. 复用组长已有的测试数据生成函数
|
| 43 |
+
from src.modules.knowledge.tests.test_knowledge import (
|
| 44 |
+
write_fixture,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
corpus_dir = folder / "corpus"
|
| 48 |
+
catalog_path = write_fixture(corpus_dir)
|
| 49 |
+
|
| 50 |
+
repo.import_corpus(
|
| 51 |
+
corpus_dir,
|
| 52 |
+
actor.tenant_id,
|
| 53 |
+
catalog_path,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# 4. 创建真正的 Knowledge Service
|
| 57 |
+
catalog = KnowledgeCatalog(repo)
|
| 58 |
+
|
| 59 |
+
# 5. 调用原有 SQLite FTS 检索
|
| 60 |
+
query = "inventory"
|
| 61 |
+
|
| 62 |
+
records = catalog.search(
|
| 63 |
+
actor,
|
| 64 |
+
query,
|
| 65 |
+
["fixture-java"],
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
print("\n【SQLite 检索结果】")
|
| 69 |
+
print("找到文档数量:", len(records))
|
| 70 |
+
|
| 71 |
+
for record in records:
|
| 72 |
+
print(
|
| 73 |
+
record["citation_id"],
|
| 74 |
+
record["title"],
|
| 75 |
+
record["source_url"],
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# 6. 调用我们新增的 Embedding 重排序
|
| 79 |
+
reranker = KnowledgeReranker()
|
| 80 |
+
|
| 81 |
+
ranked = reranker.rerank(
|
| 82 |
+
query,
|
| 83 |
+
records,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
print("\n【Embedding 重排序结果】")
|
| 87 |
+
|
| 88 |
+
for record in ranked:
|
| 89 |
+
print(
|
| 90 |
+
record["citation_id"],
|
| 91 |
+
"相似度:",
|
| 92 |
+
round(record["semantic_score"], 4),
|
| 93 |
+
"来源:",
|
| 94 |
+
record["source_url"],
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# 7. 验证引用信息没有丢失
|
| 98 |
+
assert len(ranked) == len(records)
|
| 99 |
+
assert all(
|
| 100 |
+
r["source_url"] for r in ranked
|
| 101 |
+
)
|
| 102 |
+
print("\n集成测试通过:搜索与重排序已连接!")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
main()
|
experiments/knowledge_reranker.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sentence_transformers import SentenceTransformer
|
| 2 |
+
|
| 3 |
+
MODEL_NAME = "intfloat/multilingual-e5-small"
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class KnowledgeReranker:
|
| 7 |
+
def __init__(self):
|
| 8 |
+
self.model = SentenceTransformer(MODEL_NAME)
|
| 9 |
+
|
| 10 |
+
def rerank(self, query, records):
|
| 11 |
+
# 没有找到文档时,直接返回空列表
|
| 12 |
+
if not records:
|
| 13 |
+
return []
|
| 14 |
+
|
| 15 |
+
# 提取现有 Knowledge Service 返回的内容
|
| 16 |
+
passages = [
|
| 17 |
+
"passage: " + r["title"] + " " + r["snippet"]
|
| 18 |
+
for r in records
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
# 将问题和文档转换为向量
|
| 22 |
+
query_vector = self.model.encode(
|
| 23 |
+
"query: " + query,
|
| 24 |
+
normalize_embeddings=True,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
document_vectors = self.model.encode(
|
| 28 |
+
passages,
|
| 29 |
+
normalize_embeddings=True,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# 计算语义相似度
|
| 33 |
+
scores = document_vectors @ query_vector
|
| 34 |
+
|
| 35 |
+
# 保留原始来源、版本、许可证等字段
|
| 36 |
+
ranked = sorted(
|
| 37 |
+
zip(records, scores),
|
| 38 |
+
key=lambda item: float(item[1]),
|
| 39 |
+
reverse=True,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
return [
|
| 43 |
+
{**record, "semantic_score": float(score)}
|
| 44 |
+
for record, score in ranked
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
# 模拟现有 Knowledge Service 已经授权返回的结果
|
| 50 |
+
records = [
|
| 51 |
+
{
|
| 52 |
+
"citation_id": "WMS-001",
|
| 53 |
+
"title": "库存管理",
|
| 54 |
+
"snippet": "商品入库、出库和库存余额管理。",
|
| 55 |
+
"source_url": "example://wms",
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"citation_id": "ERP-001",
|
| 59 |
+
"title": "采购管理",
|
| 60 |
+
"snippet": "供应商报价、订单审批和付款管理。",
|
| 61 |
+
"source_url": "example://erp",
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"citation_id": "JAVA-001",
|
| 65 |
+
"title": "Java API",
|
| 66 |
+
"snippet": "Spring Boot REST API 接口开发。",
|
| 67 |
+
"source_url": "example://java",
|
| 68 |
+
},
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
reranker = KnowledgeReranker()
|
| 72 |
+
|
| 73 |
+
result = reranker.rerank(
|
| 74 |
+
"怎样管理供应商采购报价?",
|
| 75 |
+
records,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
for item in result:
|
| 79 |
+
print(
|
| 80 |
+
item["citation_id"],
|
| 81 |
+
round(item["semantic_score"], 4),
|
| 82 |
+
item["source_url"],
|
| 83 |
+
)
|
experiments/semantic_search.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sentence_transformers import SentenceTransformer, util
|
| 2 |
+
|
| 3 |
+
# 加载支持中英文的 Embedding 模型
|
| 4 |
+
MODEL_NAME = "intfloat/multilingual-e5-small"
|
| 5 |
+
|
| 6 |
+
print("正在加载语义模型(第一次运行需要下载)...")
|
| 7 |
+
model = SentenceTransformer(MODEL_NAME)
|
| 8 |
+
|
| 9 |
+
# 模拟 ZKCoding 的 Java / ERP / WMS 知识库
|
| 10 |
+
documents = [
|
| 11 |
+
"库存管理系统记录商品入库、出库和剩余库存数量。",
|
| 12 |
+
"ERP 采购订单系统负责供应商报价、采购审批和付款流程。",
|
| 13 |
+
"Java Spring Boot 可以通过 REST Controller 实现 HTTP API。",
|
| 14 |
+
"设备运维系统负责设备巡检、维修工单及故障记录。",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
# E5 模型使用 passage: 和 query: 前缀
|
| 18 |
+
passages = ["passage: " + doc for doc in documents]
|
| 19 |
+
document_embeddings = model.encode(
|
| 20 |
+
passages,
|
| 21 |
+
convert_to_tensor=True,
|
| 22 |
+
normalize_embeddings=True,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
questions = [
|
| 26 |
+
"如何追踪商品的进出及剩余数量?",
|
| 27 |
+
"怎样管理供应商的报价和采购流程?",
|
| 28 |
+
"Spring Boot 如何编写接口?",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
for question in questions:
|
| 32 |
+
query_embedding = model.encode(
|
| 33 |
+
"query: " + question,
|
| 34 |
+
convert_to_tensor=True,
|
| 35 |
+
normalize_embeddings=True,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
scores = util.cos_sim(
|
| 39 |
+
query_embedding,
|
| 40 |
+
document_embeddings,
|
| 41 |
+
)[0]
|
| 42 |
+
|
| 43 |
+
best_index = int(scores.argmax())
|
| 44 |
+
|
| 45 |
+
print("\n问题:", question)
|
| 46 |
+
print("最相关文档:", documents[best_index])
|
| 47 |
+
print("相似度:", round(float(scores[best_index]), 4))
|
experiments/skill_knowledge_router.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ZKCoding V0.1
|
| 3 |
+
Skill + Knowledge 智能推荐原型
|
| 4 |
+
|
| 5 |
+
运行:
|
| 6 |
+
python experiments/skill_knowledge_router.py
|
| 7 |
+
|
| 8 |
+
运行自测:
|
| 9 |
+
python experiments/skill_knowledge_router.py --self-test
|
| 10 |
+
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
# 1. Demo 中现有的 Skill
|
| 16 |
+
SKILLS = {
|
| 17 |
+
"general": "普通对话(不执行工具)",
|
| 18 |
+
"erp": "ERP 订单助手",
|
| 19 |
+
"wms": "WMS 库存助手",
|
| 20 |
+
"device": "设备工单助手",
|
| 21 |
+
"java_erp": "Java 编程 · ERP 采购报价",
|
| 22 |
+
"java_wms": "Java 编程 · WMS 库存流水",
|
| 23 |
+
"java_device": "Java 编程 · 设备工单与巡检",
|
| 24 |
+
"java_calculator": "Java 编程 · 网页计算器",
|
| 25 |
+
"java_pdf": "Java 编程 · PDF读取与解析",
|
| 26 |
+
"verified_erp": "Java 编程 · ERP 采购报价 · 已验证源码技能",
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# 2. Demo 中现有的 Knowledge
|
| 31 |
+
KNOWLEDGE = {
|
| 32 |
+
"rules": "Java 编码规约",
|
| 33 |
+
"basics": "Java 基础知识",
|
| 34 |
+
"integration": "Java 集成知识",
|
| 35 |
+
"erp": "ERP 订单知识库",
|
| 36 |
+
"wms": "WMS 库存知识库",
|
| 37 |
+
"device": "设备工单知识库",
|
| 38 |
+
"sap": "SAP 接口参考",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# 3. 按业务领域整理特征词
|
| 43 |
+
# 分数越高,说明该词越有辨识度
|
| 44 |
+
DOMAIN_WORDS = {
|
| 45 |
+
"erp": {
|
| 46 |
+
"erp": 4,
|
| 47 |
+
"采购报价": 5,
|
| 48 |
+
"采购订单": 5,
|
| 49 |
+
"供应商": 4,
|
| 50 |
+
"采购": 3,
|
| 51 |
+
"报价": 3,
|
| 52 |
+
"审批": 2,
|
| 53 |
+
"收货": 2,
|
| 54 |
+
"付款": 2,
|
| 55 |
+
"订单": 1,
|
| 56 |
+
},
|
| 57 |
+
"wms": {
|
| 58 |
+
"wms": 4,
|
| 59 |
+
"库存流水": 5,
|
| 60 |
+
"库存": 4,
|
| 61 |
+
"仓库": 3,
|
| 62 |
+
"入库": 4,
|
| 63 |
+
"出库": 4,
|
| 64 |
+
"盘点": 3,
|
| 65 |
+
"库存余额": 5,
|
| 66 |
+
"商品进出": 3,
|
| 67 |
+
"剩余数量": 2,
|
| 68 |
+
"sku": 4,
|
| 69 |
+
},
|
| 70 |
+
"device": {
|
| 71 |
+
"设备运维": 5,
|
| 72 |
+
"设备巡检": 5,
|
| 73 |
+
"设备工单": 5,
|
| 74 |
+
"巡检": 4,
|
| 75 |
+
"维修": 3,
|
| 76 |
+
"工单": 3,
|
| 77 |
+
"运维": 3,
|
| 78 |
+
"故障": 2,
|
| 79 |
+
"设备": 2,
|
| 80 |
+
},
|
| 81 |
+
"calculator": {
|
| 82 |
+
"计算器": 5,
|
| 83 |
+
"网页计算器": 6,
|
| 84 |
+
"四则运算": 4,
|
| 85 |
+
},
|
| 86 |
+
"pdf": {
|
| 87 |
+
"pdf": 5,
|
| 88 |
+
"pdfbox": 5,
|
| 89 |
+
"文档解析": 4,
|
| 90 |
+
"文件解析": 3,
|
| 91 |
+
"提取pdf": 5,
|
| 92 |
+
},
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# 4. 判断用户是否需要生成代码
|
| 97 |
+
CODING_WORDS = [
|
| 98 |
+
"帮我写", "写一个", "生成代码",
|
| 99 |
+
"编写代码", "开发一个", "实现一个",
|
| 100 |
+
"帮我开发", "创建一个", "搭建一个",
|
| 101 |
+
"修改代码", "生成java", "写java",
|
| 102 |
+
"java项目", "java程序", "java网站",
|
| 103 |
+
"spring boot项目", "编程实现",
|
| 104 |
+
"开发", "编写", "生成代码",
|
| 105 |
+
"实现", "写代码", "构建",
|
| 106 |
+
]
|
| 107 |
+
|
| 108 |
+
# Java 技术问题,但不一定需要执行编程 Skill
|
| 109 |
+
JAVA_WORDS = [
|
| 110 |
+
"java", "spring", "spring boot", "maven",
|
| 111 |
+
"jdk", "junit", "jdbc", "controller",
|
| 112 |
+
"rest api", "接口", "类名", "方法名",
|
| 113 |
+
]
|
| 114 |
+
|
| 115 |
+
INTEGRATION_WORDS = [
|
| 116 |
+
"api", "rest", "http", "json", "maven",
|
| 117 |
+
"依赖", "文件解析", "pdfbox",
|
| 118 |
+
"集成", "接口对接", "jdbc",
|
| 119 |
+
]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def get_domain_scores(question):
|
| 123 |
+
"""给每个业务领域打分。"""
|
| 124 |
+
text = question.lower()
|
| 125 |
+
scores = {}
|
| 126 |
+
|
| 127 |
+
for domain, words in DOMAIN_WORDS.items():
|
| 128 |
+
score = 0
|
| 129 |
+
|
| 130 |
+
for word, weight in words.items():
|
| 131 |
+
if word.lower() in text:
|
| 132 |
+
score += weight
|
| 133 |
+
|
| 134 |
+
scores[domain] = score
|
| 135 |
+
|
| 136 |
+
return scores
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def recommend(question):
|
| 140 |
+
"""根据问题推荐 Skill 和 Knowledge。"""
|
| 141 |
+
|
| 142 |
+
text = question.strip().lower()
|
| 143 |
+
|
| 144 |
+
if not text:
|
| 145 |
+
return {
|
| 146 |
+
"skill": None,
|
| 147 |
+
"knowledge": [],
|
| 148 |
+
"domain": None,
|
| 149 |
+
"confidence": "低",
|
| 150 |
+
"reasons": ["请先输入需求"],
|
| 151 |
+
"needs_confirmation": True,
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
scores = get_domain_scores(text)
|
| 155 |
+
|
| 156 |
+
# 找到最可能的业务领域
|
| 157 |
+
ranked = sorted(
|
| 158 |
+
scores,
|
| 159 |
+
key=lambda name: scores[name],
|
| 160 |
+
reverse=True,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
domain = ranked[0] if scores[ranked[0]] > 0 else None
|
| 164 |
+
top_score = scores[domain] if domain else 0
|
| 165 |
+
|
| 166 |
+
is_coding = any(
|
| 167 |
+
word in text for word in CODING_WORDS
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
is_java = any(
|
| 171 |
+
word in text for word in JAVA_WORDS
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
is_integration = any(
|
| 175 |
+
word in text for word in INTEGRATION_WORDS
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
reasons = []
|
| 179 |
+
|
| 180 |
+
# 5. 推荐 Skill
|
| 181 |
+
skill = SKILLS["general"]
|
| 182 |
+
|
| 183 |
+
if is_coding:
|
| 184 |
+
coding_map = {
|
| 185 |
+
"erp": "java_erp",
|
| 186 |
+
"wms": "java_wms",
|
| 187 |
+
"device": "java_device",
|
| 188 |
+
"calculator": "java_calculator",
|
| 189 |
+
"pdf": "java_pdf",
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
if domain in coding_map:
|
| 193 |
+
skill = SKILLS[coding_map[domain]]
|
| 194 |
+
reasons.append(
|
| 195 |
+
"识别为编程任务,推荐对应 Java 编程 Skill"
|
| 196 |
+
)
|
| 197 |
+
else:
|
| 198 |
+
reasons.append(
|
| 199 |
+
"识别到编程需求,但没有足够信息匹配具体 Skill"
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
elif domain in ("erp", "wms", "device"):
|
| 203 |
+
skill = SKILLS[domain]
|
| 204 |
+
reasons.append(
|
| 205 |
+
"识别为业务查询或业务操作,推荐业务助手"
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
else:
|
| 209 |
+
reasons.append(
|
| 210 |
+
"暂不需要执行特定 Skill,使用普通对话"
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
# 6. 推荐 Knowledge
|
| 214 |
+
knowledge = []
|
| 215 |
+
|
| 216 |
+
def add_knowledge(key):
|
| 217 |
+
name = KNOWLEDGE[key]
|
| 218 |
+
if name not in knowledge:
|
| 219 |
+
knowledge.append(name)
|
| 220 |
+
|
| 221 |
+
if is_coding:
|
| 222 |
+
add_knowledge("rules")
|
| 223 |
+
reasons.append("编程任务需要参考 Java 编码规约")
|
| 224 |
+
|
| 225 |
+
if is_java:
|
| 226 |
+
add_knowledge("basics")
|
| 227 |
+
|
| 228 |
+
if is_integration:
|
| 229 |
+
add_knowledge("integration")
|
| 230 |
+
|
| 231 |
+
# 同时涉及多个业务领域时,允许推荐多个知识库
|
| 232 |
+
for name in ("erp", "wms", "device"):
|
| 233 |
+
if scores[name] > 0:
|
| 234 |
+
add_knowledge(name)
|
| 235 |
+
|
| 236 |
+
if "sap" in text:
|
| 237 |
+
add_knowledge("sap")
|
| 238 |
+
reasons.append("检测到 SAP 接口相关需求")
|
| 239 |
+
|
| 240 |
+
# 7. 可复用的已验证源码技能
|
| 241 |
+
if (
|
| 242 |
+
domain == "erp"
|
| 243 |
+
and is_coding
|
| 244 |
+
and any(
|
| 245 |
+
word in text
|
| 246 |
+
for word in ["复用", "已验证", "已有源码"]
|
| 247 |
+
)
|
| 248 |
+
):
|
| 249 |
+
skill = SKILLS["verified_erp"]
|
| 250 |
+
reasons.append(
|
| 251 |
+
"用户希望复用已验证的 ERP 源码技能"
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
# 8. 判断推荐是否需要进一步确认
|
| 255 |
+
tied = (
|
| 256 |
+
domain is not None
|
| 257 |
+
and sum(
|
| 258 |
+
1 for score in scores.values()
|
| 259 |
+
if score == top_score
|
| 260 |
+
) > 1
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
if domain is None:
|
| 264 |
+
confidence = "低"
|
| 265 |
+
elif tied or top_score < 3:
|
| 266 |
+
confidence = "低"
|
| 267 |
+
elif top_score < 6:
|
| 268 |
+
confidence = "中"
|
| 269 |
+
else:
|
| 270 |
+
confidence = "高"
|
| 271 |
+
|
| 272 |
+
needs_confirmation = (
|
| 273 |
+
confidence != "高"
|
| 274 |
+
or (is_coding and domain is None)
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
# 目前置信度仅基于规则分数,不是统计概率
|
| 278 |
+
return {
|
| 279 |
+
"skill": skill,
|
| 280 |
+
"knowledge": knowledge,
|
| 281 |
+
"domain": domain,
|
| 282 |
+
"confidence": confidence,
|
| 283 |
+
"reasons": reasons,
|
| 284 |
+
"needs_confirmation": needs_confirmation,
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def show_result(result):
|
| 289 |
+
"""展示推荐结果。"""
|
| 290 |
+
|
| 291 |
+
print("\n========== ZKCoding 推荐结果 ==========")
|
| 292 |
+
print("Skill:", result["skill"] or "暂无")
|
| 293 |
+
print(
|
| 294 |
+
"Knowledge:",
|
| 295 |
+
"、".join(result["knowledge"]) or "暂无推荐",
|
| 296 |
+
)
|
| 297 |
+
print("匹配领域:", result["domain"] or "未识别")
|
| 298 |
+
print("规则匹配强度:", result["confidence"])
|
| 299 |
+
|
| 300 |
+
print("\n推荐原因:")
|
| 301 |
+
for reason in result["reasons"]:
|
| 302 |
+
print("-", reason)
|
| 303 |
+
|
| 304 |
+
print("\n注意:建议用户确认后再执行。")
|
| 305 |
+
print("=======================================\n")
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def run_tests():
|
| 309 |
+
"""简单自测,不调用任何模型。"""
|
| 310 |
+
|
| 311 |
+
cases = [
|
| 312 |
+
(
|
| 313 |
+
"帮我用 Java 开发 ERP 采购报价系统",
|
| 314 |
+
"java_erp",
|
| 315 |
+
"erp",
|
| 316 |
+
),
|
| 317 |
+
(
|
| 318 |
+
"帮我写一个 WMS 库存流水接口",
|
| 319 |
+
"java_wms",
|
| 320 |
+
"wms",
|
| 321 |
+
),
|
| 322 |
+
(
|
| 323 |
+
"帮我开发设备巡检工单系统",
|
| 324 |
+
"java_device",
|
| 325 |
+
"device",
|
| 326 |
+
),
|
| 327 |
+
(
|
| 328 |
+
"帮我开发一个网页计算器",
|
| 329 |
+
"java_calculator",
|
| 330 |
+
"calculator",
|
| 331 |
+
),
|
| 332 |
+
(
|
| 333 |
+
"帮我开发一个 PDF 解析程序",
|
| 334 |
+
"java_pdf",
|
| 335 |
+
"pdf",
|
| 336 |
+
),
|
| 337 |
+
(
|
| 338 |
+
"查询采购订单的付款状态",
|
| 339 |
+
"erp",
|
| 340 |
+
"erp",
|
| 341 |
+
),
|
| 342 |
+
(
|
| 343 |
+
"查询仓库库存余额",
|
| 344 |
+
"wms",
|
| 345 |
+
"wms",
|
| 346 |
+
),
|
| 347 |
+
(
|
| 348 |
+
"查询设备维修工单",
|
| 349 |
+
"device",
|
| 350 |
+
"device",
|
| 351 |
+
),
|
| 352 |
+
]
|
| 353 |
+
|
| 354 |
+
success = 0
|
| 355 |
+
|
| 356 |
+
for question, expected_skill, expected_domain in cases:
|
| 357 |
+
result = recommend(question)
|
| 358 |
+
expected_name = SKILLS[expected_skill]
|
| 359 |
+
|
| 360 |
+
correct = (
|
| 361 |
+
result["skill"] == expected_name
|
| 362 |
+
and result["domain"] == expected_domain
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
print("问题:", question)
|
| 366 |
+
print("结果:", "PASS" if correct else "FAIL")
|
| 367 |
+
print("推荐:", result["skill"], "\n")
|
| 368 |
+
|
| 369 |
+
if correct:
|
| 370 |
+
success += 1
|
| 371 |
+
|
| 372 |
+
print(f"自测结果: {success}/{len(cases)}")
|
| 373 |
+
return success == len(cases)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
if __name__ == "__main__":
|
| 377 |
+
if "--self-test" in sys.argv:
|
| 378 |
+
if not run_tests():
|
| 379 |
+
sys.exit(1)
|
| 380 |
+
else:
|
| 381 |
+
while True:
|
| 382 |
+
question = input(
|
| 383 |
+
"请输入需求(输入 exit 退出):"
|
| 384 |
+
).strip()
|
| 385 |
+
|
| 386 |
+
if question.lower() == "exit":
|
| 387 |
+
break
|
| 388 |
+
|
| 389 |
+
result = recommend(question)
|
| 390 |
+
show_result(result)
|