mcpField
M
mixedbread-search

mixedbread-search

github.com/mixedbread-ai数据与数据库1489 次安装8 周前更新
代码仓库

关于 mixedbread-search

一项使用 Mixedbread Stores API 创建和搜索托管知识库的技能,提供 Python 和 TypeScript SDK。它支持多模态检索、带引用的回答、元数据筛选和自适应 Agentic 搜索。

主要功能

  1. 01创建 Store 并上传文件
  2. 02搜索文本和多模态内容
  3. 03生成带引用的回答
  4. 04筛选和查看元数据
  5. 05使用精确匹配与 Agentic 检索

适用场景

  1. 01构建可搜索的文档集合
  2. 02查找精确标识符或短语
  3. 03生成带来源引用的问答
  4. 04结合内部文档与实时网页结果

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mixedbread-ai/skills --skill mixedbread-search

安装后在 Claude Code 中输入/mixedbread-search确认已加载。

详细介绍

Mixedbread 搜索

使用 Stores API 创建并搜索托管知识库。Stores 是多模态搜索索引,可处理 100 多种语言的文本、图像、表格、音频和视频。

文档:https://www.mixedbread.com/docs/stores/overview.md 面向 Agent 的文档:https://www.mixedbread.com/docs/llms.txt 搜索最新文档:https://www.mixedbread.com/question?q=stores&section=docs

设置

pip install mixedbread          # Python
npm install @mixedbread/sdk     # TypeScript
export MXBAI_API_KEY=your_api_key

快速入门

Python:

import os
from mixedbread import Mixedbread

mxbai = Mixedbread(api_key=os.environ["MXBAI_API_KEY"])

store = mxbai.stores.create(name="my-docs", description="Product documentation")

mxbai.stores.files.upload(
    store_identifier=store.id,
    file=open("guide.pdf", "rb"),
    metadata={"category": "guides", "version": "2.0"},
)

results = mxbai.stores.search(
    query="How does authentication work?",
    store_identifiers=["my-docs"],
    top_k=5,
)
for chunk in results.data:
    print(f"{chunk.score:.3f} | {chunk.filename}: {chunk.text[:100]}")

TypeScript:

import { Mixedbread } from '@mixedbread/sdk';
import fs from 'fs';

const mxbai = new Mixedbread({
    apiKey: process.env.MXBAI_API_KEY!,
});

const store = await mxbai.stores.create({
    name: 'my-docs',
    description: 'Product documentation',
});

await mxbai.stores.files.upload({
    storeIdentifier: store.id,
    file: fs.createReadStream('guide.pdf'),
    body: { metadata: { category: 'guides', version: '2.0' } },
});

const results = await mxbai.stores.search({
    query: 'How does authentication work?',
    store_identifiers: ['my-docs'],
    top_k: 5,
});

决策树

  • 你需要哪种检索方式?
    • 简单的关键词/语义查找 → 使用带 top_k 的标准 search()
    • 带引用的自然语言回答 → 使用 question_answering()(默认启用引用)
    • 复杂的多跳问题,或适合通过自适应语义、精确匹配、元数据和文档级探索进行检索的问题 → 使用启用了 agentic 的 search()
    • 精确的令牌/正则表达式匹配(错误代码、标识符、字面短语)→ POST /v1/stores/grep。参见grep 和分块列表。
    • 将内部文档与实时网页结合 → 将 "mixedbread/web" 添加到 store_identifiers
  • 你需要元数据过滤吗?
    • 不知道有哪些元数据 → 先调用 metadata_facets()
    • 知道字段 → 使用 all/any/none 组合器构建 filters
  • 你需要更高的相关性吗?
    • 需要 → 在 search_options 中设置 "rerank": true(使用默认模型 mixedbread-ai/mxbai-rerank-v3-listwise),或者传入配置对象:{"rerank": {"model": "...", "with_metadata": true, "top_k": 10}},以选择模型、在重排中包含元数据,或限制重排后的结果数量。
  • 你需要从文件中获取 OCR、摘要或转录文本吗?
    • 需要 → 上传文件时使用 config: {"parsing_strategy": "high_quality"}。Stores 会自动提取 OCR 文本、摘要和转录文本,无需单独解析。对于 PDF、幻灯片、Word 文档和图像,分块还会在 generated_metadata.layout 中附带逐页布局:按阅读顺序排列的每个检测到的元素,包括其边界框(页面图像像素中的 [x1, y1, x2, y2])、元素类型和 OCR 文本。
    • 不需要/仅包含文本的文档 → 默认的 parsing_strategy("fast")已足够。
  • 用户的查询语言是否与元数据字段(标题、类别、作者)重合?
    • 是 → 创建 Store 时启用 contextualization,让嵌入内容携带这些元数据。参见上下文化。
    • 否 → 保持关闭(默认设置)。
  • 你需要获取已知文件中存储的确切分块(而不是执行查询)吗?
    • 需要 → 调用 stores.files.retrieve() 并设置 return_chunks=True(或传入索引列表)。参见按文件检索分块。
    • 不需要,你想要相关性排序 → 使用 search()。
  • Store 是临时的(例如,用于 PR 审查)吗?
    • 是 → 创建时设置 expires_after 和天数限制

