FastGPT-API文件库接口开发文档

1. 背景

本地部署了 FastGPT ,用于实现知识库问答功能。由于本地知识库中的文件数量较多,逐一手动添加文件较为繁琐,因此使用FastGPT知识库中的 API 文件库功能以连接本地文件系统,从而避免手动上传文件。通过 FastGPT 提供的 API 文件库接口,动态获取本地文件系统中的文件和文件夹,并将其轻松导入知识库中。

本文档将详细介绍如何开发一个符合 FastGPT 要求的 API 文件库接口,并解决在开发过程中可能遇到的问题。


2. 接口规范

FastGPT 的 API 文件库接口需要实现以下三个功能:

2.1 获取文件树

  • 接口路径: /v1/file/list

  • 请求方法: POST

  • 请求参数:

    • parentId (可选): 父级目录的 ID,用于获取指定目录下的文件和文件夹。
    • searchKey (可选): 搜索关键词,用于过滤文件和文件夹。
  • 响应格式:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    {
    "success": true,
    "message": "File list retrieved successfully",
    "data": [
    {
    "id": "文件或文件夹的完整路径",
    "parentId": "父级目录的完整路径",
    "name": "文件或文件夹的名称",
    "type": "file | folder",
    "updateTime": "文件或文件夹的最后修改时间",
    "createTime": "文件或文件夹的创建时间"
    }
    ]
    }

2.2 获取单个文件内容

  • 接口路径: /v1/file/content

  • 请求方法: GET

  • 请求参数:

    • id: 文件的完整路径。
  • 响应格式:

    1
    2
    3
    4
    5
    6
    7
    {
    "success": true,
    "message": "File content retrieved successfully",
    "data": {
    "content": "文件内容"
    }
    }

2.3 获取文件阅读链接

  • 接口路径: /v1/file/read

  • 请求方法: GET

  • 请求参数:

    • id: 文件的完整路径。
  • 响应格式:

    1
    2
    3
    4
    5
    6
    7
    {
    "success": true,
    "message": "File read link generated successfully",
    "data": {
    "url": "文件访问链接"
    }
    }

3. 实现步骤

3.1 安装依赖

首先,安装所需的 Node.js 依赖:

1
npm install express body-parser cors

3.2 创建 Express 服务

创建一个 Express 服务,并实现上述三个接口。以下是完整的代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const fs = require('fs');
const path = require('path');

// 配置变量
const CONFIG = {
// 服务端口
PORT: 5000,

// 本地文件夹路径
LOCAL_FOLDER_PATH: 'D:\\OneDrive\\Obsidian\\Obsidian\\考研_408',

// 需要包含的文件类型(扩展名),若不空则仅包含以下文件类型,若为空则获取除EXCLUDE_EXTENSIONS外的所有文件类型
INCLUDE_EXTENSIONS: [],

// 需要排除的文件类型(扩展名)
EXCLUDE_EXTENSIONS: ['.xmind', '.png','.jpg','.mp4','.canvas','.zip','.json','.bin'],

// 需要排除的文件夹路径(相对于 LOCAL_FOLDER_PATH)
EXCLUDE_FOLDERS: [
'copilot-conversations',
'copilot-custom-prompts',
'Excalidraw',
'其他文档',
'.obsidian',
'.trash'
]
};

const app = express();

app.use(bodyParser.json());
app.use(cors());

// 获取文件树
app.post('/v1/file/list', (req, res) => {
const { parentId, searchKey } = req.body;
console.log('Fetching file list with parentId:', parentId, 'and searchKey:', searchKey);

// 如果 parentId 为 null,从根目录开始获取文件树
let dir = parentId ? path.resolve(CONFIG.LOCAL_FOLDER_PATH, parentId) : CONFIG.LOCAL_FOLDER_PATH;

// 调试信息:打印实际路径
console.log('Resolved directory path:', dir);

if (!fs.existsSync(dir)) {
return res.status(404).json({
success: false,
message: 'Directory not found'
});
}

const files = fs.readdirSync(dir);

const fileList = files.map(file => {
const filePath = path.join(dir, file);
const stats = fs.statSync(filePath);

// 获取文件的扩展名
const ext = path.extname(file).toLowerCase();

// 如果是文件夹,检查是否需要排除
if (stats.isDirectory()) {
// 检查文件夹路径是否在 EXCLUDE_FOLDERS 中
const relativePath = path.relative(CONFIG.LOCAL_FOLDER_PATH, filePath);
if (CONFIG.EXCLUDE_FOLDERS.includes(relativePath)) {
// 排除该文件夹
return null;
}

return {
id: filePath,
parentId: parentId,
name: file,
type: 'folder',
updateTime: stats.mtime,
createTime: stats.birthtime
};
}

// 文件过滤逻辑优化
let includeFile = true; // 默认包含文件

if (CONFIG.INCLUDE_EXTENSIONS.length > 0) {
// 如果 INCLUDE_EXTENSIONS 不为空,则只包含指定的文件类型
includeFile = CONFIG.INCLUDE_EXTENSIONS.includes(ext);
} else {
// 如果 INCLUDE_EXTENSIONS 为空,则排除 EXCLUDE_EXTENSIONS 中的文件类型
includeFile = !CONFIG.EXCLUDE_EXTENSIONS.includes(ext);
}

if (includeFile) {
return {
id: filePath,
parentId: parentId,
name: file,
type: 'file',
updateTime: stats.mtime,
createTime: stats.birthtime
};
}

// 如果不满足条件,则排除
return null;

}).filter(file => file !== null); // 过滤掉被排除的文件

res.json({
success: true,
message: 'File list retrieved successfully',
data: fileList
});
});

