说明如何将 OpenAI Embedding 集成至 Search API Pipeline

解读

在国内企业级 Drupal 项目中,搜索体验直接影响转化率与政府门户的“好差评”。传统 Search API + Database/Solr 方案依赖倒排索引与 TF-IDF,对长尾查询、同义词、语义缺失无能为力。OpenAI Embedding(text-embedding-v2/v3)将文本转为 1536 维向量,配合向量检索(Milvus、Tencent VectorDB、阿里云 OpenSearch-向量版)可实现“以文搜意”。面试官问“如何集成”,既考察候选人对 Drupal 插件体系的熟悉度,也验证其能否把“洋技术”落地到国产化、信创、等保环境:数据不出境、网络可连代理、成本可审计。回答需覆盖“数据流、插件点、配置管理、性能、安全、合规”六要素,并给出可落地的代码级关键路径。

知识点

  1. Search API 三大插件点:datasource、processor、backend
  2. Drupal 10 服务容器与 Symfony HttpClient 的代理配置(http_proxy/https_proxy)
  3. OpenAI Embedding 接口规范:endpoint、model、max tokens 8192、返回 1536 维 float32
  4. Pipeline Processor 执行顺序:preprocess_index → preprocess_query → postprocess_results
  5. 向量数据库选型:
    • 开源:Milvus、Qdrant、Weaviate
    • 国内云:Tencent VectorDB、阿里 OpenSearch、百度 VectorDB
  6. 配置管理(CM):embedding_fields.yml 需导出到 config/sync,避免硬编码 key
  7. 等保/国密:API Key 存入 encrypt 模块 + Key 模块,国密 SM4 加密存储
  8. 性能:BigPipe 不生效于 CLI 索引,需批量 Embedding(≤100 条/请求)+ Queue API
  9. 降级策略:Embedding 服务超时 fallback 到字面量检索,保证 SLA
  10. 成本监控:记录每次 token 用量,写入 watchdog 并对接 Prometheus exporter,方便甲方审计

答案

步骤一:创建自定义 Search API Processor 模块
目录:web/modules/custom/oa_embedding_processor
oa_embedding_processor.info.yml

name: 'OpenAI Embedding Processor'
type: module
core_version_requirement: ^10 || ^11
dependencies:
  - search_api:search_api
  - key:key
  - encrypt:encrypt

步骤二:定义 Plugin
src/Plugin/search_api/processor/OpenAIEmbed.php

<?php
namespace Drupal\oa_embedding_processor\Plugin\search_api\processor;

use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Item\ItemInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Site\Settings;
use Drupal\key\KeyRepositoryInterface;

/**
 * @SearchApiProcessor(
 *   id = "openai_embed",
 *   label = @Translation("OpenAI Embedding"),
 *   description = @Translation("Generate OpenAI embedding for selected fields"),
 *   stages = {
 *     "preprocess_index" = 0,
 *   }
 * )
 */
class OpenAIEmbed extends ProcessorPluginBase {
  protected KeyRepositoryInterface $keyRepo;
  public function __construct(array $configuration, $plugin_id, $plugin_definition, KeyRepositoryInterface $key_repo) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->keyRepo = $key_repo;
  }
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container->get('key.repository'));
  }
  public function preprocessIndexItems(array $items) {
    $client = \Drupal::httpClient();
    $api_key = $this->keyRepo->getKey('openai_api_key')->getKeyValue();
    $texts = [];
    foreach ($items as $item) {
      $text = strip_tags($this->concatFields($item));
      if (mb_strlen($text) > 20) $texts[$item->getId()] = $text;
    }
    if (!$texts) return;
    // 国内代理出口
    $proxy = Settings::get('openai_proxy') ?: 'http://proxy.corp.com:7890';
    $response = $client->post('https://api.openai.com/v1/embeddings', [
      'proxy' => $proxy,
      'headers' => [
        'Authorization' => 'Bearer ' . $api_key,
        'Content-Type' => 'application/json',
      ],
      'json' => [
        'model' => 'text-embedding-v3',
        'input' => array_values($texts),
      ],
      'timeout' => 15,
    ]);
    $body = json_decode((string)$response->getBody(), TRUE);
    $embeddings = $body['data'] ?? [];
    foreach ($embeddings as $idx => $vec) {
      $id = array_keys($texts)[$idx];
      $items[$id]->setField('embedding_vector', $vec['embedding']);
    }
  }
  private function concatFields(ItemInterface $item): string {
    $fields = $this->getConfiguration()['fields'] ?? ['title', 'body'];
    $out = [];
    foreach ($fields as $f) {
      if ($v = $item->getField($f)) $out[] = $v->getValues()[0] ?? '';
    }
    return implode(' ', $out);
  }
}

步骤三:新建 Backend 插件(基于 Solr 扩展)
在自定义 search_api_solr_embed 模块中继承 SolrBackend,重写 search() 方法:

  1. 将用户查询文本同样走 Embedding 得到向量 q_vec
  2. 使用 Solr 的 Vector Search Plugin(需 core 9.3+ 加载 solr-vec jar)
  3. 构造 KNN 查询 {!knn f=embedding_vector topK=100} 并附加过滤条件
  4. 返回 Search API Result 集

步骤四:配置导出

drush config-export -y

确保 key.config_override 中 openai_api_key 指向 encrypt 实体,满足等保要求。

步骤五:批量索引与监控

drush queue-run search_api_indexing --time-limit=300

日志中记录 token 用量:

\Drupal::logger('oa_embedding')->info('Tokens used: @t', ['@t' => array_sum(array_column($body['usage'], 'total_tokens'))]);

步骤六:前端降级
若 Embedding 服务返回非 200,则捕获异常并回退到原始 Solr 查询,保证用户无感知。

拓展思考

  1. 国产化替代:若甲方要求“去 OpenAI”,可无缝切换至百度 Text2Vec-V5、阿里 DashScope,仅需修改 endpoint 与维度(百度 768 维),Processor 插件无需换。
  2. 多语言场景:Drupal 的 LanguageManager 可在 Processor 中根据 $item->getLanguage() 调用不同 Embedding 模型,避免中英混排造成语义漂移。
  3. 实时性:对于评论、UGC 增量,可结合 Queue API + Laravel Horizon(Drupal 模块 horizon)做异步 Embedding,保证索引延迟 <5s。
  4. 权限过滤:向量检索结果仍需经过 Drupal 实体访问检查,可在 Backend 的 postprocess_results 阶段调用 $item->getEntity()->access('view'),防止未授权内容泄露。
  5. 成本优化:v3 模型支持 dimensions=512 参数,可在配置页面提供下拉选项,让甲方在“精度 vs 成本”间权衡;同时利用 Redis 缓存已计算向量,减少 30% 重复请求。