首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Symfony AI Store!PHP 中 RAG 缺失的一环

Symfony AI Store!PHP 中 RAG 缺失的一环

作者头像
Tinywan
发布2026-07-01 13:46:41
发布2026-07-01 13:46:41
1070
举报
文章被收录于专栏:开源技术小栈开源技术小栈

前端

多年来,PHP 开发者只能在稍远处观看 AI 革命的展开。我们要么拼凑 Python 微服务,要么艰难地直接调用 OpenAI 的原始 API,或者依赖那些一有小版本更新就崩溃的实验性库。

随着 Symfony 7.4 的发布以及 Symfony AI Initiative 的逐渐成熟,我们终于拥有了构建 AI 原生应用的“第一公民”支持。虽然 symfony/ai-platform 负责处理聊天模型,但对业务应用来说真正改变游戏规则的是 symfony/ai-store

这个组件正是 PHP 中 Retrieval-Augmented Generation (RAG) 的核心支柱。它将向量数据库的复杂性(无论是 RedisPostgreSQL(使用 pgvector)还是 Elasticsearch)抽象成了一个干净、Symfony 风格的接口。

本文将深入探讨。我们将使用 symfony/ai-storeSymfony 7.4,结合 PHP 8.4 的最新特性,构建一个知识库搜索引擎。

为什么 symfony/ai-store 很重要

在开始写代码之前,我们先来理解整体架构。像 GPT-4 这样的大型语言模型(LLM)非常强大,但存在两个致命缺陷:

  1. 1. 幻觉(Hallucination):它们会凭空编造内容。
  2. 2. 健忘症(Amnesia):它们不知道你的私有业务数据。

RAG 通过“用你的数据 grounding AI”来解决这个问题。你把文档或产品信息转换成“向量”(代表语义的数字列表)并存储起来。当用户提问时,找到最相似的向量,把它们喂给 AI。

symfony/ai-store 提供的正是这个中间步骤的标准接口:向量存储(Vector Store)

安装与设置

我们将安装 AI Bundle,它包含了 Store 组件并简化了配置。我们还需要一个传输层(transport)。本教程使用 Doctrine + PostgreSQL(pgvector),这是 Symfony 开发者最常见的组合。

代码语言:javascript
复制
composer require symfony/ai-bundle symfony/ai-postgres-store

请确保你有一个已启用 vector 扩展的 PostgreSQL 实例。

检查 bundle 是否激活,以及 store 相关命令是否可用:

代码语言:javascript
复制
php bin/console list ai

你应该能看到类似 ai:store:setup 的命令。

配置

在 Symfony 7.4 中,我们更倾向于显式配置。打开 config/packages/ai.yaml 文件。

我们将定义一个使用 Doctrine 传输的默认 store。

代码语言:javascript
复制
# config/packages/ai.yaml
ai:
    platform:
        gemini:
            api_key: '%env(GEMINI_API_KEY)%'
        openai:
            api_key: '%env(OPENAI_API_KEY)%'

    agent:
        default:
            platform: 'ai.platform.gemini'
            model: 'gemini-2.5-pro'
        openai:
            platform: 'ai.platform.openai'
            model: 'text-embedding-3-small'

    vectorizer:
        default:
            platform: 'ai.platform.openai'
            model: 'text-embedding-3-small'

    store:
        postgres:
            default:
                table_name: 'tb_symfony_vector'

        memory:
            default:

    message_store:
        cache:
            default:
                service: 'cache.app'

数据库迁移

symfony/ai-postgres-store 包允许我们自动生成 schema。

代码语言:javascript
复制
php bin/console ai:store:setup ai.store.postgres.default

此命令会与你的数据库交互,创建必要的表(例如 vector_documents),并使用正确的 vector 列类型。

在生产环境中,建议使用 Doctrine Migrationsai:store:setup 命令非常适合快速原型,但在 CI/CD 流水线中,应生成一个执行启用扩展和创建表的 SQL 的迁移。

核心概念:Document