// 获取单个文件内容
app.get('/v1/file/content', (req, res) => {
const { id } = req.query;
console.log('Fetching file content for id:', id);

const filePath = path.resolve(CONFIG.LOCAL_FOLDER_PATH, id);

if (fs.existsSync(filePath)) {
const content = fs.readFileSync(filePath, 'utf-8');
res.json({
success: true,
message: 'File content retrieved successfully',
data: {
content: content // 返回文件内容
}
});
} else {
res.status(404).json({
success: false,
message: 'File not found'
});
}
});

// 获取文件阅读链接
app.get('/v1/file/read', (req, res) => {
const { id } = req.query;
console.log('Generating read link for id:', id);

const filePath = path.resolve(CONFIG.LOCAL_FOLDER_PATH, id);

if (fs.existsSync(filePath)) {
res.json({
success: true,
message: 'File read link generated successfully',
data: {
url: `http://localhost:${CONFIG.PORT}/v1/file/content?id=${encodeURIComponent(id)}` // 返回文件访问链接
}
});
} else {
res.status(404).json({
success: false,
message: 'File not found'
});
}
});

app.listen(CONFIG.PORT, () => {
console.log(`Server is running on port ${CONFIG.PORT}`);
});

4. 关键点说明

4.1 路径处理

  • 使用 path.resolve 替代 path.join,确保路径拼接能够正确处理 Windows 风格的反斜杠路径。
  • 在处理 parentId 时,将其转换为标准路径格式(如使用 path.normalize)。

4.2 调试信息

  • /v1/file/list 接口中,打印实际解析的路径,方便调试。

4.3 路径编码

  • /v1/file/read 接口中,对 id 进行 URL 编码,避免路径中的特殊字符导致问题。

5. 测试步骤

5.1 启动服务

在命令行中运行以下命令启动服务:

1
node server.js

使用 pm2 后台运行

pm2 是一个强大的 Node.js 进程管理工具,可以让你轻松管理后台运行的 Node.js 服务,并且支持自动重启、日志管理等功能。

安装 pm2

1
npm install -g pm2

使用 pm2 启动服务

1
pm2 start server.js

常用命令

  • 查看运行中的服务:

    1
    pm2 list
  • 停止服务:

    1
    pm2 stop server.js
  • 重启服务:

    1
    pm2 restart server.js
  • 查看日志:

    1
    pm2 logs

pm2 会自动将服务放到后台运行,即使关闭终端也不会中断服务。


5.2 测试根目录中的文件

使用 Postman 或 cURL 发送以下请求:

1
2
3
4
5
6
curl --location --request POST 'http://localhost:5000/v1/file/list' \
--header 'Content-Type: application/json' \
--data-raw '{
"parentId": null,
"searchKey": ""
}'

5.3 测试子文件夹中的文件

  • 在返回的文件树中,找到一个子文件夹的 id
  • 使用该 id 作为 parentId,再次调用 /v1/file/list 接口,获取子文件夹中的文件和文件夹。

5.4 测试文件内容接口

使用 Postman 或 cURL 发送以下请求:

1
curl --location --request GET 'http://localhost:5000/v1/file/content?id=子目录/文件名.txt'

6. 常见问题排查

6.1 404 错误

  • 检查 parentId 是否正确传递,并确保路径拼接正确。
  • 确保文件或文件夹存在于指定路径中。

6.2 路径格式问题

  • 确保路径格式符合操作系统的要求(如 Windows 使用反斜杠,Linux 使用正斜杠)。
  • 使用 path.resolvepath.normalize 处理路径。

6.3 文件权限问题

  • 确保服务器有权限访问指定路径中的文件和文件夹。

FastGPT-API文件库接口开发文档
https://blog.966677.xyz/2025/03/02/FastGPT-API文件库接口开发文档/
作者
Zhou1317fe5
发布于
2025年3月2日
许可协议