工作流

构建可搜索的知识库

创建 Store、上传文档并进行搜索。大多数情况下,无需轮询等待文件处理完成。只有当工作流依赖完整的批次覆盖率时(例如基准测试或召回率评估),才需要等待处理完成。

Python:

store = mxbai.stores.create(
    name="product-docs",
    description="Product documentation",
    config={"contextualization": {"with_metadata": ["title", "category"]}},
)

mxbai.stores.files.upload(
    store_identifier=store.id,
    file=open("guide.pdf", "rb"),
    metadata={"title": "Setup Guide", "category": "guides"},
)
mxbai.stores.files.upload(
    store_identifier=store.id,
    file=open("faq.md", "rb"),
    metadata={"title": "FAQ", "category": "support"},
)

results = mxbai.stores.search(
    query="How do I reset my password?",
    store_identifiers=["product-docs"],
    top_k=5,
    search_options={"rerank": True},  # file metadata is returned by default
)
for chunk in results.data:
    print(f"{chunk.score:.3f} | {chunk.filename}: {chunk.text[:100]}")

# Optional: poll store.file_counts if you need deterministic full-batch coverage (benchmarks, migrations).

TypeScript:

const store = await mxbai.stores.create({
    name: 'product-docs',
    description: 'Product documentation',
    config: { contextualization: { with_metadata: ['title', 'category'] } },
});

await mxbai.stores.files.upload({
    storeIdentifier: store.id,
    file: fs.createReadStream('guide.pdf'),
    body: { metadata: { title: 'Setup Guide', category: 'guides' } },
});
await mxbai.stores.files.upload({
    storeIdentifier: store.id,
    file: fs.createReadStream('faq.md'),
    body: { metadata: { title: 'FAQ', category: 'support' } },
});

const results = await mxbai.stores.search({
    query: 'How do I reset my password?',
    store_identifiers: ['product-docs'],
    top_k: 5,
    search_options: { rerank: true },  // file metadata is returned by default
});

// Optional: poll store.file_counts if you need deterministic full-batch coverage (benchmarks, migrations).
由过滤条件驱动的搜索

先发现可用元数据,再构建有针对性的过滤条件。

Python:

facets = mxbai.stores.metadata_facets(store_identifiers=["product-docs"])
for key, values in facets.facets.items():
    print(f"{key}: {values}")

results = mxbai.stores.search(
    query="deployment guide",
    store_identifiers=["product-docs"],
    top_k=10,
    filters={
        "all": [
            {"key": "category", "operator": "eq", "value": "guides"},
            {"key": "status", "operator": "not_eq", "value": "archived"},
        ]
    },
    search_options={"rerank": True},
)

TypeScript:

const facets = await mxbai.stores.metadataFacets({
    store_identifiers: ['product-docs'],
});
for (const [key, values] of Object.entries(facets.facets ?? {})) {
    console.log(`${key}: ${JSON.stringify(values)}`);
}

const results = await mxbai.stores.search({
    query: 'deployment guide',
    store_identifiers: ['product-docs'],
    top_k: 10,
    filters: {
        all: [
            { key: 'category', operator: 'eq', value: 'guides' },
            { key: 'status', operator: 'not_eq', value: 'archived' },
        ],
    },
    search_options: { rerank: true },
});

过滤运算符:eq、not_eq、gt、gte、lt、lte、in、not_in、like、not_like、contains、starts_with、regex。使用 all(AND)、any(OR)、none(NOT)进行组合。

网页增强搜索

将 "mixedbread/web" 添加到 store_identifiers,即可将 Store 搜索与实时网页结果结合。这是一个保留的 Store 标识符,无需设置。你也可以只搜索网页。

