Back to blog
Technical Practice · Vortap 团队

用 Vortap Embeddings 做中文语义搜索:RAG 应用实战

Embeddings + 向量搜索是实现 RAG(检索增强生成)的核心。本文用 Vortap API + BGE-M3 从零搭建中文知识库搜索。

This article is currently available in Chinese only.

用 Vortap Embeddings 做中文语义搜索

RAG(Retrieval-Augmented Generation)是 2026 年最热门的 AI 应用模式。它的核心是用 Embeddings 模型将文档转化为向量,再用语义搜索找到最相关的内容。

Vortap 提供 BGE-M3 等嵌入模型,兼容 OpenAI 格式。

整体流程

  1. 文档分块 → 生成 Embeddings → 存入向量库
  2. 用户提问 → 生成问题 Embedding → 向量搜索
  3. 搜索结果 + 问题 → LLM 生成回答

第一步:安装依赖

pip install openai numpy

第二步:生成 Embeddings

from openai import OpenAI
import numpy as np

client = OpenAI(
    api_key="YOUR_KEY",
    base_url="https://api.vortap.store/v1"
)

def get_embedding(text):
    response = client.embeddings.create(
        model="bge-m3",
        input=text
    )
    return response.data[0].embedding

# 示例
texts = [
    "DeepSeek R1 是高效的推理模型",
    "Qwen2.5 是阿里云发布的对话模型",
    "Vortap 提供一站式 API 访问"
]
embeddings = [get_embedding(t) for t in texts]
print(f"向量维度: {len(embeddings[0])}")  # 输出: 1024

第三步:简单向量搜索

def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

def search(query, texts, top_k=2):
    query_emb = get_embedding(query)
    scores = [cosine_similarity(query_emb, emb) for emb in embeddings]
    top_indices = np.argsort(scores)[-top_k:][::-1]
    return [(texts[i], scores[i]) for i in top_indices]

# 搜索测试
results = search("推理模型有哪些", texts)
for text, score in results:
    print(f"匹配度 {score:.3f}: {text}")

第四步:接入 LLM 做 RAG

def rag_ask(question, knowledge_texts):
    # 搜索相关文档
    results = search(question, knowledge_texts, top_k=2)
    context = "\n".join([t for t, _ in results])
    
    # LLM 回答
    response = client.chat.completions.create(
        model="deepseek-r1",
        messages=[
            {"role": "system", "content": "基于以下资料回答用户问题"},
            {"role": "user", "content": f"资料:{context}\n\n问题:{question}"}
        ]
    )
    return response.choices[0].message.content

answer = rag_ask("Vortap 能访问哪些模型?", texts)
print(answer)

生产环境建议

  • 使用向量数据库:Chroma、Pinecone 或 Qdrant
  • 文档分块策略:500-1000 tokens/块,重叠 100 tokens
  • 批量生成 Embeddings 提高效率
  • 考虑混合搜索(向量 + 关键词 BM25)

Vortap Embeddings 的优势

  • OpenAI 兼容:一行代码迁移
  • 中文优化:BGE-M3 对中文支持优秀
  • 价格低廉:仅为 OpenAI 的 20%

立即体验 → vortap.store