You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Xenova Transformers在Next.js中加载pipeline遇TypeError问题求助

解决Next.js中@xenova/transformers的TypeError问题

错误原因

你遇到的TypeError: Cannot read properties of undefined (reading 'create')错误,是因为在Next.js的RSC(React Server Components)环境顶层直接初始化依赖WebAssembly的模型。服务器端环境不支持Wasm相关API,导致模型初始化时constructSession函数无法找到所需的create方法。顶层await在RSC中会强制代码在服务器端执行,而@xenova/transformers的Wasm版本是为浏览器环境设计的,服务器端缺少必要的运行环境。

解决方案

方案1:在API路由中适配服务器端环境

将模型初始化移到POST请求处理函数内部,并禁用Wasm,使用Node.js兼容的后端:

import { pipeline } from "@xenova/transformers"

export async function POST(req) {
    try {
        // 在请求处理时初始化模型,避免顶层RSC执行问题
        const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2', {
            useWasm: false, // 服务器端禁用Wasm,使用Node.js后端
        });
        const body = await req.json();
        const query = body.query || '';
        const query_embedded = await extractor(query, { pooling: 'mean', normalize: true });
        
        // 返回生成的向量
        return new Response(JSON.stringify({ embedding: query_embedded }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' }
        });
    } catch (error) {
        console.error('处理请求出错:', error);
        return new Response(JSON.stringify({ error: error.message }), { status: 500 });
    }
}

方案2:在客户端组件中生成向量

将向量生成逻辑移到客户端组件(使用'use client'指令),利用浏览器的Wasm环境运行模型,再调用API将向量存入Pinecone:

客户端组件(生成向量)

'use client';
import { pipeline } from "@xenova/transformers";

async function generateEmbedding(query) {
    const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2', {
        useWasm: true, // 浏览器环境启用Wasm
    });
    return extractor(query, { pooling: 'mean', normalize: true });
}

export default function EmbeddingGenerator() {
    const handleSubmit = async (e) => {
        e.preventDefault();
        const query = e.target.query.value;
        if (!query) return;
        
        const embedding = await generateEmbedding(query);
        // 调用API将向量存入Pinecone
        await fetch('/api/save-pinecone', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ query, embedding })
        });
        
        alert('向量已生成并保存');
    };

    return (
        <form onSubmit={handleSubmit}>
            <input name="query" placeholder="输入问题" required />
            <button type="submit">生成向量</button>
        </form>
    );
}

API路由(存入Pinecone)

import { Pinecone } from '@pinecone-database/pinecone';

export async function POST(req) {
    const { query, embedding } = await req.json();
    const pinecone = new Pinecone({ apiKey: process.env.PINECONE_API_KEY });
    const index = pinecone.Index('你的索引名称');
    
    await index.upsert([{
        id: Date.now().toString(),
        values: embedding,
        metadata: { query }
    }]);
    
    return new Response(JSON.stringify({ success: true }), { status: 200 });
}

关键注意事项

  • 顶层await在RSC中会强制代码在服务器端执行,而Wasm依赖浏览器环境,因此要避免这种写法。
  • 服务器端运行时需禁用Wasm,依赖@xenova/transformers的Node.js后端实现;客户端则可以正常启用Wasm。

内容的提问来源于stack exchange,提问作者Salman Qurban

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 17:25:03