Python:

results = mxbai.stores.search(
    query="latest best practices",
    store_identifiers=["my-docs", "mixedbread/web"],
)

TypeScript:

const results = await mxbai.stores.search({
    query: 'latest best practices',
    store_identifiers: ['my-docs', 'mixedbread/web'],
});
上下文化

在嵌入前,将选定的文件元数据追加到分块文本中,以便与 title、category 或 author 等字段重叠的查询获得更准确的排名。在创建时通过存储的 config.contextualization 进行配置,且只影响之后上传的文件。有关模式(false / true / {"with_metadata": [...]}),请查阅 Stores 文档——获取此技能顶部链接的 llms.txt,并跳转到 Stores 配置页面。

按文件检索分块

如果已知文件(预览、导出、排查摄取问题),且不需要排序,请调用 stores.files.retrieve(),并设置 return_chunks=True(所有分块)或 return_chunks=[indices](指定 chunk_index 位置)。有关确切的请求和响应格式,请查阅 API 参考中的 “Get Store File” 端点——获取 llms.txt 并跳转到相应页面,或搜索文档。

Grep 和分块列表(REST)

目前有两个尚无专用 SDK 方法的端点——请通过 HTTP(或 SDK 的通用 post)调用:

  • POST /v1/stores/grep —— 使用 RE2 正则表达式匹配分块,而非语义搜索。查找包含字面标记、标识符、错误代码或短语的分块。请求体:pattern(正则表达式,最多 1024 个字符)、store_identifiers(必须恰好指定一个存储)、targets(默认为 ["text", "generated"]——原始分块文本与摄取时生成的 OCR 文本、转录内容和摘要)、case_sensitive(默认为 false)、top_k、filters。不支持分页——如需更多匹配结果,请增大 top_k。响应分块位于 data 下。
  • POST /v1/stores/list-chunks —— 无需搜索查询,按元数据 filters 列出分块,还可选择按元数据字段排序:sort_by: "price",或使用 ["price", false] 按降序排列(不带前缀的路径指向文件元数据,generated_metadata.* 指向分块元数据)。仅支持单个存储。
问答

获取带引用来源的生成式回答。回答中可能包含引用来源列表的 <cite i="n"/> 标签。引用(qa_options.cite)和多模态上下文(qa_options.multimodal)默认均已启用。可选顶层参数:instructions(最多 8,000 个字符),用于引导回答风格和侧重点;stream: true,用于流式传输回答。

Python:

result = mxbai.stores.question_answering(
    query="What are the rate limits?",
    store_identifiers=["my-docs"],
    top_k=10,
    search_options={"rerank": True},
)
print(result.answer)
for source in result.sources:
    print(f"  {source.filename} (score: {source.score:.3f})")

TypeScript:

const result = await mxbai.stores.questionAnswering({
    query: 'What are the rate limits?',
    store_identifiers: ['my-docs'],
    top_k: 10,
    search_options: { rerank: true },
});
console.log(result.answer);
for (const source of result.sources) {
    console.log(`  ${source.filename} (score: ${source.score.toFixed(3)})`);
}
带 Agentic 回退的问答

当问答未返回来源时,请使用 Agentic 搜索重试,以进行更深入的检索。务必再次调用 question_answering()——不要回退到原始 search(),因为这样会丢失生成的回答。

Python:

result = mxbai.stores.question_answering(
    query="Compare the pricing tiers and their feature differences",
    store_identifiers=["my-docs"],
    top_k=10,
    search_options={"rerank": True},
)

if not result.sources:
    result = mxbai.stores.question_answering(
        query="Compare the pricing tiers and their feature differences",
        store_identifiers=["my-docs"],
        top_k=10,
        search_options={"agentic": True},
    )

print(result.answer)
for source in result.sources:
    print(f"  {source.filename} (score: {source.score:.3f})")
Agentic 搜索

适用于需要多步检索的复杂问题。启用 agentic 后,检索和排序将交由 Mixedbread 托管的搜索 Agent 框架处理。它从原始查询和元数据检查开始,随后自适应地选择语义搜索、精确匹配/正则匹配、元数据筛选、语料概览以及分块或文档扩展等方式,最终提交证据排名结果。它可以并行发起多个搜索,并对多次调用中的证据去重。search() 和 question_answering() 均支持此功能。