Store 组件不会直接保存你复杂的 Doctrine 实体。它保存的是 Document。Document 是一个简单的 DTO,包含:

  1. 1. ID:唯一标识符
  2. 2. Content:AI 将要阅读的实际文本
  3. 3. Metadata:任意键值对数组,用于过滤(例如 author_id、created_at)
  4. 4. Vectors:计算出的嵌入向量(自动处理)

构建索引服务(Ingestion Service)

我们来创建一个服务,将博客文章(或其他实体)转换为 Document 并保存到 store 中。

这里使用 PHP 8.4 的属性(attribute)进行依赖注入。

代码语言:javascript
复制
namespace App\Service;

use App\Entity\BlogPost;
use Symfony\AI\Platform\Vector\VectorInterface;
use Symfony\AI\Store\Document\Metadata;
use Symfony\AI\Store\Document\VectorDocument;
use Symfony\AI\Store\Document\VectorizerInterface;
use Symfony\AI\Store\StoreInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

readonly class KnowledgeBaseIndexer
{
    public function __construct(
        #[Autowire(service: 'ai.store.postgres.default')]
        private StoreInterface $store,
        #[Autowire(service: 'ai.vectorizer.default')]
        private VectorizerInterface $vectorizer
    ) {}

    public function indexBlogPost(BlogPost $post): void
    {
        $content = sprintf(
            "Title: %s\n\n%s",
            $post->getTitle(),
            $post->getContent()
        );

        $vector = $this->vectorizer->vectorize($content);

        if ($vector instanceof VectorInterface) {
            $document = new VectorDocument(
                id: $post->getId(),
                vector: $vector,
                metadata: new Metadata([
                    'type' => 'blog_post',
                    'content' => $content,
                    'author_id' => $post->getAuthor()->getId(),
                    'published_at' => $post->getCreatedAt()->format('Y-m-d'),
                ])
            );

            $this->store->add($document);
        }
    }
}

构建检索服务(Retrieval Service)

现在进入最神奇的部分:根据用户问题找到相关博客文章。

代码语言:javascript
复制
namespace App\Service;

use Symfony\AI\Store\Document\VectorizerInterface;
use Symfony\AI\Store\StoreInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

readonly class KnowledgeBaseSearch
{
    public function __construct(
        #[Autowire(service: 'ai.store.postgres.default')]
        private StoreInterface $store,
        #[Autowire(service: 'ai.vectorizer.default')]
        private VectorizerInterface $vectorizer,
    ) {}

    /**
     * @return array<int, string> 相关内容片段列表
     */
    public function search(string $userQuery, int $limit = 3): array
    {
        $vector = $this->vectorizer->vectorize($userQuery);

        $results = $this->store->query(
            $vector,
            [
                'limit' => $limit,
                'where' => "metadata->>'type' = :type",
                'params' => ['type' => 'blog_post'],
            ]
        );

        $answers = [];

        foreach ($results as $result) {
            if ($result->score < 0.7) {
                continue;
            }
            $answers[] = $result->metadata['content'];
        }

        return $answers;
    }
}

整合:RAG Controller

最后,将其接入一个控制器,使用检索到的数据生成答案。

代码语言:javascript
复制
namespace App\Controller;

use App\Service\KnowledgeBaseSearch;
use Symfony\AI\Platform\Message\Message;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\AI\Chat\ChatInterface;

#[Route('/api/ai')]
class AssistantController extends AbstractController
{
    public function __construct(
        private KnowledgeBaseSearch $searchService,
        private ChatInterface $chat,
    ) {}

    #[Route('/ask', methods: ['POST'])]
    public function ask(Request $request): JsonResponse
    {
        $question = $request->getPayload()->get('question');

        $contextDocuments = $this->searchService->search($question);

        $contextString = implode("\n---\n", $contextDocuments);

        $systemPrompt = <<<PROMPT
You are a helpful assistant for our company blog.
Answer the user's question based ONLY on the context provided below.
If the answer is not in the context, say "I don't know."

Context:
$contextString
PROMPT;

        $this->chat->initiate(
            new MessageBag(Message::forSystem($systemPrompt))
        );

        $response = $this->chat->submit(
            Message::ofUser($question)
        );

        return $this->json([
            'answer' => $response->getContent(),
            'sources' => count($contextDocuments)
        ]);
    }
}

