> For the complete documentation index, see [llms.txt](https://docs.neuron-ai.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.neuron-ai.dev/neuron-v3-zh/rag/retrieval.md).

# 检索

实现自定义检索策略

### 简介

RAG 模块有一个单独的检索组件，可让你实现不同的策略，以从外部数据源获取上下文检索。默认情况下，RAG 使用 `SimilarityRetrieval` ，它只是查询向量存储来检索文档：

```php
namespace App\Neuron;

use NeuronAI\Providers\AIProviderInterface;
use NeuronAI\RAG\Embeddings\EmbeddingsProviderInterface;
use NeuronAI\RAG\RAG;
use NeuronAI\RAG\RAG\Retrieval\RetrievalInterface;
use NeuronAI\RAG\RAG\Retrieval\SimilarityRetrieval;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class WorkoutTipsAgent extends RAG
{
    protected function retrieval(): RetrievalInterface
    {
        return new SimilarityRetrieval(
            $this->resolveVectorStore(),
            $this->resolveEmbeddingsProvider()
        );
    }
    
    protected function provider(): AIProviderInterface
    {
        // 返回一个 AI provider 实例...
    }
    
    protected function embeddings(): EmbeddingsProviderInterface
    {
        // 返回一个 embeddings provider 实例...
    }
    
    protected function vectorStore(): VectorStoreInterface
    {
        // 返回一个向量存储实例...
    }
}
```

实现 `RetrievalInterface` 你可以自由为你的 RAG 创建任何自定义检索行为。

```php
interface RetrievalInterface
{
    /**
     * 检索给定查询的相关文档。
     *
     * @return Document[]
     */
    public function retrieve(Message $query): array;
}
```

如果你正在实现自定义工作流，你可以将检索作为一个独立组件使用，以动态检索上下文数据，供你的 agentic 系统使用。

### 过滤器

```php
use NeuronAI\RAG\Retrieval\SimilarityRetrieval;
use NeuronAI\RAG\VectorStore\Filter\Filter;
use NeuronAI\RAG\VectorStore\Filter\FilterGroup;

class WorkoutTipsAgent extends RAG
{
    protected function retrieval(): RetrievalInterface
    {
        return new SimilarityRetrieval(
            $this->resolveVectorStore(),
            $this->resolveEmbeddingsProvider(),
            filters: FilterGroup::and(Filter::eq('tenant', $tenantId)),  // 可选
        );
    }
}
```

<a href="https://docs.neuron-ai.dev/neuron-v3-zh/rag/rag.md#filters" class="button primary" data-icon="arrow-right-long">关于筛选器的更多信息</a>

### 作为工具的检索

Neuron 为你提供了一个内置的 `RetrievalTool` 工具，它使 AI 代理能够在模型认为回答当前用户问题需要更多上下文时，从向量存储中执行上下文检索。它构建于 `RetrievalInterface` 之上，从而可以构建具备按需 RAG（检索增强生成）能力的代理，而不是由 RAG 组件提供的自动上下文注入。

下面是一个使用内置 `SimilarityRetrieval`:

```php
use NeuronAI\Tools\Toolkits\RetrievalTool;
use NeuronAI\RAG\Retrieval\SimilarityRetrieval;

class AgenticRAG extends Agent
{
    protected function provider(): AIProviderInterface
    {...}
    
    protected function instructions(): string
    {...}
    
    protected function tools(): array
    {
        return [
            RetrievalTool::make(
                new SimilarityRetrieval(
                    $this->vectorStore(), 
                    $this->embeddings()
                )
            ),
        ];
    }
    
    protected function vectorStore(): VectorStoreInterface
    {
        return new FileVectorStore(__DIR__);
    }
    
    protected function embeddings(): EmbeddingsProviderInterface
    {
        return new OllamaEmbeddingsProvider(
            model: 'OLLAMA_EMBEDDINGS_MODEL'
        );
    }
}
```

正如你在这个示例中所看到的，我们并没有扩展 RAG，而是使用基础的 Agent。在这个实现中，我们让模型自行决定是否需要搜索外部来源来回答用户问题。

你始终可以使用所有工具和代理方法来自定义描述、指令以及整体提示词，从而让模型按照你的用例表现。

### 语义记忆

使用 RAG，你可以启用跨线程的记忆检索。拥有多个活跃线程的用户可以看到代理记住他们过去的对话和偏好。

```php
use NeuronAI\RAG\Retrieval\SemanticMemoryRetrieval;

class MyAgent extends RAG
{
    // 定义常规的 provider()、vectorStore() 和 embeddings() 钩子。
    
    protected function retrieval(): RetrievalInterface
    {
        return new SemanticMemoryRetrieval(
            vectorStore: $this->resolveVectorStore(),
            embeddingProvider: $this->resolveEmbeddingProvider(),
            threadIds: $threadIds,
        );
    }
}
```

参数 `threadIds` 是你想要从中召回记忆的线程列表。它可以是用户所有活跃线程的完整列表，也可以是根据你的应用偏好筛选出的子集。

{% hint style="warning" %}
记得将当前线程 **`threadId`** 从召回列表中排除，否则同一会话中的消息会被重复写入代理的系统指令中。
{% endhint %}

要为当前对话启用记忆创建，你需要将 `ConversationIngestionNode` 作为退出节点，这样 RAG 就可以自动将消息存储到分配的向量存储中。

```php
use NeuronAI\RAG\Nodes\ConversationIngestionNode;

class MyAgent extends RAG
{
    // 定义常规的 provider()、vectorStore() 和 embeddings() 钩子。
    
    protected function retrieval(): RetrievalInterface
    {
        return new SemanticMemoryRetrieval(
            vectorStore: $this->resolveVectorStore(),
            embeddingProvider: $this->resolveEmbeddingProvider(),
            threadIds: $threadIds,
        );
    }
    
    protected function exitNodes(): array
    {
        return [
            // 将最后一组用户/助手对存入记忆存储
            new ConversationIngestionNode(
                vectorStore: $this->resolveVectorStore(),
                embeddingProvider: $this->resolveEmbeddingsProvider(),
                chatHistory: $this->getChatHistory(),
            )
        ];
    }
}
```

### 复合检索

`CompositeRetrieval` 允许你在一个流水线中串联多个检索任务。它按顺序调用其子组件，并合并它们的结果。每个子组件接收相同的预处理查询和每次运行必需的过滤条件。

把特定于集合的过滤条件放在那个子组件上，而不是放在共享检索范围中。共享过滤条件必须被每个子组件支持，并且绝不会被丢弃。然后 RAG 会按内容去重并运行通用后处理器。

```php
use NeuronAI\RAG\Retrieval\CompositeRetrieval;

class MyAgent extends RAG
{
    // 定义常规的 provider()、vectorStore() 和 embeddings() 钩子。
    
    protected function retrieval(): RetrievalInterface
    {
        return new CompositeRetrieval([
            new SemanticMemoryRetrieval(
                vectorStore: $this->resolveVectorStore(),
                embeddingProvider: $this->resolveEmbeddingsProvider(),
                threadIds: $authorizedThreadIds,
            ),
            new SimilarityRetrieval(
                vectorStore: $this->resolveVectorStore(),
                embeddingProvider: $this->resolveEmbeddingsProvider(),
            ),
        ]);
    }
}
```

上面的代码对两种检索策略使用了同一个向量存储，但你很可能会有两个独立的存储。你可以自由组合这些组件，以反映你的应用需求和架构。

### RAPTOR 检索

大多数检索增强模型的工作方式是将文档拆分成小块，只检索最相关的部分。然而，这种方法有一些局限性：

* **上下文丢失**：仅检索小而孤立的片段可能会错过整体，尤其是对于长上下文文档。
* **多步推理困难**：某些问题需要来自文档多个部分的信息。

**在以下情况下使用 RAPTOR：**

* 用户提出需要全面覆盖的开放式问题
* 你的领域涉及复杂主题，其中上下文与事实同样重要
* 你需要处理关于跨文档主题、趋势或关系的查询

**在以下情况下坚持使用传统 RAG：**

* 用户主要需要快速、具体的事实检索
* 处理速度和 token 效率是关键限制

在专用仓库中了解更多关于 RAPTOR 的信息：

{% embed url="<https://github.com/neuron-core/raptor-retrieval>" %}