具体的内部工具调用序列属于实现细节:不要假设生成的子查询数量固定,也不要围绕跟踪记录中的工具名称编写客户端逻辑。公开响应仍是常见的排名分块列表;question_answering() 会使用该列表生成带引用的回答。

Python:

results = mxbai.stores.search(
    query="Compare the pricing tiers and their feature differences",
    store_identifiers=["product-docs"],
    top_k=10,
    search_options={
        "rerank": True,
        "agentic": {
            "instructions": (
                "Prioritize official pricing pages over blog posts. "
                "Surface tier names, monthly cost, and included feature lists."
            ),
        }
    },
)

TypeScript:

const results = await mxbai.stores.search({
    query: 'Compare the pricing tiers and their feature differences',
    store_identifiers: ['product-docs'],
    top_k: 10,
    search_options: {
        rerank: true,
        agentic: {
            instructions:
                'Prioritize official pricing pages over blog posts. ' +
                'Surface tier names, monthly cost, and included feature lists.',
        },
    },
});
Agentic 选项
  • agentic: true — 使用默认设置启用。
  • agentic: { ... } — 使用当前生效的请求控制项:
    • instructions(字符串,最多 5000 个字符)— 提供额外的检索和排序指导。告知 Agent 哪些实体、指标、时间范围、来源类型或权威性规则很重要,以及哪些内容应忽略。顶层的 query 仍然是用户的问题。
    • strict_top_k(默认值为 false)— 要求最终提交的证据必须恰好包含 top_k 个区块。对于可能没有足够相关区块的小型或稀疏存储库,请保持此选项关闭。

托管框架会遵循顶层的 query、store_identifiers、top_k、filters 和 file_ids。filters 和 file_ids 是硬性范围约束,会通过 AND 关系应用于 Agent 发起的每次检索;而 instructions 是软性的规划和排序指导。

为兼容先前的 Agentic 实现,请求架构仍接受 max_rounds、queries_per_round 和 media_content,但托管框架目前不会转发这些请求级值。请勿用它们进行调优。目前托管 Agent 已禁用检索到的图像内容,且请求级 score_threshold 也不会被转发。

启用 agentic 后,无需使用 search_options.rewrite_query,因为托管 Agent 会自行规划查询。可以同时启用 rerank 和 Agentic 搜索;它会对 Agent 的语义搜索工具返回的结果重新排序,然后 Agent 再进行最终的证据排序。

编写良好的 Agentic instructions
  • 优先使用指令性短语(“优先考虑 X”“忽略 Y”“将 Z 视为权威来源”),而不是重述问题。
  • 指明具体的实体、字段、指标、时间范围或文档类型,让探索和排序围绕你关注的内容展开。
  • 使用顶层的 filters 或 file_ids 设置可强制执行的范围。若元数据筛选器可以表达约束,请勿依赖“只搜索 team=growth”之类的指令。
  • 将问题本身放在 query 中;将排序和规划指导放在 instructions 中。

响应格式

搜索结果(search() 返回):

response.data  # list of chunks
chunk.text       # str — the matched text
chunk.score      # float — relevance score (0–1)
chunk.filename   # str — source file name
chunk.file_id    # str — source file ID
chunk.store_id   # str — store the chunk belongs to
chunk.metadata   # dict — attached file metadata (returned by default; disable with return_metadata=False)
chunk.type       # str — chunk type (e.g. "text", "image_url")
chunk.image_url  # dict | None — image payload for image chunks
chunk.ocr_text   # str | None — OCR text for image-heavy chunks
chunk.summary    # str | None — auto-generated summary for image chunks (high_quality mode)
chunk.transcription # str | None — transcription for audio/video chunks (high_quality mode)
chunk.generated_metadata # dict | None — ingestion-derived metadata (page counts, dimensions, headings, ...)

在 high_quality 模式下,PDF、幻灯片、Word 文档和图像区块还会在 generated_metadata.layout 中提供 OCR 布局:页面图像的 width/height,以及按阅读顺序排列的 elements。每个元素都包含 bbox(以页面图像像素坐标表示的 [x1, y1, x2, y2])、type(例如 table、figure、text)和该元素的 OCR text。可利用这些信息突出显示证据区域,或将答案映射回页面上的位置。

问答结果(question_answering() 返回):

result.answer    # str — generated answer, may contain <cite i="n"/> tags
result.sources   # list of source objects
source.filename  # str
source.score     # float
source.file_id   # str
source.text      # str — the source chunk text
source.image_url # dict | None — image payload with url/format for image chunks