高级配置:多 Store 支持

在真实的企业应用中,你可能需要为不同类型的数据使用不同的 store(例如 products_store vs documentation_store),或者使用不同的后端(Redis 用于热会话记忆,Postgres 用于长期知识)。

Symfony 7.4 通过 bind 或 target 属性让这变得非常简单。

config/packages/ai.yaml 示例:

代码语言:javascript
复制
ai:
    store:
        postgres:
            default:
                table_name: 'tb_symfony_vector'

        memory:
            default:

性能优化模式:使用 Messenger 解耦索引

前面我们是立即索引博客文章。在生产环境中,这是一个性能瓶颈。

调用 OpenAI(或其他 LLM 提供商)生成嵌入向量涉及 HTTP 请求,耗时可能从 200ms 到几秒不等。如果你在编辑点击“保存”时同步执行,浏览器会卡住;如果 API 宕机,整个应用都会报错。

解决方案是使用 Symfony Messenger 解耦索引。我们派发一个轻量消息,只包含内容的 ID,让后台 worker 异步完成嵌入和向量存储。

创建消息

遵循“Thin Message”模式:永远不要在消息中传递完整的实体或大段文本,只传递标识符。

代码语言:javascript
复制
namespace App\Messenger\Message;

use Symfony\Component\Uid\Uuid;

readonly class IndexBlogPostMessage
{
    public function __construct(
        public Uuid $blogPostId,
    ) {}
}

创建处理器(Handler)

处理器负责从数据库重新获取实体,并交给前面定义的 KnowledgeBaseIndexer

代码语言:javascript
复制
namespace App\Messenger\Handler;

use App\Messenger\Message\IndexBlogPostMessage;
use App\Repository\BlogPostRepository;
use App\Service\KnowledgeBaseIndexer;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
readonly class IndexBlogPostHandler
{
    public function __construct(
        private BlogPostRepository $repository,
        private KnowledgeBaseIndexer $indexer,
    ) {}

    public function __invoke(IndexBlogPostMessage $message): void
    {
        $post = $this->repository->find($message->blogPostId);

        if (!$post) {
            return;
        }

        $this->indexer->indexBlogPost($post);
    }
}

派发消息

现在修改你的控制器(或事件监听器),改为派发消息而不是直接调用索引器。

代码语言:javascript
复制
namespace App\Controller\Admin;

use App\Entity\BlogPost;
use App\Messenger\Message\IndexBlogPostMessage;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;

class BlogAdminController extends AbstractController
{
    public function __construct(
        private MessageBusInterface $bus,
    ) {}

    #[Route('/admin/post/{id}/publish', methods: ['POST'])]
    public function publish(BlogPost $post): Response
    {
        // ... (你现有的保存/发布逻辑) ...

        // 改为异步派发
        $this->bus->dispatch(new IndexBlogPostMessage($post->getId()));

        return $this->json(['status' => 'published', 'job_id' => 'queued']);
    }
}

总结

symfony/ai-store 填补了 PHP 生态在生产级 RAG 应用中的关键空白。它提供了类型安全、配置驱动、可扩展的向量存储抽象,让 Symfony 开发者能够以原生方式构建可靠的 AI 增强应用,而无需依赖外部微服务或脆弱的第三方包。

结合 symfony/ai-platformMessenger,你现在拥有了一条完整的 PHP 原生 AI 管道:从内容摄入 → 向量存储 → 语义检索 → 生成回答。

欢迎在 Symfony 7.4+ 项目中尝试它,并加入 Symfony AI Initiative 的讨论——PHP 的 AI 时代已经到来。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2026-02-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 开源技术小栈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前端
  • 为什么 symfony/ai-store 很重要
  • 安装与设置
  • 配置
  • 数据库迁移
  • 核心概念:Document
  • 构建索引服务(Ingestion Service)
  • 构建检索服务(Retrieval Service)
  • 整合:RAG Controller
  • 高级配置:多 Store 支持
  • 性能优化模式:使用 Messenger 解耦索引
    • 创建消息
    • 创建处理器(Handler)
    • 派发消息
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档