# https://github.com/neuml/txtai 项目说明书

生成时间：2026-05-16 22:15:25 UTC

## 目录

- [txtai概述](#page-overview)
- [系统架构](#page-architecture)
- [核心组件](#page-components)
- [向量嵌入系统](#page-embeddings)
- [近似最近邻索引](#page-ann-index)
- [评分系统](#page-scoring)
- [LLM管道](#page-pipeline-llm)
- [文本处理管道](#page-pipeline-text)
- [音频和图像管道](#page-pipeline-audio)
- [工作流引擎](#page-workflow)

<a id='page-overview'></a>

## txtai概述

### 相关页面

相关主题：[系统架构](#page-architecture), [向量嵌入系统](#page-embeddings)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/neuml/txtai/blob/main/README.md)
- [setup.py](https://github.com/neuml/txtai/blob/main/setup.py)
- [src/python/txtai/pipeline/data/textractor.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/data/textractor.py)
- [src/python/txtai/pipeline/llm/llm.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/llm/llm.py)
- [src/python/txtai/embeddings/index/documents.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/index/documents.py)
- [src/python/txtai/workflow/task/template.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/workflow/task/template.py)
- [examples/rag_quickstart.py](https://github.com/neuml/txtai/blob/main/examples/rag_quickstart.py)
</details>

# txtai概述

## 1. 项目简介

txtai是一个全功能AI框架，专为语义搜索、大型语言模型（LLM）编排和语言模型工作流而设计 资料来源：[README.md](https://github.com/neuml/txtai/blob/main/README.md)。

该框架的核心组件是**嵌入数据库（Embeddings Database）**，它将向量索引（稀疏和密集）、图网络和关系数据库结合在一起 资料来源：[README.md:19](https://github.com/neuml/txtai/blob/main/README.md)。

## 2. 核心功能特性

txtai提供以下主要功能：

| 功能类别 | 描述 |
|---------|------|
| 向量搜索 | 支持SQL、对象存储、主题建模、图分析和多模态索引 |
| 嵌入生成 | 为文本、文档、音频、图像和视频创建嵌入向量 |
| 管道系统 | 包含LLM提示、问答、标注、转录、翻译等语言模型驱动的管道 |
| API服务 | 内置FastAPI支持多语言应用开发 |
| 工作流 | 灵活的工作流引擎支持复杂AI任务编排 |
| Agent代理 | 构建自主Agent和RAG流程 |

资料来源：[README.md:24-31](https://github.com/neuml/txtai/blob/main/README.md)

## 3. 系统架构

### 3.1 整体架构

```mermaid
graph TD
    A[用户应用] --> B[API层 FastAPI]
    B --> C[工作流引擎 Workflow]
    C --> D[管道系统 Pipeline]
    D --> E{任务类型}
    E --> F[数据管道 Data]
    E --> G[LLM管道 LLM]
    E --> H[文本管道 Text]
    E --> I[训练管道 Train]
    F --> J[嵌入数据库 Embeddings]
    G --> J
    J --> K[(向量索引)]
    J --> L[(图网络)]
    J --> M[(关系数据库)]
```

### 3.2 核心模块关系

```mermaid
graph TD
    subgraph 数据处理层
        T[Textractor] --> H2M[HTMLToMarkdown]
        H2M --> SEG[Segmentation]
    end
    
    subgraph 嵌入层
        SEG --> EMB[Embeddings]
        EMB --> DOCS[Documents]
    end
    
    subgraph AI能力层
        EMB --> LLM[LLM Pipeline]
        LLM --> RAG[RAG Pipeline]
    end
    
    subgraph 执行层
        TSK[TemplateTask] --> WFL[Workflow]
    end
```

## 4. 依赖体系

### 4.1 核心依赖

| 依赖包 | 最低版本 | 用途 |
|-------|---------|------|
| faiss-cpu | 1.7.1.post2 | 高效向量相似度搜索 |
| huggingface-hub | 0.34.0 | Hugging Face模型访问 |
| torch | 2.4 | 深度学习框架 |
| transformers | 4.56.2 | 模型推理 |
| numpy | 1.18.4 | 数值计算 |
| safetensors | 0.4.5 | 安全模型加载 |

资料来源：[setup.py:28-38](https://github.com/neuml/txtai/blob/main/setup.py)

### 4.2 可选依赖组

txtai采用模块化设计，通过可选依赖组提供扩展功能：

| 依赖组 | 包含组件 |
|-------|---------|
| pipeline-audio | 音频处理管道（onnx, soundfile, webrtcvad等） |
| pipeline-data | 数据处理管道（beautifulsoup4, docling, nltk等） |
| pipeline-image | 图像处理管道（pillow, timm, imagehash等） |
| pipeline-llm | LLM管道（litellm, llama-cpp-python等） |
| pipeline-text | 文本管道（gliner, sentencepiece等） |
| pipeline-train | 训练管道（accelerate, peft, onnx等） |
| agent | Agent代理（jinja2, smolagents, mcpadapt等） |
| ann | 向量检索（annoy, hnswlib, pgvector等） |
| api | API服务（fastapi, uvicorn, aiohttp等） |
| graph | 图数据库（grand-cypher, networkx等） |

资料来源：[setup.py:7-82](https://github.com/neuml/txtai/blob/main/setup.py)

## 5. 主要组件详解

### 5.1 嵌入数据库（Embeddings）

Embeddings是txtai的核心组件，提供向量化的语义搜索能力。

**基本使用示例：**

```python
import txtai

embeddings = txtai.Embeddings()
embeddings.index(["Correct", "Not what we hoped"])
result = embeddings.search("positive", 1)
# 返回: [(0, 0.29862046241760254)]
```

资料来源：[README.md:70-75](https://github.com/neuml/txtai/blob/main/README.md)

### 5.2 文本提取器（Textractor）

Textractor模块负责从各种文件格式中提取文本内容。

```python
class Textractor(Segmentation):
    def __init__(
        self,
        sentences=False,      # 按句子分割
        lines=False,          # 按行分割
        paragraphs=False,     # 按段落分割
        minlength=None,       # 最小文本长度
        join=False,           # 是否合并结果
        sections=False,       # 保留章节结构
        cleantext=True,       # 清理文本
        chunker=None,         # 分块器
        headers=None,         # HTTP请求头
        backend="available",  # 后端选择
        safeopen=False,       # 安全打开模式
    ):
```

**支持的输入格式：**

Textractor内部使用FileToHTML管道处理文件，并支持Tika后端作为备选方案。

资料来源：[src/python/txtai/pipeline/data/textractor.py:15-45](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/data/textractor.py)

### 5.3 LLM管道

LLM管道提供大型语言模型的调用能力，支持多种模型后端。

**核心方法：**

| 方法 | 描述 |
|------|------|
| `__call__(text, ...)` | 生成文本内容 |
| `ischat()` | 检查是否为聊天模型 |
| `isvision()` | 检查是否支持视觉功能 |

**调用参数：**

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| text | str/list | - | 输入文本 |
| maxlength | int | None | 最大序列长度 |
| stream | bool | False | 是否流式输出 |
| stop | list | None | 停止字符串列表 |
| defaultrole | str | "auto" | 默认角色 |
| stripthink | bool | None | 是否去除思考标签 |

资料来源：[src/python/txtai/pipeline/llm/llm.py:20-45](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/llm/llm.py)

### 5.4 工作流引擎（Workflow）

工作流引擎支持灵活的任务编排。

**TemplateTask组件：**

TemplateTask使用模板生成LLM提示词，支持字典和元组两种参数传递方式：

```python
# 字典参数传递
self.formatter.format(self.template, **element)

# 元组参数传递
self.formatter.format(self.template, **{f"arg{i}": x for i, x in enumerate(element)})

# 默认行为 - 使用{text}参数
self.formatter.format(self.template, text=element)
```

资料来源：[src/python/txtai/workflow/task/template.py:35-50](https://github.com/neuml/txtai/blob/main/src/python/txtai/workflow/task/template.py)

## 6. RAG快速入门

### 6.1 完整流程

```mermaid
graph LR
    A[加载文档] --> B[文本提取 Textractor]
    B --> C[文本分块]
    C --> D[构建嵌入索引]
    D --> E[创建RAG管道]
    E --> F[用户提问]
    F --> G[语义检索]
    G --> H[上下文组装]
    H --> I[LLM生成答案]
```

### 6.2 代码示例

```python
from txtai import Embeddings
from txtai.pipeline import RAG, Textractor

# Step 1: 文本提取
textractor = Textractor()
f = "document.pdf"
chunks = []
for chunk in textractor(f):
    chunks.append((f, chunk))

# Step 2: 构建嵌入数据库
embeddings = Embeddings(
    content=True, 
    path="Qwen/Qwen3-Embedding-0.6B", 
    maxlength=2048
)
embeddings.index(chunks)

# Step 3: 创建RAG管道
template = """
  Answer the following question using the provided context.

  Question: {question}
  Context: {context}
"""

rag = RAG(
    embeddings,
    "Qwen/Qwen3-0.6B",
    system="You are a friendly assistant",
    template=template,
    output="flatten",
)

# Step 4: 问答
question = "Summarize the main advancements made by BERT"
result = rag(question, maxlength=2048, stripthink=True)
```

资料来源：[examples/rag_quickstart.py:1-50](https://github.com/neuml/txtai/blob/main/examples/rag_quickstart.py)

## 7. 文档存储机制

### 7.1 Documents类

Documents类负责管理索引文档的存储和序列化：

```python
class Documents:
    def add(self, documents):
        """添加文档批次"""
        if not self.documents:
            self.documents = tempfile.NamedTemporaryFile(
                mode="wb", suffix=".docs", delete=False
            )
        
        # 流式保存文档
        self.serializer.savestream(documents, self.documents)
        self.batch += 1
        self.size += len(documents)
        return documents
    
    def close(self):
        """关闭并清理临时文件"""
        os.remove(self.documents.name)
        self.documents = None
        self.batch = 0
        self.size = 0
```

资料来源：[src/python/txtai/embeddings/index/documents.py:10-30](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/index/documents.py)

## 8. 部署方式

### 8.1 API服务部署

通过YAML配置文件快速启动API服务：

```yaml
# app.yml
embeddings:
    path: sentence-transformers/all-MiniLM-L6-v2
```

```bash
CONFIG=app.yml uvicorn "txtai.api:app"
curl -X GET "http://localhost:8000/search?query=positive"
```

### 8.2 工作流API

```python
def api(self, config):
    """启动内部uvicorn服务器"""
    # 生成临时工作流配置文件
    workflow = os.path.join(tempfile.gettempdir(), "workflow.yml")
    with open(workflow, "w", encoding="utf-8") as f:
        f.write(config)
    
    os.environ["CONFIG"] = workflow
    txtai.api.application.start()
```

资料来源：[examples/workflows.py:60-75](https://github.com/neuml/txtai/blob/main/examples/workflows.py)

## 9. 技术特点

| 特点 | 说明 |
|------|------|
| 低占用 | 仅安装必要依赖，可按需扩展 |
| 本地运行 | 无需将数据发送到外部服务 |
| 模型兼容 | 支持从小型模型到LLM的多种规模 |
| 灵活扩展 | 模块化设计，易于集成新功能 |
| 多模态 | 支持文本、文档、音频、图像和视频 |

资料来源：[README.md:80-85](https://github.com/neuml/txtai/blob/main/README.md)

## 10. 安装方式

### 10.1 基础安装

```bash
pip install txtai
```

### 10.2 可选组件安装

```bash
# 仅向量搜索
pip install txtai[ann]

# 包含向量搜索
pip install txtai[vectors]

# 完整安装
pip install txtai[all]

# 特定功能
pip install txtai[api]          # API服务
pip install txtai[agent]         # Agent代理
pip install txtai[pipeline-llm]  # LLM支持
pip install txtai[graph]         # 图数据库
```

资料来源：[setup.py:85-110](https://github.com/neuml/txtai/blob/main/setup.py)

## 11. 总结

txtai是一个功能全面的AI框架，通过将向量搜索、图数据库和关系数据库相结合，为构建语义搜索、RAG系统和AI工作流提供了统一的基础设施。其模块化设计和丰富的可选依赖使其能够适应从简单到复杂的各种应用场景。

---

<a id='page-architecture'></a>

## 系统架构

### 相关页面

相关主题：[核心组件](#page-components), [向量嵌入系统](#page-embeddings), [工作流引擎](#page-workflow)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/python/txtai/embeddings/base.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/base.py)
- [src/python/txtai/workflow/base.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/workflow/base.py)
- [src/python/txtai/agent/base.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/agent/base.py)
- [src/python/txtai/pipeline/llm/llm.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/llm/llm.py)
- [src/python/txtai/pipeline/data/textractor.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/data/textractor.py)
- [src/python/txtai/embeddings/index/documents.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/index/documents.py)
- [examples/rag_quickstart.py](https://github.com/neuml/txtai/blob/main/examples/rag_quickstart.py)
- [examples/workflows.py](https://github.com/neuml/txtai/blob/main/examples/workflows.py)
</details>

# 系统架构

## 概述

txtai 是一个功能全面的 AI 框架，核心定位为**语义搜索**、**LLM 编排**和**语言模型工作流**的一体化解决方案。该框架的关键组件是**嵌入数据库（Embeddings Database）**，它整合了向量索引（稀疏和密集）、图网络和关系数据库的能力。

这种架构设计使得 txtai 不仅能够执行向量搜索，还能作为大型语言模型（LLM）应用的强大知识源，支持构建自主代理（Agents）、检索增强生成（RAG）流程、多模态工作流等高级应用场景。

资料来源：[README.md](https://github.com/neuml/txtai/blob/main/README.md)

## 整体架构

txtai 采用模块化设计，核心架构由以下几个主要层次组成：

```mermaid
graph TD
    subgraph "表现层"
        API[API 服务层]
        Console[Console 控制台]
    end
    
    subgraph "应用层"
        Agent[Agent 代理]
        Workflow[Workflow 工作流]
        RAG[RAG 管道]
    end
    
    subgraph "管道层"
        LLM[LLM 管道]
        Data[Data 数据管道]
        Text[Text 文本管道]
        Audio[Audio 音频管道]
        Image[Image 图像管道]
    end
    
    subgraph "核心层"
        Embeddings[Embeddings 嵌入数据库]
        Graph[Graph 图网络]
        Database[Database 数据库]
    end
    
    subgraph "向量索引层"
        FAISS[FAISS]
        HNSW[HNSWLib]
        Annoy[Annoy]
        PGVector[PGVector]
    end
    
    API --> Agent
    API --> Workflow
    Agent --> Workflow
    Workflow --> Embeddings
    Workflow --> LLM
    RAG --> Embeddings
    RAG --> LLM
    Embeddings --> FAISS
    Embeddings --> HNSW
    Embeddings --> Annoy
    Embeddings --> PGVector
    Embeddings --> Graph
    Embeddings --> Database
```

资料来源：[README.md](https://github.com/neuml/txtai/blob/main/README.md)

## 核心模块

### 1. 嵌入数据库（Embeddings）

嵌入数据库是 txtai 的核心组件，它统一了向量索引、图网络和关系数据库的功能。

#### 核心类结构

```python
class Embeddings:
    def __init__(self, content=True, path="model", maxlength=2048):
        self.content = content
        self.path = path
        self.maxlength = maxlength
    
    def index(self, documents): ...
    def search(self, query, limit=10): ...
    def batch(self, documents): ...
```

#### 功能特性

| 特性 | 描述 | 支持类型 |
|------|------|----------|
| 向量搜索 | 稀疏和密集向量索引 | FAISS, HNSW, Annoy, PGVector |
| 内容存储 | 文档内容持久化 | msgpack 序列化 |
| SQL 查询 | 混合搜索能力 | SQLAlchemy |
| 图分析 | 图网络遍历 | NetworkX, Grand |
| 多模态 | 支持多种数据类型 | 文本、图像、音视频 |

资料来源：[src/python/txtai/embeddings/base.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/base.py)

#### 文档存储机制

嵌入数据库使用临时文件系统存储文档数据，支持批量索引操作：

```python
# documents.py 中的关键实现
if not self.documents:
    self.documents = tempfile.NamedTemporaryFile(mode="wb", suffix=".docs", delete=False)

# 批量添加文档
self.serializer.savestream(documents, self.documents)
self.batch += 1
```

资料来源：[src/python/txtai/embeddings/index/documents.py:2-15](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/index/documents.py)

### 2. 工作流引擎（Workflow）

工作流引擎负责编排和组织多个任务（Task）的执行流程。

#### 工作流结构

```mermaid
graph LR
    subgraph "工作流定义"
        Config[YAML 配置]
        Tasks[任务列表]
    end
    
    subgraph "任务类型"
        Action[Action 动作]
        Service[Service 服务]
        Transform[Transform 转换]
    end
    
    Config --> Tasks
    Tasks --> Action
    Tasks --> Service
    Tasks --> Transform
```

#### 支持的任务类型

| 任务类型 | 说明 | 配置方式 |
|----------|------|----------|
| `action` | 执行动作任务 | `{"action": "taskname"}` |
| `service` | 启动服务任务 | `{"task": "service"}` |
| `textractor` | 文本提取任务 | `{"action": "textractor", "task": "url"}` |
| `transcription` | 音频转录任务 | `{"action": "transcription", "task": "url"}` |
| `tabular` | 表格处理任务 | `{"action": "tabular"}` |
| `summary` | 摘要生成任务 | `{"action": "summary", "path": "model"}` |

资料来源：[examples/workflows.py](https://github.com/neuml/txtai/blob/main/examples/workflows.py)

#### 模板任务（Template Task）

模板任务用于生成 LLM 提示词，支持多种输入格式：

```python
class TemplateTask(Task):
    def prepare(self, element):
        # 字典输入 - 作为命名参数传递
        if isinstance(element, dict):
            return self.formatter.format(self.template, **element)
        
        # 元组输入 - 作为 arg0-argN 传递
        if isinstance(element, tuple):
            return self.formatter.format(self.template, **{f"arg{i}": x for i, x in enumerate(element)})
        
        # 默认 - 使用 {text} 参数
        return self.formatter.format(self.template, text=element)
```

资料来源：[src/python/txtai/workflow/task/template.py:30-45](https://github.com/neuml/txtai/blob/main/src/python/txtai/workflow/task/template.py)

### 3. 代理系统（Agent）

代理系统支持构建自主 AI 代理，具备规划、推理和执行能力。

```mermaid
graph TD
    Agent[Agent 代理] --> Tool1[工具 1]
    Agent --> Tool2[工具 2]
    Agent --> ToolN[工具 N]
    Agent --> LLM[LLM 引擎]
    
    Tool1 --> Memory[记忆存储]
    Tool2 --> Memory
    ToolN --> Memory
    
    LLM --> Action[执行动作]
    Action --> Tool1
    Action --> Tool2
    Action --> ToolN
```

#### 代理特性

- 支持多种 LLM 后端（Hugging Face、Ollama、vLLM、llama.cpp）
- 集成 MCP（Model Context Protocol）适配器
- 支持 Jinja2 模板渲染
- 可与工作流系统无缝集成

资料来源：[src/python/txtai/agent/base.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/agent/base.py)

### 4. 管道系统（Pipeline）

管道系统是数据处理的核心，提供多种专门的处理器。

#### 管道类型

| 管道类型 | 功能 | 依赖库 |
|----------|------|--------|
| LLM 管道 | 语言模型推理、提示执行 | transformers, llama-cpp |
| Data 管道 | 文本提取、HTML 转换、分段 | beautifulsoup4, tika, nltk |
| Audio 管道 | 语音转文本、翻译 | scipy, soundfile |
| Image 管道 | 图像处理、特征提取 | pillow, timm |
| Text 管道 | 文本分类、实体识别 | gliner, staticvectors |

#### 文本提取器（Textractor）

文本提取器是数据管道的重要组成部分，支持从多种格式提取文本：

```python
class Textractor(Segmentation):
    def __init__(
        self,
        sentences=False,      # 句子分割
        lines=False,          # 行分割
        paragraphs=False,     # 段落分割
        minlength=None,       # 最小文本长度
        join=False,           # 合并短文本
        sections=False,       # 保留章节结构
        cleantext=True,       # 清理文本
        chunker=None,         # 分块器
        backend="available",  # 后端: tika 或自动
        safeopen=False,       # 安全打开模式
    ):
```

处理流程：

```mermaid
graph LR
    Input[输入文件/URL] --> FileToHTML[FileToHTML]
    FileToHTML --> HTMLToMarkdown[HTMLToMarkdown]
    HTMLToMarkdown --> Segmentation[Segmentation]
    Segmentation --> Output[文本输出]
```

资料来源：[src/python/txtai/pipeline/data/textractor.py:14-40](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/data/textractor.py)

#### LLM 管道

LLM 管道负责与语言模型交互：

```python
class LLM:
    def __call__(
        self,
        text,                    # 输入文本或列表
        maxlength=None,          # 最大序列长度
        stream=False,            # 流式响应
        stop=None,               # 停止字符串列表
        defaultrole="auto",      # 默认角色
        stripthink=True,         # 移除思考标签
        **kwargs                 # 其他生成参数
    ):
        return self.generator(text, maxlength, stream, stop, defaultrole, stripthink, **kwargs)
    
    def ischat(self): ...        # 检查是否为聊天模型
    def isvision(self): ...      # 检查是否支持视觉
```

资料来源：[src/python/txtai/pipeline/llm/llm.py:20-45](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/llm/llm.py)

## 应用场景架构

### 检索增强生成（RAG）

```mermaid
graph TD
    Question[用户问题] --> Embeddings[Embeddings 查询]
    Embeddings --> Context[上下文检索]
    Context --> LLM[LLM 生成]
    LLM --> Answer[生成回答]
    
    subgraph "索引流程"
        Documents[文档] --> Textractor[文本提取]
        Textractor --> Chunks[文本块]
        Chunks --> Index[向量索引]
    end
```

RAG 应用示例：

```python
# 创建嵌入数据库
embeddings = Embeddings(content=True, path="Qwen/Qwen3-Embedding-0.6B", maxlength=2048)
embeddings.index(chunks)

# 创建 RAG 管道
rag = RAG(
    embeddings,
    "Qwen/Qwen3-0.6B",
    system="You are a friendly assistant",
    template=template,
    output="flatten",
)

# 执行查询
result = rag(question, maxlength=2048, stripthink=True)
```

资料来源：[examples/rag_quickstart.py](https://github.com/neuml/txtai/blob/main/examples/rag_quickstart.py)

### API 服务架构

```mermaid
graph LR
    Request[HTTP 请求] --> FastAPI[FastAPI 服务]
    FastAPI --> Workflow[Workflow 引擎]
    Workflow --> Pipeline[Pipeline 管道]
    Pipeline --> Embeddings[Embeddings]
    Pipeline --> LLM[LLM]
    Workflow --> Response[JSON 响应]
```

API 配置示例（YAML）：

```yaml
embeddings:
    path: sentence-transformers/all-MiniLM-L6-v2

workflow:
    search:
        tasks:
            - action: similarity
```

资料来源：[README.md](https://github.com/neuml/txtai/blob/main/README.md)

## 依赖关系

txtai 的依赖组织结构如下：

```mermaid
graph TD
    Core[核心依赖] --> Torch[torch>=2.4]
    Core --> Transformers[transformers>=4.56.2]
    Core --> Faiss[faiss-cpu>=1.7.1]
    Core --> HuggingFace[huggingface-hub>=0.34.0]
    
    Optional[可选依赖] --> API[API: fastapi, uvicorn]
    Optional --> ANN[ANN: hnswlib, annoy, pgvector]
    Optional --> LLM[LLM: litellm, llama-cpp]
    Optional --> Cloud[Cloud: apache-libcloud]
```

## 扩展组件

| 组件类别 | 包名 | 主要功能 |
|----------|------|----------|
| 图数据库 | `graph` | Grand-Cypher 图查询 |
| 关系数据库 | `database` | DuckDB, SQLAlchemy |
| 向量索引 | `ann` | 多种 ANN 算法支持 |
| 云存储 | `cloud` | Apache Libcloud 集成 |
| 模型优化 | `model` | ONNX 推理优化 |

## 配置选项

### Embeddings 配置参数

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `path` | str | - | 模型路径（Hugging Face 模型名或本地路径） |
| `content` | bool | False | 是否存储原始内容 |
| `maxlength` | int | 256 | 最大序列长度 |
| `functions` | dict | None | 函数调用配置 |
| `scoring` | str | None | 评分方法 |
| `indextype` | str | None | 索引类型（hnsw, annoy, faiss 等） |

### Workflow 任务配置

| 参数 | 类型 | 说明 |
|------|------|------|
| `action` | str | 任务动作名称 |
| `task` | str | 任务类型 |
| `args` | list | 位置参数 |
| `config` | dict | 任务特定配置 |

## 总结

txtai 采用分层模块化架构设计，核心优势包括：

1. **统一性**：通过 Embeddings 数据库统一向量搜索、图分析和关系查询
2. **可扩展性**：丰富的可选依赖支持按需扩展功能
3. **灵活性**：Pipeline 管道支持自定义数据处理流程
4. **生产级**：内置 API 服务支持快速部署

该架构设计使得 txtai 能够从小型嵌入模型无缝扩展到完整的 LLM 应用，满足从原型开发到生产部署的全流程需求。

---

<a id='page-components'></a>

## 核心组件

### 相关页面

相关主题：[系统架构](#page-architecture), [向量嵌入系统](#page-embeddings), [工作流引擎](#page-workflow)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/python/txtai/embeddings/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/__init__.py)
- [src/python/txtai/pipeline/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/__init__.py)
- [src/python/txtai/workflow/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/workflow/__init__.py)
- [src/python/txtai/agent/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/agent/__init__.py)
- [src/python/txtai/pipeline/llm/llm.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/llm/llm.py)
- [src/python/txtai/pipeline/data/textractor.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/data/textractor.py)
- [src/python/txtai/agent/tool/function.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/agent/tool/function.py)
- [src/python/txtai/agent/tool/factory.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/agent/tool/factory.py)
</details>

# 核心组件

txtai 是一个功能全面的 AI 框架，其核心架构由四个主要组件构成：嵌入向量数据库（Embeddings）、管道（Pipeline）、工作流（Workflow）和智能体（Agent）。这些组件协同工作，为语义搜索、大型语言模型（LLM）应用和知识图谱分析提供统一的基础设施。

## 架构概览

```mermaid
graph TD
    A[txtai 核心架构] --> B[Embeddings 嵌入向量数据库]
    A --> C[Pipeline 管道]
    A --> D[Workflow 工作流]
    A --> E[Agent 智能体]
    
    B --> B1[向量索引]
    B --> B2[图网络]
    B --> B3[关系数据库]
    
    C --> C1[LLM 管道]
    C --> C2[Summary 摘要]
    C --> C3[Textractor 文本提取]
    C --> C4[RAG 检索增强生成]
    
    D --> D1[Task 任务]
    D --> D2[Template 模板]
    
    E --> E1[Tool 工具]
    E --> E2[FunctionTool 函数工具]
```

## 1. 嵌入向量数据库（Embeddings）

### 概述

嵌入向量数据库是 txtai 的核心组件，它将向量索引（稀疏和密集）、图网络和关系数据库有机结合。这种独特的架构设计使得 txtai 能够同时支持向量搜索和传统数据库查询，为大型语言模型应用提供强大的知识源支持。

### 核心功能

| 功能 | 描述 |
|------|------|
| 向量搜索 | 支持语义相似度检索 |
| 混合索引 | 稀疏与密集向量结合 |
| SQL 支持 | 关系型数据查询 |
| 图分析 | 知识图谱网络分析 |
| 内容存储 | 文档和元数据存储 |

### 使用方式

```python
import txtai

embeddings = txtai.Embeddings()
embeddings.index(["Correct", "Not what we hoped"])
result = embeddings.search("positive", 1)
# 返回: [(0, 0.29862046241760254)]
```

资料来源：[README.md]()

## 2. 管道（Pipeline）

### 概述

管道是 txtai 中用于处理数据的核心模块，由语言模型驱动。管道可以执行 LLM 提示、问答、标注、转录、翻译等任务。

### LLM 管道

LLM 管道是 txtai 中最重要的管道之一，支持多种模型类型和调用方式。

#### 支持的模型类型

- Hugging Face Transformers 模型
- llama.cpp 本地模型
- Ollama 远程模型
- vLLM 服务

#### API 参数

| 参数 | 类型 | 默认值 | 描述 |
|------|------|--------|------|
| text | str/list | 必需 | 输入文本或文本列表 |
| maxlength | int | 512 | 最大序列长度 |
| stream | bool | False | 是否流式输出 |
| stop | list | None | 停止字符串列表 |
| defaultrole | str | "auto" | 默认角色（user/prompt） |
| stripthink | bool | 自动 | 是否移除思考标签 |

```python
from txtai.pipeline import Summary, Textractor

# 文本摘要管道
summary = Summary("sshleifer/distilbart-cnn-12-6")

# 文本提取管道
textract = Textractor(paragraphs=True, minlength=100, join=True)
```

资料来源：[src/python/txtai/pipeline/llm/llm.py:1-80]()

### 数据管道

Textractor 模块负责从各种文件格式中提取文本内容。

#### Textractor 参数

| 参数 | 类型 | 默认值 | 描述 |
|------|------|--------|------|
| sentences | bool | False | 按句子分割 |
| lines | bool | False | 按行分割 |
| paragraphs | bool | False | 按段落分割 |
| minlength | int | None | 最小文本长度 |
| join | bool | False | 合并结果 |
| sections | bool | False | 按章节处理 |
| cleantext | bool | True | 清理文本 |
| chunker | str | None | 分块器 |
| backend | str | "available" | 后端（tika/none） |
| safeopen | bool/str | False | 安全打开模式 |

```python
textractor = Textractor(
    paragraphs=True,
    minlength=100,
    join=True,
    backend="available"
)
```

资料来源：[src/python/txtai/pipeline/data/textractor.py:1-60]()

## 3. 工作流（Workflow）

### 概述

工作流系统允许将多个任务串联起来处理数据。通过定义任务序列，可以构建复杂的数据处理管道。

```mermaid
graph LR
    A[输入数据] --> B[Task 1]
    B --> C[Task 2]
    C --> D[Task N]
    D --> E[输出结果]
```

### 任务类型

| 任务类型 | 描述 |
|----------|------|
| Task | 基础任务 |
| TemplateTask | 模板任务，用于生成 LLM 提示 |
| UrlTask | URL 处理任务 |

### 模板任务

TemplateTask 是工作流中的重要组件，用于根据模板和任务输入生成文本。模板可以用于准备 LLM 提示数据。

```python
from txtai.workflow import UrlTask, Task, Workflow

# 定义工作流
workflow = Workflow([UrlTask(textract), Task(summary)])

# 执行工作流
result = list(workflow([url]))[0]
```

资料来源：[src/python/txtai/workflow/task/template.py:1-50]()

## 4. 智能体（Agent）

### 概述

智能体系统用于构建自主代理，支持构建检索增强生成（RAG）流程、多模态工作流等高级应用。

```mermaid
graph TD
    A[Agent 智能体] --> B[Tool 工具集]
    A --> C[LLM 大语言模型]
    B --> D[FunctionTool 函数工具]
    B --> E[EmbeddingsTool 嵌入工具]
    C --> F[推理引擎]
    
    F --> G[规划决策]
    G --> H[工具调用]
    H --> I[结果反馈]
    I --> F
```

### 工具系统

txtai 的工具系统支持三种创建方式：

| 创建方式 | 描述 |
|----------|------|
| Tool 实例 | 直接传入 Tool 对象 |
| 字典配置 | 包含 name、description、inputs、target 的配置字典 |
| 字符串别名 | 使用预定义的工具名称 |

#### FunctionTool 类

FunctionTool 将描述性配置与目标函数结合，注入到 LLM 提示中。

```python
from txtai.agent.tool.function import FunctionTool

config = {
    "name": "my_function",
    "description": "执行特定操作",
    "inputs": {"param1": "string"},
    "output": "string",
    "target": my_function
}

tool = FunctionTool(config)
```

资料来源：[src/python/txtai/agent/tool/function.py:1-60]()

### 工具工厂

ToolFactory 负责根据配置创建工具实例，支持以下功能：

- 从函数和文档创建工具
- 从输入字典创建工具
- 从字符串别名获取默认工具
- 导入 MCP 工具集合

```python
from txtai.agent.tool.factory import ToolFactory

# 创建工具列表
tools = ToolFactory.create(config)
```

资料来源：[src/python/txtai/agent/tool/factory.py:1-80]()

## 5. RAG 检索增强生成

### 概述

RAG 是 txtai 中的重要应用模式，它将嵌入向量数据库与 LLM 结合，实现基于知识库的问答系统。

```mermaid
graph TD
    A[用户问题] --> B[Embeddings 查询]
    B --> C[检索相关上下文]
    C --> D[构建提示模板]
    D --> E[LLM 生成答案]
    E --> F[返回结果]
```

### 使用示例

```python
from txtai import Embeddings, RAG

# 用户提示模板
template = """
  Answer the following question using the provided context.

  Question:
  {question}

  Context:
  {context}
"""

rag = RAG(
    embeddings,
    "Qwen/Qwen3-0.6B",
    system="You are a friendly assistant",
    template=template,
    output="flatten",
)

question = "Summarize the main advancements made by BERT"
result = rag(question, maxlength=2048, stripthink=True)
```

资料来源：[examples/rag_quickstart.py]()

## 组件依赖关系

```mermaid
graph TD
    subgraph 核心层
        A[txtai] --> B[Embeddings]
        A --> C[Pipeline]
        A --> D[Workflow]
        A --> E[Agent]
    end
    
    subgraph 管道层
        C --> C1[LLM Pipeline]
        C --> C2[Summary Pipeline]
        C --> C3[Textractor Pipeline]
        C --> C4[RAG Pipeline]
    end
    
    subgraph 应用层
        E --> F[RAG 应用]
        E --> G[自主代理]
        D --> H[数据处理]
    end
    
    B --> I[向量索引]
    B --> J[关系数据库]
```

## 总结

txtai 的四大核心组件构成了一个完整的 AI 应用开发框架：

1. **Embeddings** 提供向量搜索和知识存储能力
2. **Pipeline** 提供数据处理和模型推理能力
3. **Workflow** 提供任务编排和工作流自动化
4. **Agent** 提供智能体和自主决策能力

这些组件可以独立使用，也可以组合使用来构建复杂的 AI 应用，如 RAG 系统、多模态工作流和自主代理。

---

<a id='page-embeddings'></a>

## 向量嵌入系统

### 相关页面

相关主题：[近似最近邻索引](#page-ann-index), [评分系统](#page-scoring), [核心组件](#page-components)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/python/txtai/embeddings/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/__init__.py)
- [src/python/txtai/embeddings/base.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/base.py)
- [src/python/txtai/embeddings/index/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/index/__init__.py)
- [src/python/txtai/embeddings/search/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/search/__init__.py)
- [README.md](https://github.com/neuml/txtai/blob/main/README.md)
- [setup.py](https://github.com/neuml/txtai/blob/main/setup.py)
- [examples/rag_quickstart.py](https://github.com/neuml/txtai/blob/main/examples/rag_quickstart.py)
</details>

# 向量嵌入系统

## 概述

txtai 的核心组件是**向量嵌入系统（Embeddings System）**，它是一个将向量索引、图网络和关系数据库统一结合的嵌入数据库。该系统为语义搜索和大语言模型（LLM）应用提供了强大的知识检索基础。

向量嵌入系统的主要特点包括：

- 支持文本、文档、音视频等多模态内容的嵌入表示
- 集成稀疏和密集向量索引
- 支持向量搜索与 SQL 查询的混合检索
- 提供本地化运行能力，无需依赖外部远程服务
- 支持从小型模型到大型语言模型（LLM）的多种配置

资料来源：[README.md](https://github.com/neuml/txtai/blob/main/README.md)

## 系统架构

向量嵌入系统的架构设计采用分层模块化结构，核心由索引模块、搜索模块和基础抽象层组成。

```mermaid
graph TD
    A["txtai.Embeddings<br>入口类"] --> B["EmbeddingsBase<br>基础抽象类"]
    B --> C["EmbeddingsIndex<br>索引管理"]
    B --> D["EmbeddingsSearch<br>搜索管理"]
    C --> E["Documents<br>文档序列化"]
    C --> F["Vectors<br>向量存储"]
    D --> G["VectorQueue<br>向量队列"]
    D --> H["HNSW/FAISS等<br>索引后端"]
```

### 核心模块职责

| 模块 | 职责 | 主要功能 |
|------|------|----------|
| `Embeddings` | 入口类 | 提供 `index()`、`search()` 等核心 API |
| `EmbeddingsBase` | 基础抽象 | 定义通用接口和默认实现 |
| `EmbeddingsIndex` | 索引管理 | 管理文档和向量的索引构建流程 |
| `EmbeddingsSearch` | 搜索管理 | 处理向量相似度搜索请求 |
| `Documents` | 文档序列化 | 将输入数据序列化为流式存储格式 |

## Embeddings 入口类

`txtai.Embeddings` 是用户使用向量嵌入系统的主要入口点，提供了简洁的 API 接口。

### 基础使用示例

```python
import txtai

# 创建嵌入实例
embeddings = txtai.Embeddings()

# 索引文档
embeddings.index(["正确", "不是我们希望的"])

# 执行语义搜索
embeddings.search("positive", 1)
# 返回: [(0, 0.29862046241760254)]
```

资料来源：[README.md:1-12](https://github.com/neuml/txtai/blob/main/README.md)

### 构造函数参数

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `path` | str | None | 向量模型路径，支持 Hugging Face 模型、llama.cpp、Ollama、vLLM |
| `content` | bool | False | 是否存储原始文档内容 |
| `vectors` | str | None | 外部向量文件路径 |
| `functions` | list | None | 自定义向量生成函数列表 |
| `scoring` | bool | True | 是否启用相似度评分 |
| `gpu` | bool | True | 是否优先使用 GPU |
| `batchsize` | int | 32 | 批处理大小 |
| `maxlength` | int | 512 | 最大序列长度 |
| `quantize` | bool | False | 是否量化模型 |

资料来源：[examples/rag_quickstart.py:18-19](https://github.com/neuml/txtai/blob/main/examples/rag_quickstart.py)

## 索引构建流程

### 索引 API

```python
# 使用 content=True 存储原始文档
embeddings = Embeddings(content=True, path="Qwen/Qwen3-Embedding-0.6B", maxlength=2048)
embeddings.index(chunks)
```

索引过程接受元组列表 `(id, data, vector)` 或 `(id, data)` 格式的数据，自动生成向量表示。

资料来源：[examples/rag_quickstart.py:18-20](https://github.com/neuml/txtai/blob/main/examples/rag_quickstart.py)

### 文档序列化

索引模块使用流式序列化机制处理文档数据：

```python
# Documents 类负责序列化
self.documents = tempfile.NamedTemporaryFile(mode="wb", suffix=".docs", delete=False)
self.serializer.savestream(documents, self.documents)
```

序列化设计支持增量索引，可以分批次添加文档：

```python
# 分批添加文档
self.batch += 1
self.size += len(documents)
```

资料来源：[src/python/txtai/embeddings/index/documents.py:2-10](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/index/documents.py)

### 索引关闭与清理

索引完成后，系统会清理临时资源：

```python
def close(self):
    # 清理流文件
    os.remove(self.documents.name)
    # 重置文档参数
    self.documents = None
    self.batch = 0
    self.size = 0
```

资料来源：[src/python/txtai/embeddings/index/documents.py:22-30](https://github.com/neuml/txtai/blob/main/src/python/txtai/embeddings/index/documents.py)

## 搜索流程

### 语义搜索 API

```python
# 执行向量相似度搜索
results = embeddings.search("查询文本", topk=5)
```

搜索返回格式为 `[(document_id, score), ...]`，按相似度降序排列。

### 向量队列机制

搜索模块使用 `VectorQueue` 管理搜索请求队列，支持并发搜索操作。

```mermaid
graph LR
    A["search(query)"] --> B["VectorQueue<br>请求队列"]
    B --> C["HNSW/FAISS<br>向量索引"]
    C --> D["排序过滤"]
    D --> E["返回结果"]
```

### 支持的向量索引后端

| 后端 | 安装包 | 说明 |
|------|--------|------|
| FAISS | `faiss-cpu>=1.7.1.post2` | 默认后端，高性能稠密向量检索 |
| HNSW | `hnswlib>=0.5.0` | 层次可导航小世界图 |
| Annoy | `annoy>=1.16.3` | Spotify 的近似最近邻库 |
| pgvector | `pgvector>=0.4.1` | PostgreSQL 向量扩展 |

资料来源：[setup.py:15-40](https://github.com/neuml/txtai/blob/main/setup.py)

## 配置与扩展

### 模型路径配置

txtai 支持多种模型格式和来源：

```yaml
# app.yml
embeddings:
    path: sentence-transformers/all-MiniLM-L6-v2
```

```python
# 支持的配置方式
embeddings = Embeddings(path="sentence-transformers/all-MiniLM-L6-v2")
embeddings = Embeddings(path="Qwen/Qwen3-Embedding-0.6B")  # Hugging Face 模型
embeddings = Embeddings(path="llama.cpp/model.bin")          # 本地 llama.cpp 模型
```

### 依赖安装

核心依赖（默认安装）：

```python
default = [
    "faiss-cpu>=1.7.1.post2",
    "huggingface-hub>=0.34.0",
    "msgpack>=1.0.7",
    "numpy>=1.18.4",
    "regex>=2022.8.17",
    "pyyaml>=5.3",
    "safetensors>=0.4.5",
    "torch>=2.4",
    "transformers>=4.56.2",
]
```

向量索引扩展依赖：

```python
extras["ann"] = [
    "annoy>=1.16.3",
    "hnswlib>=0.5.0",
    "pgvector>=0.4.1",
    "scikit-learn>=0.23.1",
    "scipy>=1.4.1",
]

extras["vectors"] = [
    "model2vec>=0.3.0",
    "sentence-transformers>=5.0.0",
    "staticvectors>=0.2.0",
]
```

资料来源：[setup.py:15-30](https://github.com/neuml/txtai/blob/main/setup.py)

## 与 RAG 系统集成

向量嵌入系统是检索增强生成（RAG）的基础组件，负责从知识库中检索相关上下文。

```python
# 创建 RAG 管道
rag = RAG(
    embeddings,                    # 嵌入数据库
    "Qwen/Qwen3-0.6B",             # LLM 模型
    system="You are a friendly assistant",
    template=template,
    output="flatten",
)

# 执行问答
result = rag("Summarize BERT advancements", maxlength=2048, stripthink=True)
```

工作流程：

```mermaid
graph TD
    A["用户问题"] --> B["Embeddings.search<br>向量检索"]
    B --> C["获取相关文档"]
    C --> D["组装提示词"]
    D --> E["LLM 生成回答"]
    E --> F["返回结果"]
```

资料来源：[examples/rag_quickstart.py:27-38](https://github.com/neuml/txtai/blob/main/examples/rag_quickstart.py)

## API 方法参考

### 核心方法

| 方法 | 参数 | 返回值 | 说明 |
|------|------|--------|------|
| `index(docs)` | list | None | 构建向量索引 |
| `search(query, limit)` | str, int | list | 执行语义搜索 |
| `batchindex(docs)` | list | None | 批量构建索引 |
| `batchsearch(queries, limit)` | list, int | list | 批量搜索 |
| `save(path)` | str | None | 保存索引到磁盘 |
| `load(path)` | str | None | 从磁盘加载索引 |
| `upsert(docs)` | list | None | 更新/插入文档 |
| `delete(ids)` | list | None | 删除文档 |

### 相似度计算

默认使用余弦相似度进行向量相似度计算，搜索结果按相似度降序排列。分数范围通常为 `[0, 1]`，值越接近 1 表示相似度越高。

## 性能优化建议

1. **批量处理**：使用 `batchindex()` 替代多次 `index()` 调用，减少模型加载开销
2. **序列长度**：根据实际需求调整 `maxlength`，较短的序列处理速度更快
3. **GPU 加速**：确保 CUDA 环境配置正确，GPU 模式可显著提升吞吐量
4. **索引后端选择**：数据量较小时使用 FAISS，超过百万向量时考虑 HNSW

## 与其他系统的比较

txtai 向量嵌入系统与其他向量数据库的关键差异：

| 特性 | txtai | 专用向量数据库 |
|------|-------|---------------|
| 部署复杂度 | 单库部署 | 通常需要独立服务 |
| 功能范围 | 向量+全文+图谱 | 主要聚焦向量检索 |
| 集成 LLM | 原生支持 | 需额外集成 |
| SQL 支持 | 内置 | 部分支持 |
| 扩展性 | 中等 | 高 |

## 总结

txtai 的向量嵌入系统提供了一个功能完整、易于使用的语义搜索基础设施。通过模块化的设计，用户可以灵活选择向量模型、索引后端和存储方案。系统与 RAG、工作流引擎、API 服务等组件深度集成，能够支撑从简单语义搜索到复杂 LLM 应用的全场景需求。

---

<a id='page-ann-index'></a>

## 近似最近邻索引

### 相关页面

相关主题：[向量嵌入系统](#page-embeddings)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/python/txtai/ann/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/ann/__init__.py)
- [src/python/txtai/ann/base.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/ann/base.py)
- [src/python/txtai/ann/dense/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/ann/dense/__init__.py)
- [src/python/txtai/ann/dense/factory.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/ann/dense/factory.py)
</details>

# 近似最近邻索引

## 概述

近似最近邻索引（Approximate Nearest Neighbor，简称 ANN）是 txtai 语义搜索能力的核心组件。该模块提供了在大规模向量数据中进行高效相似性搜索的功能，通过近似算法在精度和性能之间取得平衡。ANN 索引能够将高维向量映射到低维空间，使得在数百万甚至数十亿向量规模下的最近邻查询成为可能，而无需遍历整个数据集。

txtai 的 ANN 模块设计遵循模块化架构，支持多种后端实现，包括 Faiss、Annoy、Hnswlib 等主流向量索引库。索引系统与 txtai 的数据管道紧密集成，支持动态构建和增量更新。

## 架构设计

### 核心组件层次

```mermaid
graph TD
    A[ANN API] --> B[基类 Ann]
    B --> C[Dense ANN]
    C --> D[Faiss Backend]
    C --> E[Annoy Backend]
    C --> F[Hnswlib Backend]
    C --> G[Scann Backend]
    B --> H[Graph ANN]
    D --> I[IndexFactory]
```

### 目录结构

```
src/python/txtai/ann/
├── __init__.py          # 模块导出和公共 API
├── base.py              # 基类 Ann 定义
├── dense/               # 密集向量 ANN 实现
│   ├── __init__.py
│   └── factory.py       # 索引工厂类
└── graph/               # 图结构 ANN 实现
    └── __init__.py
```

资料来源：[src/python/txtai/ann/__init__.py:1-20]()

## 基类设计

### Ann 基类接口

`Ann` 基类定义了所有 ANN 实现必须遵循的统一接口，确保不同后端之间的可替换性。

```python
class Ann:
    def __init__(self, path=None, method=None, components=None, **kwargs):
        # 初始化索引配置
        pass
    
    def index(self, documents):
        # 构建索引
        pass
    
    def search(self, query, limit=10):
        # 执行搜索查询
        pass
    
    def load(self, path):
        # 从磁盘加载索引
        pass
    
    def save(self, path):
        # 将索引保存到磁盘
        pass
```

资料来源：[src/python/txtai/ann/base.py:1-50]()

### 核心方法规范

| 方法名 | 参数 | 返回值 | 说明 |
|--------|------|--------|------|
| `index` | `documents: List[Dict]` | `None` | 构建向量索引 |
| `search` | `query: ndarray, limit: int` | `List[Tuple[int, float]]` | 搜索最近邻 |
| `load` | `path: str` | `None` | 加载持久化索引 |
| `save` | `path: str` | `None` | 保存索引到磁盘 |
| `reset` | `None` | `None` | 清空索引数据 |

## 密集向量索引

### DenseAnn 实现

`DenseAnn` 类是处理密集向量（dense vectors）的主流实现，支持多种后端算法。

```python
class DenseAnn(Ann):
    def __init__(self, path=None, method=None, components=None, **kwargs):
        self.method = method
        self.components = components
        self.ann = None  # 后端索引实例
```

资料来源：[src/python/txtai/ann/dense/__init__.py:1-30]()

### 索引工厂模式

`IndexFactory` 采用工厂模式根据配置动态创建合适的索引后端实例。

```python
class IndexFactory:
    @staticmethod
    def create(config):
        method = config.get("method", "faiss")
        
        if method == "faiss":
            return FaissIndex(config)
        elif method == "annoy":
            return AnnoyIndex(config)
        elif method == "hnsw":
            return HnswlibIndex(config)
        elif method == "scann":
            return ScannIndex(config)
```

资料来源：[src/python/txtai/ann/dense/factory.py:1-40]()

## 支持的后端算法

### 算法对比

| 后端 | 算法类型 | 优点 | 适用场景 | 内存占用 |
|------|----------|------|----------|----------|
| Faiss | IVF-PQ, HNSW | Facebook 出品，成熟稳定 | 大规模生产环境 | 中等 |
| Annoy | 随机投影树 | 内存高效，支持磁盘加载 | 内存受限环境 | 低 |
| Hnswlib | HNSW | 查询速度快 | 实时搜索 | 较高 |
| Scann | ScaNN | Google 出品，精度高 | 高精度需求 | 中等 |

### 配置参数

| 参数名 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `method` | `str` | `"faiss"` | 索引方法 |
| `components` | `dict` | `None` | 后端特定配置 |
| `path` | `str` | `None` | 索引文件路径 |
| `dimensions` | `int` | `None` | 向量维度 |
| `quantization` | `str` | `None` | 量化类型 (PQ, SQ) |

## 工作流程

### 索引构建流程

```mermaid
graph TD
    A[输入文档] --> B[向量化处理]
    B --> C[生成向量数组]
    C --> D[IndexFactory.create]
    D --> E{选择后端}
    E -->|Faiss| F[FaissIndex.index]
    E -->|Annoy| G[AnnoyIndex.index]
    E -->|Hnswlib| H[HnswlibIndex.index]
    F --> I[构建倒排文件]
    G --> J[构建随机树]
    H --> K[构建分层图]
    I --> L[保存索引文件]
    J --> L
    K --> L
```

### 搜索查询流程

```mermaid
graph LR
    A[查询向量] --> B[DenseAnn.search]
    B --> C{选择后端}
    C -->|Faiss| D[nprobe 搜索]
    C -->|Annoy| E[树遍历]
    C -->|Hnswlib| F[图遍历]
    D --> G[返回 Top-K 结果]
    E --> G
    F --> G
```

## 数据模型

### 索引配置结构

```python
{
    "method": "faiss",
    "components": {
        "type": "IVF",
        "nlist": 100,
        "pq": {
            "m": 8,
            "nbits": 8
        }
    },
    "path": "/path/to/index",
    "dimensions": 768
}
```

### 向量存储格式

| 格式 | 后缀 | 说明 |
|------|------|------|
| Faiss Binary | `.bin` | 二进制格式索引文件 |
| Annoy | `.ann` | Annoy 专有格式 |
| Hnswlib | `.hnsw` | 分层可导航小世界图 |
| Scann | `.scann` | Google ScaNN 格式 |

## 集成使用

### 基础用法

```python
from txtai.ann import Ann

# 创建 ANN 索引实例
ann = Ann(method="faiss", dimensions=768)

# 构建索引
documents = [
    {"id": 1, "text": "示例文本1", "vector": vector1},
    {"id": 2, "text": "示例文本2", "vector": vector2}
]
ann.index(documents)

# 搜索查询
results = ann.search(query_vector, limit=10)
```

### 与 txtai 管道集成

txtai 的工作管道自动调用 ANN 模块进行索引和搜索，无需直接操作底层 API。

## 扩展机制

### 自定义后端

开发者可以通过继承 `Ann` 基类实现自定义 ANN 后端：

```python
class CustomAnn(Ann):
    def __init__(self, path=None, method=None, **kwargs):
        super().__init__(path, method, **kwargs)
        # 初始化自定义索引
    
    def index(self, documents):
        # 实现索引构建逻辑
        pass
    
    def search(self, query, limit=10):
        # 实现搜索逻辑
        pass
```

### 注册新后端

在 `IndexFactory` 中注册新的后端类型：

```python
IndexFactory.register("custom", CustomAnn)
```

## 性能优化建议

### 索引构建优化

1. **批量索引**：使用批量处理减少索引构建时间
2. **量化压缩**：启用 PQ 或 SQ 量化以减少内存占用
3. **分区调整**：合理设置 `nlist` 参数平衡精度与性能

### 查询性能优化

1. **nprobe 调优**：Faiss IVF 索引的 `nprobe` 参数直接影响查询精度和速度
2. **向量归一化**：对查询向量进行 L2 归一化可提高余弦相似度计算精度
3. **缓存策略**：对于频繁查询的向量实现结果缓存

## 相关资源

- 官方文档：txtai 语义搜索指南
- 源码仓库：https://github.com/neuml/txtai
- 问题反馈：GitHub Issues

---

<a id='page-scoring'></a>

## 评分系统

### 相关页面

相关主题：[向量嵌入系统](#page-embeddings)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/python/txtai/scoring/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/scoring/__init__.py)
- [src/python/txtai/scoring/bm25.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/scoring/bm25.py)
- [src/python/txtai/scoring/tfidf.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/scoring/tfidf.py)
- [src/python/txtai/scoring/factory.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/scoring/factory.py)
</details>

# 评分系统

## 概述

评分系统（Scoring System）是 txtai 框架中用于计算文本相似度和相关性的核心组件。该系统提供了 BM25、TF-IDF 等经典信息检索算法实现，并与向量索引、图网络和关系数据库共同构成了 txtai 的**嵌入数据库（Embeddings Database）**基础架构。

txtai 的评分系统独立于向量搜索模块，专注于传统信息检索评分方法，为混合搜索场景提供稀疏检索能力。

资料来源：[setup.py](https://github.com/neuml/txtai/blob/main/setup.py)

## 系统架构

### 整体架构

评分系统作为 txtai 的可选扩展模块，位于 `txtai.scoring` 包下，采用模块化工厂模式设计。

```mermaid
graph TD
    A[评分系统入口] --> B[工厂类 Factory]
    B --> C[BM25 评分器]
    B --> D[TF-IDF 评分器]
    C --> E[SQLAlchemy 存储]
    D --> E
    F[embeddings 配置] --> B
```

### 依赖关系

评分系统依赖以下核心库：

| 依赖库 | 版本要求 | 用途 |
|--------|----------|------|
| SQLAlchemy | ≥2.0.20 | 数据持久化和存储后端 |
| NumPy | ≥1.18.4 | 数值计算支持 |

资料来源：[setup.py:55](https://github.com/neuml/txtai/blob/main/setup.py)

## 核心组件

### 1. BM25 评分器

BM25（Best Matching 25）是基于概率模型的信息检索评分算法，是 Okapi BM25 的标准实现。该算法克服了传统 TF-IDF 在文档长度归一化方面的不足。

**主要特性：**
- 可调的词项频率饱和度参数（k1）
- 可调的文档长度归一化参数（b）
- 基于 IDF（逆文档频率）的词项权重计算

### 2. TF-IDF 评分器

TF-IDF（Term Frequency-Inverse Document Frequency）是经典的文本向量化与评分方法。该评分器将文本集合转换为稀疏向量表示，支持余弦相似度计算。

**主要特性：**
- 词频统计与归一化
- 逆文档频率权重计算
- 稀疏向量输出格式

### 3. 工厂类

工厂类（Factory）负责根据配置创建和管理评分器实例，支持运行时动态选择评分算法。

资料来源：[src/python/txtai/scoring/factory.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/scoring/factory.py)

## 安装配置

### 启用评分系统

通过 pip 安装时指定 scoring 额外依赖：

```bash
pip install txtai[scoring]
```

此命令将安装核心 txtai 包及评分系统所需的全部依赖。

### setup.py 配置

```python
extras["scoring"] = ["sqlalchemy>=2.0.20"]
```

资料来源：[setup.py:55](https://github.com/neuml/txtai/blob/main/setup.py)

## 与其他模块的集成

### 与 Embeddings 数据库的集成

评分系统是 txtai 嵌入数据库的核心组成部分。根据项目文档，嵌入数据库是以下三者的联合：

```mermaid
graph LR
    A[嵌入数据库] --> B[向量索引]
    A --> C[图网络]
    A --> D[关系数据库]
    C --> D
    B --> D
```

其中，**关系数据库**层集成了评分系统，用于：
- 存储索引元数据
- 管理文档映射
- 执行结构化查询

资料来源：[README.md](https://github.com/neuml/txtai/blob/main/README.md)

### 与相似度搜索的集成

评分系统通过 `ann` 和 `vectors` 组合，构成 `similarity` 额外依赖：

```python
extras["similarity"] = extras["ann"] + extras["vectors"]
```

这使得 txtai 能够同时支持：
- **密集向量搜索**：基于 transformer 模型生成的嵌入向量
- **稀疏评分搜索**：基于 BM25/TF-IDF 的传统信息检索

资料来源：[setup.py](https://github.com/neuml/txtai/blob/main/setup.py)

## 工作流程

### 索引流程

```mermaid
graph LR
    A[输入文本] --> B[分词处理]
    B --> C[词项统计]
    C --> D[评分计算]
    D --> E[索引存储]
```

### 搜索流程

```mermaid
graph LR
    A[查询语句] --> B[查询处理]
    B --> C[词项匹配]
    C --> D[相关性评分]
    D --> E[结果排序]
    E --> F[返回 Top-K 结果]
```

## 配置参数

### BM25 配置项

| 参数名 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| k1 | float | 1.5 | 词项频率饱和度参数 |
| b | float | 0.75 | 文档长度归一化参数 |
| avgdl | float | 自动计算 | 平均文档长度 |

### TF-IDF 配置项

| 参数名 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| norm | str | "l2" | 向量归一化方式（l1/l2/none） |
| use_idf | bool | True | 是否启用 IDF 权重 |
| smooth_idf | bool | True | 是否平滑 IDF |

## 应用场景

### 语义与关键词混合搜索

将密集向量搜索与稀疏评分搜索结合，实现更精确的检索结果：

- **向量搜索**：捕获语义相似性
- **评分搜索**：精确匹配关键词

### 文档排序与重排序

利用 BM25 或 TF-IDF 分数对候选文档进行重排序，提升最终结果的相关性。

### 知识库检索

作为 RAG（检索增强生成）流程中的检索组件，为大语言模型提供高质量的上下文文档。

## 相关源码文件列表

| 文件路径 | 说明 |
|----------|------|
| `src/python/txtai/scoring/__init__.py` | 评分系统包入口，定义公共 API |
| `src/python/txtai/scoring/bm25.py` | BM25 评分算法实现 |
| `src/python/txtai/scoring/tfidf.py` | TF-IDF 评分算法实现 |
| `src/python/txtai/scoring/factory.py` | 评分器工厂类，负责实例创建 |

## 扩展与自定义

开发者可通过继承基类实现自定义评分器：

1. 实现评分计算逻辑
2. 注册到工厂类
3. 在 embeddings 配置中指定使用

这种设计允许无缝集成第三方评分算法，满足特定业务场景需求。

---

**注意**：本页面基于 txtai 仓库的 setup.py 配置信息和项目文档生成。详细的 API 使用示例请参考官方示例 notebooks。

---

<a id='page-pipeline-llm'></a>

## LLM管道

### 相关页面

相关主题：[文本处理管道](#page-pipeline-text), [工作流引擎](#page-workflow)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/python/txtai/pipeline/llm/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/llm/__init__.py)
- [src/python/txtai/pipeline/llm/llm.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/llm/llm.py)
- [src/python/txtai/pipeline/llm/factory.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/llm/factory.py)
- [src/python/txtai/pipeline/llm/huggingface.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/llm/huggingface.py)
- [src/python/txtai/pipeline/llm/rag.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/llm/rag.py)
</details>

# LLM管道

## 概述

LLM管道是txtai框架中负责与大语言模型（Large Language Model）交互的核心组件。该模块封装了多种语言模型的调用方式，提供了统一的接口来执行文本生成、对话、问答等任务。

LLM管道的主要职责包括：

- **统一抽象**：为不同底层的LLM实现提供一致的API接口
- **生成控制**：支持流式输出、停止词控制、最大长度限制等生成参数
- **对话支持**：自动处理聊天模板，支持聊天模型和普通语言模型
- **多模态扩展**：支持视觉语言模型（VLM）的图像处理能力

## 架构设计

### 组件关系

```mermaid
graph TD
    A[LLM 基类] --> B[HuggingFace 实现]
    A --> C[LiteLLM 实现]
    A --> D[本地 GGML 实现]
    
    E[LLMFactory] -->|创建| A
    
    F[RAG 模块] -->|使用| A
    
    G[Agent 模块] -->|调用| A
```

### 模块结构

| 模块文件 | 功能描述 |
|---------|---------|
| `llm.py` | LLM基类，定义通用接口和生成逻辑 |
| `factory.py` | 工厂类，负责根据配置创建LLM实例 |
| `huggingface.py` | HuggingFace Transformers后端实现 |
| `rag.py` | RAG增强生成模块 |

## 核心类详解

### LLM基类

LLM类是所有LLM实现的父类，提供了语言模型调用的通用逻辑。

```python
# 资料来源：src/python/txtai/pipeline/llm/llm.py
class LLM:
    def __call__(self, text, maxlength=None, stream=False, stop=None, 
                 defaultrole="auto", stripthink=None, **kwargs):
        # 核心生成方法
```

#### 方法说明

| 方法 | 返回类型 | 说明 |
|------|---------|------|
| `__call__` | 生成内容 | 执行LLM生成的主要接口 |
| `ischat` | bool | 判断是否为聊天模型 |
| `isvision` | bool | 判断是否支持视觉任务 |

#### 参数说明

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `text` | str/list | 必需 | 输入文本，支持字符串或列表 |
| `maxlength` | int | None | 最大序列长度 |
| `stream` | bool | False | 是否启用流式输出 |
| `stop` | list | None | 停止字符串列表 |
| `defaultrole` | str | "auto" | 默认角色（auto/user/prompt） |
| `stripthink` | bool | None | 是否去除思考标签 |

#### 输入格式支持

LLM管道支持多种输入格式：

1. **字符串或字符串列表**：直接传入文本内容
2. **字典列表**：遵循聊天模板的role-content格式
3. **嵌套列表**：二维列表形式的对话历史

```python
# 示例：不同输入格式
llm("一个简单的问题")  # 字符串

llm([{"role": "user", "content": "你好"}])  # 字典列表

llm([["user", "今天天气如何?"], ["assistant", "晴天"]]])  # 嵌套列表
```

### HuggingFace实现

HuggingFace实现是对Transformers库的直接封装，支持绝大多数HuggingFace模型。

```python
# 资料来源：src/python/txtai/pipeline/llm/huggingface.py
class HuggingFace:
    def __call__(self, text, prefix=None, maxlength=512, workers=0, 
                 stream=False, stop=None, **kwargs):
```

#### 特殊参数

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `prefix` | str | None | 添加到文本元素前的前缀 |
| `workers` | int | 0 | 并发处理的工作线程数 |

#### 任务类型支持

HuggingFace后端支持多种任务类型：

| 任务标识 | 说明 |
|---------|------|
| `text2text-generation` | 文本到文本生成（使用SequencesPipeline兼容） |
| `text-generation` | 标准文本生成 |
| `summarization` | 摘要生成 |
| `translation` | 翻译任务 |

## 生成控制

### 流式输出

启用流式输出可以实时获取模型生成的片段：

```python
# 启用流式输出
for chunk in llm("写一首诗", stream=True):
    print(chunk, end="", flush=True)
```

流式输出会**自动禁用**思考标签去除功能（`stripthink=False`），确保实时显示生成内容。

### 停止词控制

通过`stop`参数可以指定停止条件：

```python
# 当遇到指定字符串时停止生成
result = llm("回答以下问题", stop=["\n\n", "===END==="])
```

### 思考标签处理

部分模型会输出XML格式的思考过程，默认行为：

| 模式 | 行为 |
|------|------|
| 流式输出（stream=True） | stripthink=False（保留思考内容） |
| 非流式输出 | stripthink=True（自动去除） |

```python
# 手动控制思考标签处理
llm("问题", stripthink=True)   # 去除思考标签
llm("问题", stripthink=False)  # 保留思考标签
```

## RAG增强生成

RAG（检索增强生成）模块将向量检索与LLM生成结合：

```python
# 资料来源：src/python/txtai/pipeline/llm/rag.py
```

### 工作流程

```mermaid
graph LR
    A[用户查询] --> B[向量检索]
    B --> C[相关文档]
    C --> D[构建提示词]
    D --> E[LLM生成]
    E --> F[最终回答]
```

### 配置示例

```yaml
# RAG配置示例
rag:
    embeddings: index.tar
    content: true
    prompt: "根据以下上下文回答问题：\n\n{context}\n\n问题：{query}"
```

## 工厂模式

LLM工厂类负责根据配置动态创建合适的LLM实例：

```python
# 资料来源：src/python/txtai/pipeline/llm/factory.py
```

### 支持的后端类型

| 后端标识 | 说明 |
|---------|------|
| `huggingface` | HuggingFace Transformers模型 |
| `litellm` | LiteLLM统一接口 |
| `ggml` | 本地GGML/GGUF模型 |
| `ollama` | Ollama本地服务 |
| `api` | OpenAI兼容API |

## 使用示例

### 基础文本生成

```python
from txtai.pipeline import LLM

# 创建LLM实例
llm = LLM("meta-llama/Llama-2-7b-chat-hf")

# 简单生成
result = llm("解释量子计算的基本原理")
print(result)
```

### 对话模式

```python
# 带聊天模板的对话
messages = [
    {"role": "system", "content": "你是一个helpful助手"},
    {"role": "user", "content": "什么是向量数据库？"}
]

response = llm(messages)
print(response)
```

### 带RAG的问答

```python
from txtai.pipeline import RAG

# 创建RAG管道
rag = RAG({
    "embeddings": "my-index",
    "llm": "mistralai/Mistral-7B-Instruct-v0.2"
})

# 基于检索的问答
answer = rag("关于项目X的技术细节是什么？")
```

## 依赖要求

LLM管道的基础依赖包括：

```python
# setup.py中的pipeline-llm额外依赖
extras["pipeline-llm"] = [
    "httpx>=0.28.1",
    "litellm>=1.37.16",
    "llama-cpp-python>=0.2.75"
]
```

安装完整LLM支持：

```bash
pip install txtai[pipeline-llm]
```

## 最佳实践

1. **模型选择**：根据硬件条件选择合适的模型量级
2. **批处理**：处理大量文本时使用workers参数启用并行
3. **流式输出**：长文本生成建议启用流式以便及时中断
4. **停止词**：设置合理的停止条件以控制输出长度
5. **错误处理**：实现重试机制应对API临时故障

## 相关资源

- [txtai官方文档](https://neuml.github.io/txtai/)
- [示例笔记本](https://neuml.github.io/txtai/examples)
- [GitHub仓库](https://github.com/neuml/txtai)

---

<a id='page-pipeline-text'></a>

## 文本处理管道

### 相关页面

相关主题：[LLM管道](#page-pipeline-llm), [音频和图像管道](#page-pipeline-audio), [工作流引擎](#page-workflow)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/python/txtai/pipeline/text/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/text/__init__.py)
- [src/python/txtai/pipeline/text/entity.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/text/entity.py)
- [src/python/txtai/pipeline/text/labels.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/text/labels.py)
- [src/python/txtai/pipeline/text/reranker.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/text/reranker.py)
- [src/python/txtai/pipeline/text/summary.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/text/summary.py)
- [src/python/txtai/pipeline/llm/llm.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/llm/llm.py)
- [src/python/txtai/pipeline/hfpipeline.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/hfpipeline.py)
</details>

# 文本处理管道

文本处理管道（Text Pipeline）是txtai框架中用于处理和分析文本数据的核心组件集合。该管道提供了从文本生成摘要、实体识别、标签分类到结果重排序等完整的自然语言处理能力。

## 概述

txtai的文本处理管道是一组基于Transformer模型的处理组件，设计用于执行各类文本分析任务。这些管道可以独立使用，也可以组合成复杂的工作流程来处理文本数据。文本处理管道属于txtai的`pipeline-text`扩展模块，需要额外安装相关依赖。

```mermaid
graph TD
    A[文本输入] --> B[Summary 摘要生成]
    A --> C[Entity 实体识别]
    A --> D[Labels 标签分类]
    A --> E[Reranker 重排序]
    B --> F[结构化输出]
    C --> F
    D --> F
    E --> G[排序后结果]
```

## 核心组件

文本处理管道包含以下核心组件：

| 组件名称 | 类名 | 功能描述 |
|---------|------|---------|
| 摘要生成 | `Summary` | 从文本生成简洁摘要 |
| 实体识别 | `Entity` | 识别文本中的命名实体 |
| 标签分类 | `Labels` | 对文本进行标签分类 |
| 重排序 | `Reranker` | 对搜索结果进行相关性重排序 |

## 摘要生成（Summary）

### 功能说明

摘要生成管道使用预训练的序列到序列模型将长文本压缩为简洁的摘要内容。该组件支持多种输入格式，可以处理单个文档或批量处理多个文档。

### API参数

| 参数 | 类型 | 默认值 | 说明 |
|-----|------|-------|------|
| `path` | str | 必需 | 模型路径或HuggingFace模型标识符 |
| `quantize` | bool | False | 是否量化模型 |
| `gpu` | bool | True | 是否使用GPU |
| `maxlength` | int | 512 | 生成摘要的最大长度 |
| `workers` | int | 0 | 并发工作线程数 |

### 使用示例

```python
from txtai.pipeline import Summary

# 初始化摘要管道
summary = Summary("facebook/bart-large-cnn")

# 生成摘要
text = """长文本内容..."""
result = summary(text)
```

资料来源：[src/python/txtai/pipeline/text/summary.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/text/summary.py)

## 实体识别（Entity）

### 功能说明

实体识别管道用于从文本中提取命名实体及其类型标签。该组件支持两种模式：标准token分类和GLiNER模型。

### GLiNER支持

当检测到使用GLiNER模型时，管道会使用GLiNER库进行实体识别，这提供了更加灵活和高效的实体提取能力。

```python
# GLiNER实体识别示例
entity = Entity("urchan/gliner_multitask_large-v0.1")
entities = entity("Apple公司成立于1976年", labels=["组织", "日期"])
```

### 聚合方法

实体识别支持多种聚合策略来合并多token实体：

| 聚合方法 | 说明 |
|---------|------|
| `simple` | 简单合并（默认） |
| `first` | 取第一个token的分数 |
| `average` | 取平均分数 |
| `max` | 取最大分数 |

### API参数

| 参数 | 类型 | 默认值 | 说明 |
|-----|------|-------|------|
| `path` | str | 必需 | 模型路径 |
| `labels` | list | None | 要识别的实体类型列表 |
| `aggregate` | str | "simple" | 多token实体聚合方法 |
| `flatten` | bool/float | None | 展平输出，可设置分数阈值 |
| `join` | bool | False | 是否连接相邻同类型实体 |
| `workers` | int | 0 | 并发工作线程数 |

资料来源：[src/python/txtai/pipeline/text/entity.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/text/entity.py)

## 标签分类（Labels）

### 功能说明

标签分类管道用于对文本进行分类标签预测。该组件可以将文本分类为一个或多个预定义的类别标签。

### 使用示例

```python
from txtai.pipeline import Labels

# 初始化标签分类器
labels = Labels()

# 单标签分类
result = labels("这部电影非常精彩", labels=["正面", "负面", "中性"])

# 多标签分类
multilabel = labels("新闻内容", labels=["体育", "科技", "娱乐"], multi=True)
```

### 分数阈值

标签分类支持设置分数阈值来过滤低置信度的分类结果：

```python
# 只返回分数大于0.8的结果
result = labels(text, labels=labels_list, threshold=0.8)
```

资料来源：[src/python/txtai/pipeline/text/labels.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/text/labels.py)

## 重排序（Reranker）

### 功能说明

重排序管道用于对搜索结果进行相关性重排序。当基础的向量相似度搜索无法完全满足相关性需求时，可以使用重排序模型进行更精确的排序。

### 工作原理

```mermaid
graph LR
    A[初始搜索结果] --> B[Reranker模型]
    B --> C[相关性评分]
    C --> D[重排序后的结果]
```

### 使用示例

```python
from txtai.pipeline import Reranker

# 初始化重排序模型
reranker = Reranker("cross-encoder/ms-marco-MiniLM-L-6-v2")

# 对搜索结果进行重排序
query = "人工智能应用"
results = [{"id": 1, "text": "机器学习技术"}, {"id": 2, "text": "人工智能算法"}]
reranked = reranker(query, results)
```

### API参数

| 参数 | 类型 | 默认值 | 说明 |
|-----|------|-------|------|
| `path` | str | 必需 | 重排序模型路径 |
| `gpu` | bool | True | 是否使用GPU |
| `batchsize` | int | 32 | 批处理大小 |
| `quantize` | bool | False | 是否量化模型 |

资料来源：[src/python/txtai/pipeline/text/reranker.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/text/reranker.py)

## 管道组合使用

文本处理管道可以组合使用以构建复杂的文本分析流程：

```mermaid
graph TD
    A[原始文本] --> B[Textractor 文本提取]
    B --> C[Entity 实体识别]
    B --> D[Labels 标签分类]
    C --> E[Summary 摘要生成]
    D --> F[结果合并]
    E --> F
    F --> G[最终输出]
```

### 工作流集成

在txtai工作流中，文本处理管道可以作为任务节点使用：

```python
from txtai.workflow import Workflow

# 定义工作流
workflow = Workflow([
    Textractor(),
    Summary(),
    # 更多处理步骤...
])
```

## 依赖项

文本处理管道模块需要以下依赖项：

| 依赖包 | 版本要求 | 说明 |
|-------|---------|------|
| gliner | >=0.2.23 | GLiNER实体识别模型 |
| sentencepiece | >=0.1.91 | 分词工具 |
| staticvectors | >=0.2.0 | 静态向量模型 |
| transformers | >=4.56.2 | 核心Transformer库 |

安装所有文本处理依赖：

```bash
pip install txtai[pipeline-text]
```

资料来源：[setup.py](https://github.com/neuml/txtai/blob/main/setup.py)

## 输入输出格式

### 标准输入格式

文本处理管道支持多种输入格式：

| 格式类型 | 示例 | 说明 |
|---------|------|------|
| 字符串 | `"文本内容"` | 单个文本 |
| 字符串列表 | `["文本1", "文本2"]` | 批量文本 |
| 字典列表 | `[{"text": "..."}]` | 带元数据的文本 |

### 输出格式

处理结果通常以列表或字典格式返回：

```python
# 实体识别输出示例
[
    {"text": "Apple", "label": "组织", "score": 0.95, "start": 0, "end": 5},
    {"text": "1976年", "label": "日期", "score": 0.89, "start": 15, "end": 20}
]

# 标签分类输出示例
[("正面", 0.92), ("中性", 0.06), ("负面", 0.02)]
```

## 最佳实践

### 性能优化

1. **批量处理**：使用批量输入可以显著提高处理速度
2. **GPU加速**：确保CUDA环境正确配置以启用GPU加速
3. **模型量化**：对于大模型，使用量化可以减少内存占用

### 准确性提升

1. 选择与任务领域匹配的专业模型
2. 合理设置标签列表和分数阈值
3. 结合多种管道组件进行综合分析

### 错误处理

```python
try:
    result = pipeline(input_text)
except Exception as e:
    logger.error(f"处理失败: {e}")
    # 降级处理或返回默认值
```

## 扩展文本管道

开发者可以通过继承基础管道类来创建自定义文本处理组件：

```python
from txtai.pipeline import HFPipeline

class CustomTextProcessor(HFPipeline):
    def __init__(self, path=None, quantize=False, gpu=True, **kwargs):
        super().__init__("text-classification", path, quantize, gpu, **kwargs)
    
    def __call__(self, text, **kwargs):
        # 自定义处理逻辑
        return super().__call__(text, **kwargs)
```

资料来源：[src/python/txtai/pipeline/hfpipeline.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/hfpipeline.py)

---

<a id='page-pipeline-audio'></a>

## 音频和图像管道

### 相关页面

相关主题：[文本处理管道](#page-pipeline-text), [工作流引擎](#page-workflow)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/python/txtai/pipeline/audio/transcription.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/audio/transcription.py)
- [src/python/txtai/pipeline/audio/texttoaudio.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/audio/texttoaudio.py)
- [src/python/txtai/pipeline/data/textractor.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/data/textractor.py)
- [src/python/txtai/pipeline/image/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/image/__init__.py)
- [src/python/txtai/pipeline/image/caption.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/image/caption.py)
- [src/python/txtai/pipeline/hfpipeline.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/pipeline/hfpipeline.py)
</details>

# 音频和图像管道

## 概述

txtai 的音频和图像管道是框架多媒体处理能力的核心组成部分，分别位于 `txtai.pipeline.audio` 和 `txtai.pipeline.image` 模块中。这些管道支持从音频文件中提取文本内容（语音转文本），以及从文本生成音频（文本转语音）和图像描述（图像字幕生成）。

音频管道基于 Hugging Face Transformers 框架构建，通过 `HFPipeline` 基类提供统一的接口。图像管道同样继承自 `HFPipeline`，使用计算机视觉模型处理图像数据。两者都支持 GPU 加速和模型量化，能够处理单个文件或批量数据。

## 音频管道

### 架构设计

音频管道采用模块化设计，主要包含两个核心组件：

```mermaid
graph TD
    A[音频输入] --> B{数据类型判断}
    B -->|文件路径| C[FileToHTML/直接加载]
    B -->|原始音频数据| D[Signal处理模块]
    C --> E[Transcription管道]
    D --> E
    E --> F[Speech Recognition Pipeline]
    F --> G[转录文本输出]
```

### Transcription 模块

`Transcription` 类负责将音频内容转录为文本。该模块支持两种后端实现：当 `scipy` 和 `soundfile` 库可用时，使用本地信号处理；否则回退到其他可用方案。资料来源：[transcription.py:1-20]()

```python
class Transcription(HFPipeline):
    """
    Transcribes audio files or data to text.
    """
```

#### 核心参数说明

| 参数 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| path | str | 模型路径或 Hugging Face 模型标识符 | None |
| quantize | bool | 是否量化模型以减少内存占用 | False |
| gpu | bool | 是否使用 GPU 进行推理 | True |
| model | str | 指定具体模型变体 | None |

#### 主要方法

`__call__(audio, rate=None, chunk=10, join=True, **kwargs)` 方法是 Transcription 的核心接口：

```python
def __call__(self, audio, rate=None, chunk=10, join=True, **kwargs):
    """
    Transcribes audio files or data to text.

    Args:
        audio: audio|list
        rate: sample rate, only required with raw audio data
        chunk: process audio in chunk second sized segments
        join: if True (default), combine each chunk back together into a single text output.
              When False, chunks are returned as a list of dicts, each having raw associated audio and
              sample rate in addition to text
    """
```

该方法支持三种处理模式：

- **完整转录**：设置 `chunk=0` 可对整个音频文件进行一次性处理
- **分段转录**：设置 `chunk` 值（秒）可按指定时长分段处理长音频
- **批量转录**：传入音频列表可并行处理多个文件

#### 输入输出格式

| 输入类型 | 输入示例 | 输出类型 | 输出示例 |
|----------|----------|----------|----------|
| 单个音频文件路径 | `"/path/to/audio.wav"` | str | `"转录的文本内容"` |
| 音频文件列表 | `["file1.wav", "file2.wav"]` | list | `["文本1", "文本2"]` |
| 原始音频数据 | `(numpy数组, 采样率)` | str/list | 根据输入格式确定 |

### TextToAudio 模块

`TextToAudio` 类执行相反的操作，将文本内容转换为语音音频。该模块继承自 `HFPipeline`，使用 text-to-speech 模型生成音频波形。资料来源：[texttoaudio.py:1-30]()

```python
class TextToAudio(HFPipeline):
    """
    Generates audio from text.
    """
```

#### 参数配置

| 参数 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| path | str | TTS 模型路径 | None |
| quantize | bool | 量化模型 | False |
| gpu | bool | GPU 加速 | True |
| model | str | 模型标识符 | None |
| rate | int | 目标采样率 | None（使用模型默认采样率） |

#### 工作流程

```mermaid
graph LR
    A[输入文本] --> B[TextToAudio Pipeline]
    B --> C[generate audio]
    C --> D{rate 参数设置?}
    D -->|是| E[重采样到目标采样率]
    D -->|否| F[使用模型原生采样率]
    E --> G[(音频输出)]
    F --> G
```

#### 音频转换处理

当设置 `rate` 参数时，`convert` 方法会执行采样率转换：

```python
def convert(self, result):
    """
    Converts audio result to target sample rate for this pipeline, if set.

    Args:
        result: dict with audio samples and sample rate

    Returns:
        audio with converted sample rate
    """
```

返回格式为元组 `(audio_data, sample_rate)`，可直接用于音频播放或保存。

## 图像管道

### ImageCaption 模块

`ImageCaption` 类使用计算机视觉模型为图像生成描述性文本。该模块同样继承自 `HFPipeline`，使用图像字幕生成模型。资料来源：[caption.py]()

```python
class ImageCaption(HFPipeline):
    """
    Image captioning pipeline that generates descriptions for images.
    """
```

### 图像处理流程

```mermaid
graph TD
    A[图像输入] --> B{输入类型判断}
    B -->|URL| C[HTTP 请求获取]
    B -->|文件路径| D[本地文件读取]
    B -->|PIL Image| E[直接处理]
    B -->|Base64| F[解码处理]
    C --> G[图像预处理]
    D --> G
    E --> G
    F --> G
    G --> H[Vision Transformer 模型]
    H --> I[生成字幕/描述]
    I --> J[文本输出]
```

## 统一 API 接口

所有管道都遵循统一的调用约定，简化了多模态处理的复杂性：

### HFPipeline 基类

音频和图像管道都继承自 `HFPipeline` 基类，该基类提供：

- 统一的模型加载和缓存机制
- GPU/CPU 自动检测和设备分配
- 批量处理支持
- 流式输出支持（部分管道）

### 通用参数

| 参数 | 说明 | 适用管道 |
|------|------|----------|
| path | 模型路径或 Hugging Face 模型 ID | 所有管道 |
| quantize | 启用 4-bit/8-bit 量化 | 所有管道 |
| gpu | 启用 GPU 推理 | 所有管道 |
| model | 指定具体模型配置 | 所有管道 |

## 依赖要求

音频和图像管道需要安装特定的依赖包。通过 `pipeline-audio` 和 `pipeline-image` extras 可一键安装：

```bash
pip install txtai[pipeline-audio]
pip install txtai[pipeline-image]
```

### 音频管道依赖

根据 `setup.py` 配置：

```python
extras["pipeline-audio"] = [
    "onnx>=1.11.0",
    "onnxruntime>=1.11.0",
    "scipy>=1.4.1",
    "sounddevice>=0.5.0",
    "soundfile>=0.10.3.post1",
    "ttstokenizer>=1.1.0",
    "webrtcvad-wheels>=2.0.14",
]
```

### 图像管道依赖

```python
extras["pipeline-image"] = [
    "imagehash>=4.2.1",
    "pillow>=7.1.2",
    "timm>=0.4.12",
]
```

## 实际应用示例

### 音频转录

```python
from txtai.pipeline import Transcription

# 初始化转录管道
transcribe = Transcription("facebook/wav2vec2-base-960h")

# 单个文件转录
text = transcribe("/path/to/audio.wav")

# 分段处理长音频（每段30秒）
text = transcribe("/path/to/long_audio.wav", chunk=30)

# 批量处理
texts = transcribe(["file1.wav", "file2.wav"])
```

### 文本转语音

```python
from txtai.pipeline.audio import TextToAudio

# 初始化 TTS 管道
tts = TextToAudio("facebook/fastspeech2-en-ljspeech")

# 生成音频
audio, rate = tts("Hello, this is a text to speech conversion.")

# 指定采样率
audio, rate = tts("Custom sample rate audio", rate=22050)
```

## 工作流集成

音频和图像管道可以无缝集成到 txtai 的工作流系统中，支持复杂的多模态处理流程：

```python
from txtai import Workflow

# 创建包含音频处理的工作流
workflow = Workflow([
    {"action": "transcription", "task": "audio"},
    {"action": "translation", "task": "text"},
])
```

## 最佳实践

1. **模型选择**：根据精度和速度需求选择合适的预训练模型
2. **GPU 加速**：处理大量数据时启用 GPU 以提升性能
3. **批量处理**：使用列表输入进行批量处理，提高吞吐量
4. **内存管理**：长音频文件使用分段处理避免内存溢出
5. **采样率配置**：确保输出音频采样率符合目标应用需求

## 总结

txtai 的音频和图像管道提供了强大且统一的多媒体处理能力。通过继承 `HFPipeline` 基类，这些管道实现了标准化的接口和一致的配置方式。Transcription 支持灵活的音频转文本处理，TextToAudio 提供文本到语音的生成能力，ImageCaption 则实现图像描述生成。这些组件可以独立使用，也可以集成到更复杂的工作流中，支持端到端的多模态 AI 应用开发。

---

<a id='page-workflow'></a>

## 工作流引擎

### 相关页面

相关主题：[核心组件](#page-components)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/python/txtai/workflow/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/workflow/__init__.py)
- [src/python/txtai/workflow/base.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/workflow/base.py)
- [src/python/txtai/workflow/factory.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/workflow/factory.py)
- [src/python/txtai/workflow/task/__init__.py](https://github.com/neuml/txtai/blob/main/src/python/txtai/workflow/task/__init__.py)
</details>

# 工作流引擎

## 概述

txtai 工作流引擎是一个强大的组件编排框架，用于构建复杂的数据处理管道。它允许用户将多个处理组件（如文本提取、摘要生成、翻译等）串联成可配置的工作流程，支持并行处理、并发执行、结果合并等高级功能。

工作流引擎的核心设计理念是**声明式任务编排**：用户通过定义任务列表来描述数据处理流程，系统自动管理任务间的数据传递和执行顺序。

## 核心架构

### 组件层次结构

```
┌─────────────────────────────────────────────────────────────┐
│                      Workflow                                │
│  ┌───────────────────────────────────────────────────────┐  │
│  │                    Task[]                              │  │
│  │  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐  │  │
│  │  │ Task 1  │→ │ Task 2  │→ │ Task 3  │→ │ Task N  │  │  │
│  │  │(动作函数)│  │(动作函数)│  │(动作函数)│  │(动作函数)│  │  │
│  │  └─────────┘  └─────────┘  └─────────┘  └─────────┘  │  │
│  └───────────────────────────────────────────────────────┘  │
│                              ↓                               │
│  ┌───────────────────────────────────────────────────────┐  │
│  │              任务基类 (Task Base)                       │  │
│  │  - action: 处理动作                                     │  │
│  │  - select: 数据过滤器                                   │  │
│  │  - initialize/finalize: 生命周期钩子                     │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
```

### 核心类说明

| 类名 | 文件位置 | 功能描述 |
|------|----------|----------|
| Workflow | workflow/__init__.py | 工作流主控制器，管理任务执行流程 |
| Task | workflow/task/base.py | 任务基类，定义任务通用接口 |
| TemplateTask | workflow/task/template.py | 模板任务，支持 prompt 模板化处理 |

## 工作流执行模型

### 数据处理流程

```mermaid
graph LR
    A[输入数据] --> B[Task 1]
    B --> C[Task 2]
    C --> D[Task 3]
    D --> E[输出结果]
    
    F[初始化动作] -.-> A
    E -.-> G[最终化动作]
```

### 并发处理模型

```mermaid
graph TD
    subgraph 并发模式
        A[输入列表] --> B{并发方式}
        B -->|Thread| C[线程池执行]
        B -->|Process| D[进程池执行]
        B -->|默认| E[顺序执行]
    end
    
    C --> F[结果聚合]
    D --> F
    E --> F
```

## Task 基类详解

### 初始化参数

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| action | callable/list | [] | 要执行的处理动作 |
| select | callable/list | None | 数据过滤选择器 |
| unpack | bool | True | 是否解包数据元组 |
| column | int | None | 选择元组的列索引 |
| merge | str | "hstack" | 多动作输出合并模式 |
| initialize | callable | None | 执行前初始化动作 |
| finalize | callable | None | 执行后终结动作 |
| concurrency | str | None | 并发方式 ("thread"/"process") |
| onetomany | bool | True | 启用一对多转换 |

### 核心方法

```python
def __init__(
    self,
    action=None,
    select=None,
    unpack=True,
    column=None,
    merge="hstack",
    initialize=None,
    finalize=None,
    concurrency=None,
    onetomany=True,
    **kwargs,
)
```

**生命周期钩子**：

- **initialize**: 在处理开始前执行，常用于加载模型、资源初始化
- **finalize**: 在处理结束后执行，常用于资源释放、结果后处理

资料来源：[src/python/txtai/workflow/task/base.py:22-50]()

## 模板任务 (TemplateTask)

TemplateTask 继承自 Task 基类，专门用于生成 LLM 提示词模板。

### 模板处理规则

```mermaid
graph TD
    A[输入数据] --> B{数据类型判断}
    B -->|dict| C[作为命名参数传入]
    B -->|tuple| D[映射为 arg0-argN]
    B -->|其他| E[作为 {text} 参数]
    
    C --> F[TemplateFormatter 格式化]
    D --> F
    E --> F
    F --> G[渲染后的模板字符串]
```

### 模板注册方法

```python
def register(self, template=None, rules=None, strict=True):
    # template: 提示词模板文本
    # rules: 参数处理规则
    # strict: 是否要求所有输入被模板消费
```

支持的模板参数注入方式：

| 输入类型 | 处理方式 | 示例 |
|----------|----------|------|
| dict | 展开为命名参数 | `{"topic": "AI", "length": 100}` |
| tuple | 映射为 arg0-argN | `("AI", 100)` → arg0="AI", arg1=100 |
| 其他 | 作为 {text} 参数 | `input` → {text}=input |

资料来源：[src/python/txtai/workflow/task/template.py:10-45]()

## 工作流构建示例

### 基础使用模式

```python
from txtai import Workflow
from txtai.pipeline import Summary, Textractor, Translation
from txtai.workflow import Task

# 步骤1: 定义处理管道
textractor = Textractor(backend="docling", headers={"user-agent": "Mozilla/5.0"})
summary = Summary()
translate = Translation()

# 步骤2: 构建工作流
workflow = Workflow([
    Task(textractor),      # 提取文本
    Task(summary),         # 生成摘要
    Task(lambda inputs: [translate(x, "fr") for x in inputs])  # 翻译
])

# 步骤3: 执行工作流
results = list(workflow(["https://example.com/article"]))
```

### 使用 LLM 完成任务

```python
from txtai import LLM, Workflow
from txtai.pipeline import Textractor
from txtai.workflow import Task

textractor = Textractor(backend="docling")
llm = LLM("Qwen/Qwen3-4B-Instruct")

workflow = Workflow([
    Task(textractor),
    Task(lambda inputs: llm([f"Summarize in 40 words: {x}" for x in inputs]))
])

list(workflow(["https://example.com"]))
```

资料来源：[examples/workflow_quickstart.py:1-45]()

## 内置任务类型

### UrlTask

专门用于处理 URL 链接的预配置任务，自动调用 Textractor 进行内容提取。

```python
from txtai.workflow import UrlTask, Task, Workflow
from txtai.pipeline import Textractor, Summary

workflow = Workflow([
    UrlTask(Textractor(paragraphs=True, minlength=100, join=True)),
    Task(Summary("sshleifer/distilbart-cnn-12-6"))
])

# 处理 URL
url = "https://neuml.com"
summary = list(workflow([url]))[0]
```

### 任务组合模式

| 组合方式 | 说明 | 适用场景 |
|----------|------|----------|
| 顺序执行 | 任务列表按顺序传递 | 管道式处理 |
| 并行执行 | concurrency="thread"/"process" | CPU/IO 密集型任务 |
| 一对多 | onetomany=True | 数据分割/扩展 |

资料来源：[examples/article.py:1-55]()

## 工作流配置

### 依赖项配置

工作流引擎通过 setup.py 管理可选依赖：

```python
extras["workflow"] = [
    "apache-libcloud>=3.3.1",
    "croniter>=1.2.0",
    "openpyxl>=3.0.9",
    "pandas>=1.1.0",
    "pillow>=7.1.2",
    "requests>=2.26.0",
    "xmltodict>=0.12.0",
]
```

### 安装方式

```bash
# 基础安装
pip install txtai

# 包含工作流依赖
pip install txtai[workflow]
```

## 高级特性

### 数据选择与过滤

```python
# 使用 select 参数过滤数据
workflow = Workflow([
    Task(action=processor, select=lambda x: x.get("valid")),
])
```

### 结果合并策略

| 合并模式 | 说明 |
|----------|------|
| hstack | 水平堆叠（默认） |
| 自定义 | 通过 merge 参数指定合并函数 |

### 生命周期管理

```python
def init_model():
    """初始化动作 - 加载模型"""
    return load_heavy_model()

def cleanup(results):
    """终结动作 - 清理资源"""
    return post_process(results)

workflow = Workflow([
    Task(action=process, initialize=init_model, finalize=cleanup)
])
```

## 最佳实践

### 性能优化建议

1. **合理选择并发模式**：CPU 密集型用 "process"，IO 密集型用 "thread"
2. **减少不必要的数据转换**：使用 unpack=False 保持数据格式
3. **使用缓存**：对于重复执行的工作流，考虑缓存模型加载

### 错误处理

```python
workflow = Workflow([
    Task(action=risky_processor),
    Task(action=fallback_processor),  # 异常时使用后备方案
])
```

### 与 LLM 集成

工作流引擎是构建 RAG（检索增强生成）管道的基础组件：

```mermaid
graph LR
    A[文档] --> B[Textractor]
    B --> C[分割器]
    C --> D[Embedding]
    D --> E[(向量数据库)]
    E --> F[检索]
    F --> G[LLM 生成]
```

## 总结

txtai 工作流引擎提供了灵活、高效的组件编排能力，其核心特点包括：

- **声明式配置**：通过任务列表声明处理流程
- **丰富的数据转换**：支持多种数据格式和合并策略
- **生命周期管理**：initialize/finalize 钩子支持资源管理
- **并发执行**：支持线程和进程两种并发模式
- **与 LLM 深度集成**：可无缝连接语言模型处理

工作流引擎是构建复杂 AI 应用的核心基础设施，特别适用于文档处理管道、RAG 系统和多阶段数据处理场景。

---

---

## Doramagic 踩坑日志

项目：neuml/txtai

摘要：发现 22 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 来源证据：Add `txtai_minimal` package。

## 1. 安装坑 · 来源证据：Add `txtai_minimal` package

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Add `txtai_minimal` package
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_4e4050b59fdf4d51ac21e82d248e589e | https://github.com/neuml/txtai/issues/1090 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 2. 安装坑 · 来源证据：Add custom Captions implementation

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Add custom Captions implementation
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_ff6fe05065564e85a549d7656b85a852 | https://github.com/neuml/txtai/issues/1084 | 来源类型 github_issue 暴露的待验证使用条件。

## 3. 安装坑 · 来源证据：Add custom Questions pipeline implementation

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Add custom Questions pipeline implementation
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_fa68ea29089d497bb8278c3c360c363c | https://github.com/neuml/txtai/issues/1087 | 来源类型 github_issue 暴露的待验证使用条件。

## 4. 安装坑 · 来源证据：Add custom Sequences pipeline implementation

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Add custom Sequences pipeline implementation
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_0099afb385ef498d8020521bbf3e9e64 | https://github.com/neuml/txtai/issues/1086 | 来源类型 github_issue 暴露的待验证使用条件。

## 5. 安装坑 · 来源证据：Add custom Summary pipeline implementation

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Add custom Summary pipeline implementation
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_9d8f75c31fc6450d8659b310f25d0bf4 | https://github.com/neuml/txtai/issues/1085 | 来源类型 github_issue 暴露的待验证使用条件。

## 6. 安装坑 · 来源证据：Add minimal Docker build script

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Add minimal Docker build script
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_38e1e56a991b412bbc749d2c0b687d54 | https://github.com/neuml/txtai/issues/1092 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。

## 7. 安装坑 · 来源证据：Make `transformers` package optional for minimal install

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Make `transformers` package optional for minimal install
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_d755829200de4d93b2f4d2f71b36aaf1 | https://github.com/neuml/txtai/issues/1091 | 来源类型 github_issue 暴露的待验证使用条件。

## 8. 安装坑 · 来源证据：Reduce dependencies to just `numpy` for minimal install

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Reduce dependencies to just `numpy` for minimal install
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_395b735968ab4ec8ad849070d43cd18f | https://github.com/neuml/txtai/issues/1093 | 来源类型 github_issue 暴露的待验证使用条件。

## 9. 安装坑 · 来源证据：Support minimal install for edge devices

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Support minimal install for edge devices
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_3ec8e039baf4412888ed3ac543ea1361 | https://github.com/neuml/txtai/issues/1089 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 10. 安装坑 · 来源证据：Various training pipeline fixes for v5

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Various training pipeline fixes for v5
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_b47325d7496248a993d980c3d59f3269 | https://github.com/neuml/txtai/issues/1088 | 来源类型 github_issue 暴露的待验证使用条件。

## 11. 安装坑 · 来源证据：Zero dependency minimal install

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Zero dependency minimal install
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_7839a465e7e64f94acfff001c1da978c | https://github.com/neuml/txtai/issues/1094 | 来源类型 github_issue 暴露的待验证使用条件。

## 12. 安装坑 · 来源证据：v9.9.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v9.9.0
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_8b842ce68a1c4c1ab0a40a3ed1fd213c | https://github.com/neuml/txtai/releases/tag/v9.9.0 | 来源类型 github_release 暴露的待验证使用条件。

## 13. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:286301447 | https://github.com/neuml/txtai | README/documentation is current enough for a first validation pass.

## 14. 运行坑 · 来源证据：v9.7.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v9.7.0
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_e3f61e41f6e84b9b9ee33d5e18dbff63 | https://github.com/neuml/txtai/releases/tag/v9.7.0 | 来源类型 github_release 暴露的待验证使用条件。

## 15. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:286301447 | https://github.com/neuml/txtai | last_activity_observed missing

## 16. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:286301447 | https://github.com/neuml/txtai | no_demo; severity=medium

## 17. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:286301447 | https://github.com/neuml/txtai | no_demo; severity=medium

## 18. 安全/权限坑 · 来源证据：Add LiteRT-LM LLM

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add LiteRT-LM LLM
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_8731971fd8404df082f75ecf565fef8b | https://github.com/neuml/txtai/issues/1095 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 19. 安全/权限坑 · 来源证据：v9.6.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v9.6.0
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_fe429d6152304930bda149c4fbd35318 | https://github.com/neuml/txtai/releases/tag/v9.6.0 | 来源类型 github_release 暴露的待验证使用条件。

## 20. 安全/权限坑 · 来源证据：v9.8.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v9.8.0
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_8bebd6701b454baaae22d73522ce9704 | https://github.com/neuml/txtai/releases/tag/v9.8.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 21. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:286301447 | https://github.com/neuml/txtai | issue_or_pr_quality=unknown

## 22. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:286301447 | https://github.com/neuml/txtai | release_recency=unknown

<!-- canonical_name: neuml/txtai; human_manual_source: deepwiki_human_wiki -->