存储库管理

stores = mxbai.stores.list(limit=20)
for store in stores.data:
    print(store.name)

store = mxbai.stores.retrieve(store_identifier="my-docs")
print(store.file_counts)  # {"completed": 5, "in_progress": 2, "failed": 0}

mxbai.stores.delete(store_identifier="my-docs")

files = mxbai.stores.files.list(store_identifier="my-docs", limit=20)
for file in files.data:
    print(file.filename, file.status)

规则

关键规则
  • 存储库名称只能包含小写字母、数字、连字符和句点。 名称无效会导致创建失败。不得包含空格、下划线或大写字母。
  • 要对字段进行上下文处理,请使用文档规定的 {"with_metadata": [...]} 格式。 其他文档规定的模式为 true(全部元数据)和 false(不包含元数据)。支持对嵌套字段使用点号表示法。
HIGH
  • 除非完整性很重要,否则不要等待全部摄取完成。 存储会异步处理文件,处理完成的文件会随即变为可搜索状态。大多数情况下,尤其是在交互式流程中,上传后立即搜索,无需轮询。只有当工作流依赖完整的批次覆盖率时(例如基准测试、迁移或同步验证),才轮询文件状态或 file_counts。
  • 构建筛选条件前,先使用 metadata_facets()。 不要猜测元数据键——先查明实际键名。筛选键中的拼写错误会悄无声息地导致没有结果。
  • 在生产环境搜索中启用 rerank。 重排序能显著提高相关性。仅在对延迟敏感的原型开发中跳过它。
  • 使用 parsing_strategy: "high_quality" 启用自动内容提取。 在上传时的单文件配置中设置此项后,高质量模式会提取图像的 OCR 文本和摘要,以及音频和视频的转录内容。这些字段可直接用作大模型上下文。此外,它还会为 PDF、幻灯片、Word 文档和图像块填充 generated_metadata.layout,其中包含与 OCR 文本对应的各元素边界框。默认的 "fast" 策略会为内容建立索引,但不会进行这些额外提取。
  • 简单查找使用标准搜索。 Agentic 搜索会因多轮检索而增加延迟。仅在复杂的多跳问题中使用它。
MEDIUM
  • 为临时存储设置 expires_after。 PR 审查存储、演示存储和测试存储应自动过期,避免未使用的索引不断累积。
  • 每个知识领域使用一个存储,而不是每个查询使用一个。 存储是持久化索引,旨在重复使用。创建一次,多次搜索。
  • 在标准搜索中使用 score_threshold 过滤低相关性噪声。 设置 search_options: {"score_threshold": 0.3},即可在服务端排除低于最低相关性阈值的分块——无需在客户端对 chunk.score 进行后置筛选。目前,Agentic 搜索不会转发此参数。
  • 仅使用有效的 Agentic 控制项。 调整 top_k,使用 filters/file_ids 严格限定范围,并通过 agentic.instructions 引导检索。请求级别的 max_rounds、queries_per_round 和 media_content 是兼容性字段,目前不会转发到托管运行框架。
  • 使用 agentic.instructions 引导检索,而不是修改 query。 保持 query 为用户的自然语言问题。将“优先考虑 X”、“忽略 Y”、来源类型偏好和排序提示放入 search_options.agentic.instructions(最多 5000 个字符)。
  • 图像查询仅支持纯语义搜索。 将图像查询与 rerank、rewrite_query 或 agentic 结合会导致验证错误。

故障排除

症状原因解决方法
未返回结果新上传的文件仍在处理中,或存储名称/查询有误至少等一个文件处理完成后重试。对于对完整性敏感的运行,在评估结果前确认预期文件均为 completed。
未返回结果分数阈值过高降低或移除 search_options.score_threshold(或任何客户端侧阈值)。
未返回结果store_identifiers 有误确认存储名称或 ID 完全匹配。
元数据筛选没有结果键名或值有误使用 metadata_facets() 查明实际键和值。
Agentic 搜索缓慢托管式多步探索会增加模型调用和检索调用查询简单时使用标准搜索;如果最终所需分块较少,则降低 top_k;并让 agentic.instructions 更聚焦。不要尝试调整仅用于兼容的 max_rounds 或 queries_per_round。
API 密钥错误密钥无效或缺失确认已设置 MXBAI_API_KEY。请在 https://platform.mixedbread.com/platform?next=api-keys 获取密钥

评论

支持 Markdown