feat: 删除 知识库-终端 关联, 简化 prompt 配置

This commit is contained in:
2026-03-23 15:27:06 +08:00
parent 81a22a2b54
commit 89af7c17f1
23 changed files with 102 additions and 1633 deletions

View File

@@ -2,8 +2,8 @@
namespace App\Services;
use App\Models\Terminal;
use App\Models\Document;
use App\Models\KnowledgeBase;
use Illuminate\Support\Facades\Log;
class KnowledgeContextService
@@ -12,15 +12,14 @@ class KnowledgeContextService
private const TOP_K = 5;
/**
* 搜索终端关联知识库中的文档
* 搜索所有知识库中的文档
*
* @param Terminal $terminal
* @param string $query
* @return array{context: string, sources: array}
*/
public function search(Terminal $terminal, string $query): array
public function search(string $query): array
{
$knowledgeBaseIds = $terminal->knowledgeBases->pluck('id')->toArray();
$knowledgeBaseIds = KnowledgeBase::where('status', 'active')->pluck('id')->toArray();
if (empty($knowledgeBaseIds)) {
return [
@@ -30,11 +29,18 @@ class KnowledgeContextService
}
try {
// 使用 Scout/Meilisearch 原生过滤(与 DocumentSearchService 一致)
$documents = Document::search($query)
->whereIn('knowledge_base_id', $knowledgeBaseIds)
->take(self::TOP_K)
->get();
// 使用 Scout/Meilisearch 搜索并获取排名分数
$rawResults = Document::search($query, function ($meilisearch, $query, $options) use ($knowledgeBaseIds) {
$options['showRankingScore'] = true;
$filter = collect($knowledgeBaseIds)
->map(fn($id) => "knowledge_base_id = {$id}")
->implode(' OR ');
$options['filter'] = $filter;
$options['limit'] = self::TOP_K;
return $meilisearch->search($query, $options);
})->raw();
$hits = $rawResults['hits'] ?? [];
} catch (\Exception $e) {
Log::warning('Knowledge search failed', [
'query' => $query,
@@ -47,17 +53,29 @@ class KnowledgeContextService
];
}
if ($documents->isEmpty()) {
if (empty($hits)) {
return [
'context' => '',
'sources' => [],
];
}
// 取出文档 ID 并加载 Eloquent 模型
$hitIds = collect($hits)->pluck('id')->toArray();
$documents = Document::whereIn('id', $hitIds)->get()->keyBy('id');
// 构建排名分数映射
$rankingScores = collect($hits)->pluck('_rankingScore', 'id');
$context = '';
$sources = [];
foreach ($documents as $document) {
foreach ($hits as $hit) {
$document = $documents->get($hit['id']);
if (!$document) {
continue;
}
$snippet = $this->extractSnippet($document);
if (mb_strlen($context) + mb_strlen($snippet) > self::MAX_CONTEXT_LENGTH) {
@@ -66,9 +84,9 @@ class KnowledgeContextService
$context .= $snippet . "\n\n";
$sources[] = [
'id' => $document->id,
'title' => $document->title,
'knowledge_base' => $document->knowledgeBase?->name,
'id' => 'kb-doc-' . str_pad($document->id, 3, '0', STR_PAD_LEFT),
'relevance' => round($rankingScores->get($document->id, 0), 2),
];
}