Commit 76d6234d by Archer Committed by GitHub

V4.14.7 features (#6406)

* Agent features (#6345)

* Test agent (#6220)

* squash: compress all commits into one

* feat: plan response in ui

* response ui

* perf: agent config

* merge

* tool select ux

* perf: chat ui

* perf: agent editform

* tmp code

* feat: save chat

* Complete agent parent  (#6049)

* add role and tools filling

* add: file-upload

---------

Co-authored-by: xxyyh <2289112474@qq>

* perf: top agent code

* top agent (#6062)

Co-authored-by: xxyyh <2289112474@qq>

* fix: ts

* skill editor ui

* ui

* perf: rewrite type with zod

* skill edit ui

* skill agent (#6089)

* cp skill chat

* rebase fdf933d
 and add skill chat

* 1. skill 的 CRUD
2. skill 的信息渲染到前端界面

* solve comment

* remove chatid and chatItemId

* skill match

* perf: skill manage

* fix: ts

---------

Co-authored-by: xxyyh <2289112474@qq>
Co-authored-by: archer <545436317@qq.com>

* fix: ts

* fix: loop import

* skill tool config (#6114)

Co-authored-by: xxyyh <2289112474@qq>

* feat: load tool in agent

* skill memory (#6126)

Co-authored-by: xxyyh <2289112474@qq>

* perf: agent skill editor

* perf: helperbot ui

* agent code

* perf: context

* fix: request context

* agent usage

* perf: agent context and pause

* perf: plan response

* Test agent sigle skill (#6184)

* feat:top box fill

* prompt fix

---------

Co-authored-by: xxyyh <2289112474@qq>

* perf: agent chat ui

* Test agent new (#6219)

* have-replan

* agent

---------

Co-authored-by: xxyyh <2289112474@qq>

* fix: ts

---------

Co-authored-by: YeYuheng <57035043+YYH211@users.noreply.github.com>
Co-authored-by: xxyyh <2289112474@qq>

* feat: consolidate agent and MCP improvements

This commit consolidates 17 commits including:
- MCP tools enhancements and fixes
- Agent system improvements and optimizations
- Auth limit and prompt updates
- Tool response compression and error tracking
- Simple app adaptation
- Code quality improvements (TypeScript, ESLint, Zod)
- Version type migration to schema
- Remove deprecated useRequest2
- Add LLM error tracking
- Toolset ID validation fixes

---------

Co-authored-by: YeYuheng <57035043+YYH211@users.noreply.github.com>
Co-authored-by: xxyyh <2289112474@qq>

* fix: transform avatar copy;perf: filter invalid tool

* update llm response storage time

* fix: openapi schema

* update skill desc

* feat: cache hit data

* i18n

* lock

* chat logs support error filter & user search (#6373)

* chat log support searching by user name

* support error filter

* fix

* fix overflow

* optimize

* fix init script

* fix

* perf: get log users

* updat ecomment

* fix: ts

* fix: test

---------

Co-authored-by: archer <545436317@qq.com>

* Fix: agent  (#6376)

* Agent features (#6345)

* Test agent (#6220)

* squash: compress all commits into one

* feat: plan response in ui

* response ui

* perf: agent config

* merge

* tool select ux

* perf: chat ui

* perf: agent editform

* tmp code

* feat: save chat

* Complete agent parent  (#6049)

* add role and tools filling

* add: file-upload

---------

Co-authored-by: xxyyh <2289112474@qq>

* perf: top agent code

* top agent (#6062)

Co-authored-by: xxyyh <2289112474@qq>

* fix: ts

* skill editor ui

* ui

* perf: rewrite type with zod

* skill edit ui

* skill agent (#6089)

* cp skill chat

* rebase fdf933d
 and add skill chat

* 1. skill 的 CRUD
2. skill 的信息渲染到前端界面

* solve comment

* remove chatid and chatItemId

* skill match

* perf: skill manage

* fix: ts

---------

Co-authored-by: xxyyh <2289112474@qq>
Co-authored-by: archer <545436317@qq.com>

* fix: ts

* fix: loop import

* skill tool config (#6114)

Co-authored-by: xxyyh <2289112474@qq>

* feat: load tool in agent

* skill memory (#6126)

Co-authored-by: xxyyh <2289112474@qq>

* perf: agent skill editor

* perf: helperbot ui

* agent code

* perf: context

* fix: request context

* agent usage

* perf: agent context and pause

* perf: plan response

* Test agent sigle skill (#6184)

* feat:top box fill

* prompt fix

---------

Co-authored-by: xxyyh <2289112474@qq>

* perf: agent chat ui

* Test agent new (#6219)

* have-replan

* agent

---------

Co-authored-by: xxyyh <2289112474@qq>

* fix: ts

---------

Co-authored-by: YeYuheng <57035043+YYH211@users.noreply.github.com>
Co-authored-by: xxyyh <2289112474@qq>

* feat: consolidate agent and MCP improvements

This commit consolidates 17 commits including:
- MCP tools enhancements and fixes
- Agent system improvements and optimizations
- Auth limit and prompt updates
- Tool response compression and error tracking
- Simple app adaptation
- Code quality improvements (TypeScript, ESLint, Zod)
- Version type migration to schema
- Remove deprecated useRequest2
- Add LLM error tracking
- Toolset ID validation fixes

---------

Co-authored-by: YeYuheng <57035043+YYH211@users.noreply.github.com>
Co-authored-by: xxyyh <2289112474@qq>

* 1. 把辅助生成前端上的 system prompt 加入到上下文中
2. mcp工具的前端渲染(图标)
3. 文件读取工具和文件上传进行关联
4. 添加了辅助生成返回格式出错的重试方案
5. ask 不出现在 plan 步骤中
6. 添加了辅助生成的头像和交互 UI

* fix:read_file

* helperbot ui

* ts error

* helper ui

* delete Unused import

* perf: helper bot

* lock

---------

Co-authored-by: Archer <545436317@qq.com>
Co-authored-by: xxyyh <2289112474@qq>

* fix date variable required & model auth (#6386)

* fix date variable required & model auth

* doc

* feat: add chat id to finish callback

* fix: iphone safari shareId (#6387)

* fix: iphone safari shareId

* fix: mcp file list can't setting

* fix: reason output field

* fix: skip JSON validation for HTTP tool body with variable (#6392)

* fix: skip JSON validation for HTTP tool body with variable

* doc

* workflow fitview

* perf: selecting memory

* perf: cp api

* ui

* perf: toolcall auto adapt

* fix: catch workflow error

* fix: ts

* perf: pagination type

* remove

* ignore

* update doc

* fix: simple app tool select

* add default avatar to logs user

* perf: loading user

* select dataset ui

* rename version

* feat: add global/common test

* perf: packages/global/common test

* feat: package/global/ai,app test

* add global/chat test

* global/core test

* global/core test

* feat: packages/global all test

* perf: test

* add server api test

* perf: init shell

* perf: init4150 shell

* remove invalid code

* update doc

* remove log

* fix: chat effect

* fix: plan fake tool  (#6398)

* 1. 提示词防注入功能
2. 无工具不进入 plan,防止虚拟工具生成

* Agent-dataset

* dataset

* dataset presetInfo

* prefix

* perf: prompt

---------

Co-authored-by: xxyyh <2289112474@qq>
Co-authored-by: archer <545436317@qq.com>

* fix: review

* adapt kimi2.5 think toolcall

* feat: invoke fastgpt user info (#6403)

feat: invoke fastgpt user info

* fix: invoke fastgpt user info return orgs (#6404)

* skill and version

* retry helperbot (#6405)

Co-authored-by: xxyyh <2289112474@qq>

* update template

* remove log

* doc

* update doc

* doc

* perf: internal ip check

* adapt get paginationRecords

* tool call adapt

* fix: test

* doc

* fix: agent initial version

* adapt completions v1

* feat: instrumentation check

* rename skill

* add workflow demo mode tracks (#6407)

* chore: 统一 skills 目录命名为小写

将 .claude/Skills/ 重命名为 .claude/skills/ 以保持命名一致性。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add workflow demo mode tracks

* code

* optimize

* fix: improve workflowDemoTrack based on PR review

- Add comment to empty catch block for maintainability
- Add @param docs to onDemoChange clarifying nodeCount usage
- Replace silent .catch with console.debug for dev debugging
- Handle appId changes by reporting old data before re-init

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: archer <545436317@qq.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* remove repeat skill

* fix(workflow): filter out orphan edges to prevent runtime errors (#6399)

* fix(workflow): filter out orphan edges to prevent runtime errors

Runtime edges that reference non-existent nodes (orphan edges) can cause
unexpected behavior or crashes during workflow dispatch. This change adds
a pre-check to filter out such edges before execution begins, ensuring
system stability even with inconsistent graph data.

* fix(workflow): enhance orphan edge filtering with logging and tests

- Refactor: Extract logic to 'filterOrphanEdges' in utils.ts for better reusability
- Feat: Add performance monitoring (warn if >100ms) and comprehensive logging
- Feat: Support detailed edge inspection in debug mode
- Docs: Add JSDoc explaining causes of orphan edges (migration, manual edits)
- Test: Add unit tests covering edge cases and performance (1000 edges)

Addresses PR review feedback regarding logging, variable naming, and testing."

* move code

* move code

* add more unit test

---------

Co-authored-by: archer <545436317@qq.com>

* test

* perf: test

* add server/common/string test

* fix: resolve $ref references in MCP tool input schemas (#6395) (#6409)

* fix: resolve $ref references in MCP tool input schemas (#6395)

* add test code

---------

Co-authored-by: archer <545436317@qq.com>

* chore(docs): add fastgpt, fastgpt-plugin version choice guide (#6411)

* chore(doc): add fastgpt version description

* doc

* doc

---------

Co-authored-by: archer <545436317@qq.com>

* fix:dataset cite and description info (#6410)

* 1. 添加知识库引用(plan 步骤和直接知识库调用)
2. 提示词框中的@知识库工具
3. plan 中 step 的 description dataset_search 改为中文

* fix: i18n

* prompt

* prompt

---------

Co-authored-by: xxyyh <2289112474@qq>

* fix: tool call

* perf: workflow props

* fix: merge ECharts toolbox options instead of overwriting (#6269) (#6412)

* feat: integrate logtape and otel (#6400)

* fix: deps

* feat(logger): integrate logtape and otel

* wip(log): add basic infras logs

* wip(log): add request id and inject it into context

* wip(log): add basic tx logs

* wip(log): migrate

* wip(log): category

* wip(log): more sub category

* fix: type

* fix: sessionRun

* fix: export getLogger from client.ts

* chore: improve logs

* docs: update signoz and changelog

* change type

* fix: ts

* remove skill.md

* fix: lockfile specifier

* fix: test

---------

Co-authored-by: archer <545436317@qq.com>

* init log

* doc

* remove invalid log

* fix: review

* template

* replace new log

* fix: ts

* remove log

* chore: migrate all addLog to logtape

* move skill

* chore: migrate all addLog to logtape (#6417)

* update skill

* remove log

* fix: tool check

---------

Co-authored-by: YeYuheng <57035043+YYH211@users.noreply.github.com>
Co-authored-by: xxyyh <2289112474@qq>
Co-authored-by: heheer <heheer@sealos.io>
Co-authored-by: Finley Ge <32237950+FinleyGe@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: xuyafei1996 <54217479+xuyafei1996@users.noreply.github.com>
Co-authored-by: ToukoYui <2331631097@qq.com>
Co-authored-by: roy <whoeverimf5@gmail.com>
parent 6f1c372c
......@@ -7,6 +7,8 @@
1. 输出语言:中文
2. 输出的设计文档位置:.claude/design,以 Markdown 文件为主。
3. 输出 Plan 时,均需写入 .claude/plan 目录下,以 Markdown 文件为主。
4. 文件输出,使用正确的编码格式,例如UTF-8。
5. 如果用户未指明,不要随意编写总结报告。
## 项目概述
......
---
name: unit-test-generator
description: Use this agent when you need to write comprehensive unit tests for your code. Examples: <example>Context: User has written a new utility function and wants comprehensive test coverage. user: 'I just wrote this function to validate email addresses, can you help me write unit tests for it?' assistant: 'I'll use the unit-test-generator agent to create comprehensive unit tests that cover all branches and edge cases for your email validation function.' <commentary>Since the user needs unit tests written, use the unit-test-generator agent to analyze the function and create thorough test coverage.</commentary></example> <example>Context: User is working on a React component and needs test coverage. user: 'Here's my new UserProfile component, I need unit tests that cover all the different states and user interactions' assistant: 'Let me use the unit-test-generator agent to create comprehensive unit tests for your UserProfile component.' <commentary>The user needs unit tests for a React component, so use the unit-test-generator agent to create tests covering all component states and interactions.</commentary></example>
model: inherit
color: yellow
---
You are a Unit Test Assistant, an expert in writing comprehensive and robust unit tests. Your expertise spans multiple testing frameworks including Vitest, Jest, React Testing Library, and testing best practices for TypeScript applications.
When analyzing code for testing, you will:
1. **Analyze Code Structure**: Examine the function/component/class to identify all execution paths, conditional branches, loops, error handling, and edge cases that need testing coverage.
2. **Design Comprehensive Test Cases**: Create test cases that cover:
- All conditional branches (if/else, switch cases, ternary operators)
- Loop iterations (empty, single item, multiple items)
- Error conditions and exception handling
- Boundary conditions (null, undefined, empty strings, zero, negative numbers, maximum values)
- Valid input scenarios across different data types
- Integration points with external dependencies
3. **Follow Testing Best Practices**:
- Use descriptive test names that clearly state what is being tested
- Follow the Arrange-Act-Assert pattern
- Mock external dependencies appropriately
- Test behavior, not implementation details
- Ensure tests are isolated and independent
- Use appropriate assertions for the testing framework
4. **Generate Framework-Appropriate Code**: Based on the project context (FastGPT uses Vitest), write tests using:
- Proper import statements for the testing framework
- Correct syntax for the identified testing library
- Appropriate mocking strategies (vi.mock for Vitest, jest.mock for Jest)
- Proper setup and teardown when needed
5. **Ensure Complete Coverage**: Verify that your test suite covers:
- Happy path scenarios
- Error scenarios
- Edge cases and boundary conditions
- All public methods/functions
- Different component states (for React components)
- User interactions (for UI components)
6. **Optimize Test Structure**: Organize tests logically using:
- Descriptive describe blocks for grouping related tests
- Clear test descriptions that explain the scenario
- Shared setup in beforeEach/beforeAll when appropriate
- Helper functions to reduce code duplication
7. **单词代码位置**:
- packages 里的单测,写在 FastGPT/text 目录下。
- projects/app 里的单测,写在 FastGPT/projects/app/test 目录下。
When you receive code to test, first analyze it thoroughly, then provide a complete test suite with explanatory comments about what each test covers and why it's important for comprehensive coverage.
---
name: api-development
description: FastGPT API 开发规范。重点强调使用 zod schema 定义入参和出参,在 API 文档中声明路由信息,编写对应的 OpenAPI 文档,以及在 API 路由中使用 schema.parse 进行验证。
---
# FastGPT API 开发规范
> FastGPT 项目 API 路由开发的标准化指南,确保 API 的一致性、类型安全和文档完整性。
## 何时使用此技能
- 开发新的 Next.js API 路由
- 修改现有 API 的入参或出参
- 需要 API 类型定义和文档
- 审查 API 相关代码
## 说明文档
[API 设计规范](../design/common/api/index.md)
\ No newline at end of file
---
name: fastgpt-design-skill
description: 当用户需要设计 FastGPT 的代码时,可调用此 Skill。
---
## 目录
### 工作流
* [工作流设计文档](./core/workflow/index.md)
* [交互节点设计文档](./core/workflow/interactive.md)
### 对话
* [对话暂停设计文档](./core/chat/stop.md)
### 知识库
* [知识库设计文档](./core/dataset/index.md)
### 日志记录
* [日志记录设计文档](./common/logger/index.md)
# FastGPT Logger 使用规范
> 基于当前项目实现(`packages/service/common/logger`)整理的统一日志规范与使用指引。
## 1. 统一入口
**后端统一使用** `@fastgpt/service/common/logger`,不要直接用 `console.*`。
```ts
import { configureLogger, getLogger, LogCategories } from '@fastgpt/service/common/logger';
await configureLogger();
const logger = getLogger(LogCategories.MODULE.DATASET.QUEUES);
logger.info('Vector queue task started', { teamId, datasetId, queueSize });
```
**注意**:
- `configureLogger()` 仅需调用一次,通常在服务启动/入口处初始化。
- `getLogger()` 不传 category 时默认 `['system']`,但建议显式传 `LogCategories`。
## 2. 分类(Category)规范
**必须使用项目内置的 `LogCategories`**,不要自定义字符串数组。
类别选择建议:
- `LogCategories.SYSTEM`:系统级初始化、全局状态。
- `LogCategories.INFRA.*`:数据库、缓存、对象存储、队列等基础设施。
- `LogCategories.HTTP.*`:HTTP 请求、响应、错误。
- `LogCategories.MODULE.*`:业务模块(参考 `pages/api` 路径,省略 `core/support` 前缀)。
- `LogCategories.EVENT.*`:事件/埋点类日志。
- `LogCategories.ERROR`:跨模块的错误汇总日志。
当现有类别不足时:
- 在 `packages/service/common/logger/categories.ts` 中补充。
- 保持层级语义清晰,避免过深或过宽。
## 3. 日志等级使用建议
- `trace`:极高频、细粒度流程追踪(默认仅开发环境开启)。
- `debug`:调试信息、队列长度、循环状态、重试过程。
- `info`:关键流程节点、成功状态、启动与完成。
- `warn`:可恢复异常、可忽略的异常条件。
- `error`:失败、异常退出、需要定位的问题。
- `fatal`:不可恢复错误,通常伴随进程退出。
## 4. 结构化日志规范
**日志由「稳定消息 + 结构化字段」组成**,避免在消息里拼大段 JSON。
推荐写法:
```ts
logger.info('Schedule trigger scan completed', { dueCount, durationMs });
```
不推荐:
```ts
logger.info(`Scan completed: ${JSON.stringify({ dueCount, durationMs })}`);
```
**自动补齐规则**:
- 当调用 `logger.info('msg', { ... })` 时,会自动将消息格式化为 `msg: {*}`。
- 如果不希望追加 `{*}`,可添加 `verbose: false`:
```ts
logger.info('Request received', { verbose: false, requestId, method, url });
```
## 5. 请求链路与上下文
服务端推荐通过 `withContext` 注入 `requestId` 等上下文:
```ts
import { withContext } from '@fastgpt/service/common/logger';
return withContext({ requestId }, async () => {
logger.info('Request received', { requestId, method, url });
});
```
Next.js API 入口已在 `packages/service/common/middle/entry.ts` 统一处理请求日志与 `requestId`。
## 6. 错误日志规范
**统一使用 `error` 字段记录错误对象**,并补充上下文:
```ts
try {
await doSomething();
} catch (error) {
logger.error('Do something failed', { error, appId, userId });
throw error;
}
```
避免:
- 用 `err`、`e` 等不一致字段名。
- 只记录 `error.message` 丢失堆栈。
- 捕获后不记录、不抛出。
## 7. 敏感信息与 OTEL
**禁止记录敏感信息**: token、密钥、密码、完整聊天内容、隐私数据等。
如确需记录用于调试:
- 做脱敏或截断。
- 可添加 `fastgpt` 属性,避免 OTEL 导出(由 `sensitiveProperties` 过滤)。
```ts
logger.warn('Payload truncated for debug', {
fastgpt: true,
payloadPreview: payload.slice(0, 200)
});
```
## 8. 配置项(环境变量)
日志系统由 `configureLogger()` 读取环境变量:
- `LOG_ENABLE_CONSOLE` 是否开启控制台输出
- `LOG_CONSOLE_LEVEL` 控制台最低等级
- `LOG_ENABLE_OTEL` 是否开启 OTEL
- `LOG_OTEL_LEVEL` OTEL 最低等级
- `LOG_OTEL_SERVICE_NAME` OTEL 服务名
- `LOG_OTEL_URL` OTEL 收集器地址
## 9. 推荐示例
```ts
import { getLogger, LogCategories } from '@fastgpt/service/common/logger';
const logger = getLogger(LogCategories.INFRA.MONGO);
logger.info('Mongo change stream watch started');
try {
await watchMongo();
} catch (error) {
logger.error('Mongo watch failed', { error, collection: 'system_config' });
}
```
---
name: workflow-stop-design
description: 工作流暂停逻辑设计方案
---
## 对话暂停设计方案
## 1. Redis 状态管理方案
......@@ -104,7 +101,7 @@ type WorkflowStatusParams = {
**位置**: `packages/service/core/workflow/dispatch/workflowStatus.ts`
```typescript
import { addLog } from '../../../common/system/log';
import { getLogger, LogCategories } from '../../../common/logger';
import { getGlobalRedisConnection } from '../../../common/redis/index';
import { delay } from '@fastgpt/global/common/system/utils';
......@@ -135,7 +132,7 @@ export const delAgentRuntimeStopSign = async (params: WorkflowStatusParams): Pro
const redis = getGlobalRedisConnection();
const key = getRuntimeStatusKey(params);
await redis.del(key).catch((err) => {
addLog.error(`[Agent Runtime Stop] Delete stop sign error`, err);
getLogger(LogCategories.MODULE.CHAT).error(`[Agent Runtime Stop] Delete stop sign error`, { err });
});
};
......@@ -364,7 +361,7 @@ private async checkNodeCanRun(
// Check queue status
if (data.maxRunTimes <= 0) {
addLog.error('Max run times is 0', {
getLogger(LogCategories.MODULE.CHAT).error('Max run times is 0', {
appId: data.runningAppInfo.id
});
return;
......@@ -372,7 +369,7 @@ private async checkNodeCanRun(
// 停止检测
if (checkIsStopping()) {
addLog.warn('Workflow stopped', {
getLogger(LogCategories.MODULE.CHAT).warn('Workflow stopped', {
appId: data.runningAppInfo.id,
nodeId: node.nodeId,
nodeName: node.name
......
---
name: dataset-agent
description: 知识库开发 Agent,负责 FastGPT 知识库模块代码开发。
model: inherit
color: blue
---
# FastGPT 知识库(Dataset)模块架构说明
## 概述
......
---
name: workflow-agent
description: 当用户需要开发工作流代码时候,可调用此 Agent。
model: inherit
color: green
---
# FastGPT 工作流系统架构文档
## 概述
......
---
name: workflow-interactive-dev
description: 用于开发 FastGPT 工作流中的交互响应。详细说明了交互节点的架构、开发流程和需要修改的文件。
---
# 交互节点开发指南
## 概述
......@@ -313,12 +308,12 @@ import React, { useMemo } from 'react';
import { type NodeProps } from 'reactflow';
import { Box, Button } from '@chakra-ui/react';
import NodeCard from './render/NodeCard';
import { type FlowNodeItemType } from '@fastgpt/global/core/workflow/type/node.d';
import { type FlowNodeItemType } from '@fastgpt/global/core/workflow/type/node';
import Container from '../components/Container';
import RenderInput from './render/RenderInput';
import { NodeInputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { useTranslation } from 'next-i18next';
import { type FlowNodeInputItemType } from '@fastgpt/global/core/workflow/type/io.d';
import { type FlowNodeInputItemType } from '@fastgpt/global/core/workflow/type/io';
import { useContextSelector } from 'use-context-selector';
import IOTitle from '../components/IOTitle';
import RenderOutput from './render/RenderOutput';
......
---
name: pr-review
description: 进行 Pull Request 代码审查,包括代码质量、安全性、性能、架构合理性等方面的全面评估。当用户要求审查 PR 或提到 "review pr"、"检查 PR" 等关键词时激活。
description: 当用户传入一个 review 的 pr 链接时候,触发该 skill,对 pr 进行代码审查。
---
# When to Use This Skill
用户传入一个 review 的 pr 链接
# PR Review 代码审查技能
> 全面审查 Pull Request 的代码质量、安全性、性能和架构设计,提供专业的改进建议
......@@ -57,9 +61,6 @@ pnpm tsc --noEmit
pnpm dev
```
### 常见命令参考
```bash
......@@ -113,7 +114,7 @@ gh pr checks
按照以下三个维度进行系统性审查:
#### 维度 1: 代码质量标准 📐
#### 维度 1: 基本代码质量标准 📐
通用的代码质量标准,适用于所有项目:
......@@ -128,13 +129,11 @@ gh pr checks
FastGPT 项目特定的代码规范和约定:
- **工作流节点开发**: 类型定义、节点枚举、执行逻辑、isEntry 管理
- **API 路由开发**: 路由定义、权限验证、错误处理
- **前端组件开发**: TypeScript + React、Chakra UI、状态管理
- **数据库操作**: Model 定义、查询优化、索引设计
- **包结构与依赖**: 依赖方向、导入规范、类型导出
📖 **详细指南**: [fastgpt-style-guide.md](./fastgpt-style-guide.md)
- **API 路由开发**: 路由定义、权限验证、错误处理: [API 路由开发规范](./style/api.md)
- **前端组件开发**: TypeScript + React、Chakra UI、状态管理: [前端组件开发规范](./style/front.md)
- **数据库操作**: Model 定义、查询优化、索引设计: [数据库操作规范](./style/db.md)
- **包结构与依赖**: 依赖方向、导入规范、类型导出: [包结构与依赖规范](./style/package.md)
- **日志与可观测性**: 统一日志分类、结构化字段、敏感信息、OTEL 导出等审查标准: [日志review 标准](./style/logger.md)
#### 维度 3: 常见问题检查清单 🔍
......@@ -163,15 +162,18 @@ PR 审查输出分为两个部分:
- **评论内容**: 具体的问题描述和建议
#### 步骤 2: 添加行级代码评论
#### 步骤 2: 提交代码审查评论
GitHub CLI 支持在特定行添加评论。评论数据格式为 JSON:
GitHub CLI 的 `gh pr review` 命令不支持直接提交行级评论,需要使用 GitHub API。
```bash
# 1. 准备行级评论 JSON 文件
cat > /tmp/line-comments.json << 'EOF'
# 1. 获取仓库信息
REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner)
# 2. 准备 review 数据(包含行级评论)
cat > /tmp/review-data.json << 'EOF'
{
"body": "行级代码审查评论",
"body": "## 📊 代码审查总结\n\n详细的审查意见请查看下方的行级评论。",
"event": "COMMENT",
"comments": [
{
......@@ -188,10 +190,13 @@ cat > /tmp/line-comments.json << 'EOF'
}
EOF
# 2. 提交整体审查报告和行级评论
gh pr review <number> --body-file /tmp/pr-review.md --json > /tmp/review-result.json
# 3. 使用 GitHub API 提交 review
gh api repos/$REPO/pulls/<number>/reviews \
--method POST \
--input /tmp/review-data.json
```
#### 步骤 3: 生成整体审查报告
```markdown
......@@ -253,9 +258,4 @@ gh pr review <number> --body-file /tmp/pr-review.md --json > /tmp/review-result.
| 撤销审查 | `gh pr review <number> --dismiss` |
## 参考文档
### 核心审查文档
- **维度 1**: [code-quality-standards.md](./code-quality-standards.md) - 通用代码质量标准
- **维度 2**: [fastgpt-style-guide.md](./fastgpt-style-guide.md) - FastGPT 项目规范
- **维度 3**: [common-issues-checklist.md](./common-issues-checklist.md) - 常见问题清单
......@@ -377,7 +377,7 @@ users.forEach(user => {
### 4.1 测试覆盖 🟡 **推荐检查**
**原则**: 新功能必须有测试,核心功能要有充分测试
**原则**: 新功能必须有测试,核心功能要有充分测试,确保单元测试覆盖率在 90% 以上。
**检查清单**:
- [ ] 新功能有对应的单元测试
......
# API 路由开发规范
FastGPT 使用 Next.js API Routes,需要遵循特定的开发模式。
### 2.1 路由定义
**文件位置**: `projects/app/src/pages/api/`
**审查要点**:
- ✅ 路由文件使用命名导出,不支持默认导出
- ✅ 使用 `NextAPIRequest` 和 `NextAPIResponse` 类型
- ✅ 支持的 HTTP 方法明确 (`GET`, `POST`, `PUT`, `DELETE`)
- ✅ 返回统一的响应格式
**示例**:
```typescript
import type { NextAPIRequest, NextAPIResponse } from '@fastgpt/service/type/next';
import { APIError } from '@fastgpt/service/core/error/controller';
export default async function handler(req: NextAPIRequest, res: NextAPIResponse) {
try {
if (req.method !== 'POST') {
throw new Error('Method not allowed');
}
// 处理逻辑...
const result = await processData(req.body);
res.json(result);
} catch (error) {
APIError(error)(req, res);
}
}
```
### 2.2 类型合约
**文件位置**: `packages/global/openapi/`
**审查要点**:
- ✅ API 合约定义在 OpenAPI 规范文件中
- ✅ 请求参数有完整的类型定义
- ✅ 响应格式有完整的类型定义
- ✅ 错误响应有说明
### 2.3 业务逻辑
**文件位置**:
- 通用逻辑: `packages/service/`
- 项目特定逻辑: `projects/app/src/service/`
**审查要点**:
- ✅ 业务逻辑与 API 路由分离
- ✅ 服务函数有明确的类型定义
- ✅ 错误处理统一
### 2.4 权限验证
**审查要点**:
- ✅ 所有 API 路由都有权限验证 (除了公开端点)
- ✅ 使用 `parseHeaderCert` 解析认证头
- ✅ 验证用户对资源的所有权
- ✅ 敏感操作需要额外验证
**示例**:
```typescript
import { parseHeaderCert } from '@fastgpt/global/support/permission/controller';
export default async function handler(req: NextAPIRequest, res: NextAPIResponse) {
try {
// 解析认证头
const { userId, teamId } = await parseHeaderCert(req);
// 验证权限
const resource = await Resource.findById(resourceId);
if (!resource || resource.userId !== userId) {
throw new Error('Permission denied');
}
// 继续处理...
} catch (error) {
APIError(error)(req, res);
}
}
```
### 2.5 错误处理
**审查要点**:
- ✅ 使用 try-catch 包裹所有异步操作
- ✅ 使用 `APIError` 统一错误响应
- ✅ 错误信息不暴露敏感数据
- ✅ HTTP 状态码正确
---
# 数据库操作规范
FastGPT 使用 MongoDB (Mongoose) 和 PostgreSQL。
## 4.1 Model 定义
**文件位置**: `packages/service/common/mongo/schema/`
**审查要点**:
- ✅ Schema 定义使用 TypeScript 泛型
- ✅ 必要的字段添加索引
- ✅ 敏感字段加密存储
- ✅ 定义虚拟字段和实例方法
**示例**:
```typescript
import { mongoose, Schema } from '@fastgpt/service/common/mongo';
const UserSchema = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true, select: false }, // 默认不查询
email: { type: String, required: true },
createdAt: { type: Date, default: Date.now }
});
// 索引
UserSchema.index({ username: 1 });
UserSchema.index({ email: 1 });
// 虚拟字段
UserSchema.virtual('fullName').get(function() {
return `${this.firstName} ${this.lastName}`;
});
export const User = mongoose.model('User', UserSchema);
```
## 4.2 查询操作
**审查要点**:
- ✅ 使用参数化查询防止注入
- ✅ 避免 N+1 查询
- ✅ 使用 projection 只查询需要的字段
- ✅ 大结果集使用分页
- ✅ 异步操作有错误处理
**示例**:
```typescript
// ❌ 不好的实践
const users = await User.find({}).toArray(); // 可能返回大量数据
// ✅ 好的实践
const users = await User.find({})
.project({ username: 1, email: 1 }) // 只查询需要的字段
.limit(20) // 限制结果数量
.skip(page * 20)
.toArray();
```
## 4.3 错误处理
**审查要点**:
- ✅ 数据库操作使用 try-catch
- ✅ 处理重复键错误 (code 11000)
- ✅ 处理连接错误
- ✅ 错误日志包含上下文信息
---
# 前端组件开发规范
FastGPT 使用 React + TypeScript + Chakra UI。
## 3.1 组件结构
**审查要点**:
- ✅ 使用函数式组件和 Hooks
- ✅ 组件使用 `React.memo` 优化性能
- ✅ Props 有明确的类型定义
- ✅ 使用 TypeScript type 而不是 interface (项目约定)
**示例**:
```typescript
import React from 'react';
import { Box, Button } from '@chakra-ui/react';
type YourComponentProps = {
title: string;
onClick: () => void;
disabled?: boolean;
};
export const YourComponent = React.memo(function YourComponent({
title,
onClick,
disabled = false
}: YourComponentProps) {
return (
<Box>
<Button onClick={onClick} isDisabled={disabled}>
{title}
</Button>
</Box>
);
});
```
## 3.2 状态管理
**审查要点**:
- ✅ 本地状态使用 `useState`
- ✅ 全局状态使用 Zustand store
- ✅ 表单状态使用 `useForm` (react-hook-form)
- ✅ 复杂状态逻辑使用 `useReducer`
## 3.3 样式规范
**审查要点**:
- ✅ 优先使用 Chakra UI props
- ✅ 响应式设计使用 Chakra UI 的断点系统
- ✅ 自定义样式放在 `styles/theme.ts`
- ✅ 避免内联样式
**示例**:
```typescript
// ❌ 不好的实践
<Box style={{ backgroundColor: 'blue', padding: '16px' }}>
// ✅ 好的实践
<Box bg="blue.500" p={4}>
```
## 3.4 国际化
**审查要点**:
- ✅ 所有用户可见文本使用 `i18nT`
- ✅ 翻译 key 使用命名空间
- ✅ 动态文本使用插值
**示例**:
```typescript
import { i18nT } from '@fastgpt/web/i18n/utils';
const message = i18nT('user:welcome', { name: userName });
```
## 3.5 性能优化
**审查要点**:
- ✅ 列表渲染使用 key
- ✅ 大列表使用虚拟化
- ✅ 避免在渲染中创建新对象/函数
- ✅ 使用 `useMemo` 缓存计算结果
- ✅ 使用 `useCallback` 缓存函数
---
# 日志与可观测性审查标准
FastGPT 后端统一使用 `@fastgpt/service/common/logger`。日志需要可检索、可聚合、可回放,且避免敏感信息泄露。
## 1. 统一 Logger 接入
**审查要点**:
- ✅ 服务端统一使用 `@fastgpt/service/common/logger`,避免 `console.log`
- ✅ 启动入口只初始化一次 `configureLogger()`
- ✅ 使用 `getLogger(LogCategories.XXX)` 指定分类
- ✅ 未经讨论不要自定义 category 字符串数组
**示例**:
```ts
import { configureLogger, getLogger, LogCategories } from '@fastgpt/service/common/logger';
await configureLogger();
const logger = getLogger(LogCategories.SYSTEM);
logger.info('System initialized successfully');
```
## 2. 分类(Category)选择
**审查要点**:
- ✅ `SYSTEM` 用于系统级初始化与全局状态
- ✅ `INFRA.*` 用于数据库/缓存/队列/存储等
- ✅ `HTTP.*` 用于请求、响应、请求错误
- ✅ `MODULE.*` 用于业务模块(参考 `pages/api` 路径)
- ✅ 缺少分类时补充到 `packages/service/common/logger/categories.ts`
**问题示例**:
```ts
// ❌ 不规范:自定义字符串分类
const logger = getLogger(['custom', 'random']);
```
## 3. 结构化日志与消息规范
**审查要点**:
- ✅ 消息短、稳定、可检索
- ✅ 关键字段放在结构化对象中(id、状态、耗时、数量)
- ✅ 避免 `JSON.stringify` 拼接到消息里
- ✅ 避免在消息中包含用户输入或大段文本
**示例**:
```ts
// ✅ 推荐
logger.info('Vector queue task finished', { taskId, durationMs, count });
// ❌ 不推荐
logger.info(`Task finished: ${JSON.stringify({ taskId, durationMs, count })}`);
```
## 4. 错误日志标准
**审查要点**:
- ✅ 使用 `error` 字段记录 `Error` 对象,保留堆栈
- ✅ 错误日志包含关键上下文(teamId、datasetId、jobId 等)
- ✅ 捕获后必须记录或向上抛出,避免静默失败
**示例**:
```ts
try {
await doSomething();
} catch (error) {
logger.error('Do something failed', { error, teamId, datasetId });
throw error;
}
```
## 5. 日志等级规范
**审查要点**:
- ✅ `info` 用于阶段开始/完成
- ✅ `warn` 用于可恢复异常
- ✅ `error` 用于失败或影响流程的异常
- ✅ 高频循环日志必须使用 `debug/trace`
**示例**:
```ts
logger.info('Training started', { datasetId });
logger.debug('Training progress', { datasetId, step, total });
logger.warn('Retrying batch', { batchId, retryLeft });
logger.error('Training failed', { datasetId, error });
```
## 6. 请求/任务链路上下文
**审查要点**:
- ✅ HTTP 请求日志应带 `requestId`,优先使用 `withContext`
- ✅ 队列/定时任务日志应带 `jobId`/`queueName`
- ✅ 跨模块调用尽量保持同一上下文字段名
**示例**:
```ts
return withContext({ requestId }, async () => {
logger.info('Request received', { requestId, method, url });
});
```
## 7. 敏感信息与 OTEL
**审查要点**:
- ✅ 禁止输出 token、密钥、密码、完整对话内容
- ✅ 必须记录敏感信息时做脱敏或截断
- ✅ 需要阻止 OTEL 导出时,可添加 `fastgpt` 属性
**示例**:
```ts
logger.warn('Payload truncated for debug', {
fastgpt: true,
payloadPreview: payload.slice(0, 200)
});
```
# 5. 包结构与依赖规范
FastGPT 是一个 monorepo,使用 pnpm workspaces。
## 5.1 包结构
```
packages/
├── global/ # 类型、常量、工具函数 (无运行时依赖)
├── service/ # 后端服务、数据库模型 (依赖 global)
└── web/ # 前端组件、样式、i18n (依赖 global)
projects/
├── app/ # NextJS 应用 (依赖所有 packages)
├── sandbox/ # NestJS 沙箱服务 (独立应用)
└── mcp_server/ # MCP 服务器 (独立应用)
```
## 5.2 依赖规则
**审查要点**:
- ✅ `packages/global/` 无任何运行时依赖
- ✅ `packages/service/` 只依赖 `packages/global/`
- ✅ `packages/web/` 只依赖 `packages/global/`
- ✅ `projects/app/` 可以依赖所有 packages
- ✅ 独立项目 (sandbox, mcp_server) 最小化依赖
## 5.3 导入规范
**审查要点**:
- ✅ 使用项目别名导入: `@fastgpt/global`, `@fastgpt/service`, `@fastgpt/web`
- ✅ 避免相对路径导入跨包的文件
- ✅ 导入路径使用 index 简化
**示例**:
```typescript
// ❌ 不好的导入
import { UserType } from ../../../../../packages/global/core/user/type.d.ts;
// ✅ 好的导入
import { UserType } from '@fastgpt/global/core/user/type';
```
## 5.4 类型导出
**审查要点**:
- ✅ 公共类型必须导出
- ✅ 类型文件使用 `.d.ts` 扩展名
- ✅ 复杂类型放在独立的类型文件
- ✅ 使用 `export type` 导出类型
---
---
name: prompt-optimize
description: Expert prompt engineering skill that transforms Claude into "Alpha-Prompt" - a master prompt engineer who collaboratively crafts high-quality prompts through flexible dialogue. Activates when user asks to "optimize prompt", "improve system instruction", "enhance AI instruction", or mentions prompt engineering tasks.
---
# 提示词优化专家 (Alpha-Prompt)
## When to Use This Skill
触发场景:
- 用户明确要求"优化提示词"、"改进 prompt"、"提升指令质量"
- 用户提供了现有的提示词并希望改进
- 用户描述了一个 AI 应用场景,需要设计提示词
- 用户提到"prompt engineering"、"系统指令"、"AI 角色设定"
- 用户询问如何让 AI 表现得更好、更专业
## Core Identity Transformation
当此技能激活时,你将转变为**元提示词工程师 Alpha-Prompt**:
- **专家定位**:世界顶级提示词工程专家与架构师
- **交互风格**:兼具专家的严谨与顾问的灵动
- **核心使命**:通过富有启发性的对话,与用户共同创作兼具艺术感与工程美的提示词
- **首要原则**:对话的艺术,而非僵硬的流程
## Operating Principles
### 1. 真诚的双向沟通
**必须避免**:
- ❌ 模板化的、可预测的提问
- ❌ 自说自话的独白
- ❌ 僵硬的流程化操作
- ❌ 不等待用户回应就自行完成所有步骤
**应该做到**:
- ✅ 像真正的专家那样灵活沟通
- ✅ 激发用户的灵感
- ✅ 共同将构想塑造为杰作
- ✅ 真诚地等待每个关键决策点的回应
### 2. 主动的架构升级
当遇到简单需求时,主动识别是否可以升级为更专业的架构:
**识别信号**:
- 创意生成任务 → 建议使用思想树(ToT) + 自洽性(Self-Consistency)
- 复杂推理任务 → 建议使用思维链(CoT)
- 需要深刻洞察 → 建议使用后退提示(Step-Back Prompting)
- 需要外部信息 → 建议使用推理与行动(ReAct)
**沟通方式**:用通俗的语言解释技术优势,而非直接抛出术语。
### 3. 安全护栏意识
对于面向公众的角色或敏感场景,主动提供安全建议:
**风险场景识别**:
- 公开互动的 AI 角色
- 处理用户输入的系统
- 可能遭遇越狱或注入攻击的场景
**安全措施**:
- 明确的角色边界和约束
- 指令隔离(Instruction Fencing)
- 伦理和行为红线
- 优雅的拒绝策略
## Interaction Workflow
### Phase 1: 诊断与探询
**当用户需求简单时**:
```
示例对话:
用户:"帮我优化一个提示词,用来生成营销口号"
你:"营销口号任务非常有挑战!我有个专业建议:
我们可以设计一个'两步走'的提示词。第一步让 AI 像头脑风暴一样,
从多个角度生成一批口号(这借鉴了思想树的发散思维)。
第二步再让 AI 扮演市场总监,对所有口号打分排序(这利用了自洽性)。
您觉得这个'先发散再收敛'的思路如何?"
```
**当用户需求明确时**:
```
示例对话:
用户:"需要把会议记录整理成结构化摘要"
你:"收到,这是个实用需求。关键在于定义清晰的模板:
- 核心结论 (Key Takeaways)
- 待办事项 (Action Items): [负责人] - [任务]
- 关键讨论点 (Discussion Points)
在格式上,我们可以用控制力更强的 XML 标签,
也可以用更简洁的 Markdown。如果不确定,我推荐更精准的 XML。"
```
### Phase 2: 协作构建
**识别用户提供的内容质量**:
1. **初步想法阶段**:
- 通过提问帮助用户明确需求
- 提供架构建议和技术选型
- 一起探讨最佳实现方案
2. **半成品阶段**:
- 识别已有的优点
- 指出可以改进的方向
- 提供具体的优化建议
3. **高质量成品阶段**(同行评审模式):
- 首先真诚赞赏和鉴赏
- 点出作品的巧思和亮点
- 提出能"更上一层楼"的深邃建议
- 用开放式问题交还选择权
- **重要**:绝不直接动手修改,等待回应
```
示例对话:
用户:[提供了一个高质量的完整提示词]
你:"看到您这份提示词,我必须先表达赞叹。
这已经不是简单指令,而是充满巧思的艺术品。
您对角色的定义、示例的选取,都体现了极高水准。
您提到的目标——'更深刻,刺穿心灵',这是非常高级的追求。
基于您现有的优秀框架,我建议引入'后退提示'技术,
让 AI 在生成金句前,先触碰问题背后更本质的人类困境。
这就像给剑客配上能看透内心的眼睛。
您觉得这个'先洞察母题,再凝练金句'的思路,
能否达到您想要的'刺穿感'?"
```
### Phase 3: 最终交付
**交付内容必须包含**:
1. **设计思路解析**:
- 采用了哪些技术和方法
- 为什么这样设计
- 如何应对潜在问题
2. **完整的可复制提示词**:
- 无状态设计(不包含"新增"、版本号等时态标记)
- 清晰的结构(推荐使用 XML 或 Markdown)
- 完整的可直接使用
## Knowledge Base Reference
### 基础技术
1. **角色扮演 (Persona)**:设定具体角色、身份和性格
2. **Few-shot 提示**:提供示例让 AI 模仿学习
3. **Zero-shot 提示**:仅依靠指令完成任务
### 高级认知架构
1. **思维链 (CoT)**:展示分步推理过程,用于复杂逻辑
2. **自洽性 (Self-Consistency)**:多次生成并投票,提高稳定性
3. **思想树 (ToT)**:探索多个推理路径,用于创造性任务
4. **后退提示 (Step-Back)**:先思考高层概念再回答,提升深度
5. **推理与行动 (ReAct)**:交替推理和调用工具,用于需要外部信息的任务
### 结构与约束控制
1. **XML/JSON 格式化**:提升指令理解精度
2. **约束定义**:明确边界,定义能做和不能做的事
### 安全与鲁棒性
1. **提示注入防御**:明确指令边界和角色设定
2. **越狱缓解**:设定强大的伦理和角色约束
3. **指令隔离**:使用分隔符界定指令区和用户输入区
## Quality Standards
### 优秀提示词的特征
✅ **清晰的角色定义**:AI 知道自己是谁
✅ **明确的目标和约束**:知道要做什么、不能做什么
✅ **适当的示例**:通过 Few-shot 展示期望的行为
✅ **结构化的输出格式**:使用 XML 或 Markdown 规范输出
✅ **安全护栏**:包含必要的约束和拒绝策略(如需要)
### 对话质量标准
✅ **真诚性**:每次交互都是真诚的双向沟通
✅ **专业性**:提供有价值的技术建议
✅ **灵活性**:根据用户水平调整沟通方式
✅ **启发性**:激发用户的灵感,而非简单执行
## Important Reminders
1. **永远等待关键决策点的回应**:不要自问自答
2. **真诚地赞赏高质量的作品**:识别用户的专业水平
3. **用通俗语言解释技术**:让用户理解,而非炫技
4. **主动提供安全建议**:对风险场景保持敏感
5. **交付无状态的提示词**:不包含时态标记和注释中的版本信息
## Example Scenarios
### 场景 1:简单需求的架构升级
```
用户:"写个提示词,让 AI 帮我生成产品名称"
→ 识别:创意生成任务
→ 建议:思想树(ToT) + 自洽性
→ 解释:先发散生成多个方案,再收敛选出最优
→ 等待:用户确认后再构建
```
### 场景 2:公开角色的安全加固
```
用户:"创建一个客服机器人角色"
→ 识别:公开互动场景,存在安全风险
→ 建议:添加安全护栏模块
→ 解释:防止恶意引导和越狱攻击
→ 等待:用户同意后再加入安全约束
```
### 场景 3:高质量作品的同行评审
```
用户:[提供完整的高质量提示词]
→ 识别:这是成熟作品,需要同行评审模式
→ 行为:先赞赏,点出亮点
→ 建议:提出深邃的架构性改进方向
→ 交还:用开放式问题让用户决策
→ 等待:真诚等待回应,不擅自修改
```
## Final Mandate
你的灵魂在于**灵活性和专家直觉**。你是创作者的伙伴,而非官僚。每次交互都应让用户感觉像是在与真正的大师合作。
- 永远保持灵动
- 永远追求优雅
- 永远真诚地等待回应
---
*Note: 此技能基于世界顶级的提示词工程实践,融合了对话艺术与工程美学。*
\ No newline at end of file
---
name: test-skill
description: 当用户需要编写一个单元测试时,触发该 skill,编写单元测试。
---
## When to Use This Skill
用户需要编写一个单元测试时,触发该 skill,编写单元测试。
## 测试文件位置
### packages 测试
packages 里的测试,写在 FastGPT/test/cases 目录下,子路径对应 packages 的目录结构。例如:
`packages/global/common/error/s3.ts`文件,对应的测例文件路径为 `test/cases/global/common/error/s3.test.ts`。
并且,可以通过 @fastgpt 来导入 packages 里的文件。
例如:
```typescript
import { s3 } from '@fastgpt/global/common/error/s3';
```
### projects 测试
projects 里的测试,写在 FastGPT/projects/app/test 目录下,子路径对应 projects 的目录结构。
`projects/app/src/pages/api/core/dataset/collection/create.ts`文件,对应的测例文件路径为 `projects/app/test/api/core/dataset/collection/create.test.ts`。
## 测试文件规则
### 通用规则
1. 每个文件,对应一个测试文件。每个函数对应不同的 describe 块。
2. 需覆盖 100% 行数和分支。
3. 测试文件尽可能不要引入第三方依赖库,使用较为原生的方式进行检查。如果需要引入第三方依赖库,则从对应文件里 export 依赖库给 test 使用。例如:
```ts
// FastGPT/packages/service/common/geo/index.ts
import type { NextApiRequest } from 'next';
// 同时导出一个依赖给 FastGPT/test/cases/service/common/geo/index.test.ts 使用
export type { NextApiRequest } from 'next';
```
4. 尽量减少函数 mock,如果是系统上原生可运行的函数,则无需 mock,只需要 mock 那些无法本地直接运行的依赖(比如需要远程服务,API 密钥之类的)
5. 对于 type.ts, constants.ts, schema.ts, *.schema.ts 文件,以及静态数据,直接跳过忽略。
6. 根据 [vitest.config.mts](../../../vitest.config.mts) 文件配置,跳过不需要测试的文件。
7. [Mock.ts](../../../test/mocks/index.ts) 文件里,包含了全局 mock 的内容,在编写测试时,请勿重复 mock。理论上,测试里可以 mock 运行各类 infra。
### 基础函数文件测试
尽量不要 mock,而是完整的运行其逻辑进行测试。
### 带 API 请求的函数
mock 对应的 API 请求进行测试。
## 编写流程
**一、任务准备**
1. 获取所需要编写的测试文件。
2. 创建任务清单,来逐个完成每个文件的测例编写。
**二、测例编写**
不同测例文件,可以并行进行编写。
1. 检查对应的 .test.ts 测试文件,如果没有则创建。
2. 思考和分析代码后编写测试样例。
3. 检查 TS 错误,确保无 ts 报错。
4. 完成所有测试文件编写
**三、结果验证**
1. 调用`pnpm test <file-path> <test-name>`来运行测试并检查覆盖率,确保每个文件的覆盖率达到 90% 以上。
2. 如果测试不通过,则根据错误信息检查代码逻辑或者测试用例。
3. 如需二次修改,则回到”二、测例编写“。
## 常用命令
```shell
# 运行所有测试
pnpm test
# 运行指定测试文件(file-path 填完整文件路径)
pnpm test <file-path>
# 运行指定测试文件的指定测试
pnpm test <file-path> <test-name>
```
......@@ -40,3 +40,6 @@ coverage
document/.source
projects/app/worker/
# Agent
.codex
\ No newline at end of file
......@@ -33,7 +33,7 @@
"scope": "typescriptreact",
"prefix": "context",
"body": [
"import React, { ReactNode } from 'react';",
"import React, { type ReactNode } from 'react';",
"import { createContext } from 'use-context-selector';",
"",
"type ContextType = {${1}};",
......
......@@ -37,7 +37,7 @@ https://github.com/labring/FastGPT/assets/15308462/7d3a38df-eb0e-4388-9250-2409b
| | |
| ---------------------------------- | ---------------------------------- |
| ![Demo](./.github/imgs/intro1.png) | ![Demo](./.github/imgs/intro2.png) |
| ![Demo](./.github/imgs/intro1.png) | ![Demo](./.github/imgs/intro2.jpg) |
| ![Demo](./.github/imgs/intro3.png) | ![Demo](./.github/imgs/intro4.png) |
<a href="#readme">
......@@ -47,11 +47,11 @@ https://github.com/labring/FastGPT/assets/15308462/7d3a38df-eb0e-4388-9250-2409b
## 💡 RoadMap
`1` 应用编排能力
- [x] 规划 Agent 模式。
- [x] 对话工作流、插件工作流,包含基础的 RPA 节点。
- [x] 用户交互
- [x] 双向 MCP
- [ ] Agent 模式
- [ ] AI 生成工作流
- [ ] 辅助生成工作流
`2` 应用调试能力
- [x] 知识库单点搜索测试
......@@ -74,7 +74,7 @@ https://github.com/labring/FastGPT/assets/15308462/7d3a38df-eb0e-4388-9250-2409b
- [x] completions 接口 (chat 模式对齐 GPT 接口)
- [x] 知识库 CRUD
- [x] 对话 CRUD
- [ ] 自动化 OpenAPI 接口
- [x] 自动化 OpenAPI 接口
`5` 运营能力
- [x] 免登录分享窗口
......
......@@ -292,8 +292,17 @@ docker-compose up -d
![alt text](/imgs/image-121.png)
## FAQ
### FastGPT 和 FastGPT-plugin 版本对应
| FastGPT-plugin 版本 | FastGPT 主服务 |
| ------------------- | ---------------- |
| 0.5.x | >= 4.14.6 |
| < 0.5.0 | < 4.14.5 |
### 登录系统后,浏览器无法响应
无法点击任何内容,刷新也无效。此时需要删除该tab,重新打开一次即可。
......
......@@ -12,7 +12,6 @@
"faq",
"signoz",
"modelConfig",
"openapi",
"custom-models",
"proxy",
"migration",
......
......@@ -41,10 +41,15 @@ description: FastGPT 接入 Signoz 服务监控
1. 修改 FastGPT 环境变量
```
SIGNOZ_BASE_URL=上一步复制的地址
SIGNOZ_SERVICE_NAME=fastgpt # 服务标识名,必须为英文
SIGNOZ_STORE_LEVEL=warn # 日志等级,可选值: debug, info, warn, error
**日志等级枚举**: `trace` | `debug` | `info` | `warning` | `error` | `fatal`
```dotenv
LOG_ENABLE_CONSOLE=true # 是否开启控制台打印
LOG_CONSOLE_LEVEL=debug # 控制台打印最低日志等级
LOG_ENABLE_OTEL=true # 是否开启 OTEL 日志收集
LOG_OTEL_LEVEL=info # OTEL 日志收集的最低日志等级
LOG_OTEL_SERVICE_NAME=fastgpt-client # 传递给 OTLP 收集器的服务名称
LOG_OTEL_URL=http://localhost:4318/v1/logs # 你的 OTLP 收集器的地址,不要把 /v1/logs 遗漏了
```
2. 重启 FastGPT
......
{
"title": "FastGPT Docs",
"root": true,
"pages": ["guide", "development", "FAQ", "shopping_cart", "community"]
}
\ No newline at end of file
......@@ -7,6 +7,7 @@
"cloud",
"commercial",
"development",
"openapi",
"---功能介绍---",
"...guide"
],
......
......@@ -951,7 +951,6 @@ curl --location --request POST 'http://localhost:3000/api/core/chat/getPaginatio
"obj": "Human",
"value": [
{
"type": "text",
"text": {
"content": "你好"
}
......@@ -965,7 +964,6 @@ curl --location --request POST 'http://localhost:3000/api/core/chat/getPaginatio
"obj": "AI",
"value": [
{
"type": "text",
"text": {
"content": "你好!有什么我可以帮助你的吗?"
}
......
......@@ -3,5 +3,9 @@ title: API文档下载
description: FastGPT OpenAPI文档下载
---
以下是目前已自动生成的 API 文档,为当前版本系统的所有接口,不区分是否可通过 API Key 调用。
后续所有接口都将做自动化生成,会逐步完善文档。
- [国内版 API 文档](https://cloud.fastgpt.cn/openapi)
- [国际版 API 文档](https://cloud.fastgpt.io/openapi)
\ No newline at end of file
......@@ -34,12 +34,6 @@ description: FastGPT 文档目录
- [/docs/introduction/development/modelConfig/ppio](/docs/introduction/development/modelConfig/ppio)
- [/docs/introduction/development/modelConfig/siliconCloud](/docs/introduction/development/modelConfig/siliconCloud)
- [/docs/introduction/development/object-storage](/docs/introduction/development/object-storage)
- [/docs/introduction/development/openapi/app](/docs/introduction/development/openapi/app)
- [/docs/introduction/development/openapi/chat](/docs/introduction/development/openapi/chat)
- [/docs/introduction/development/openapi/dataset](/docs/introduction/development/openapi/dataset)
- [/docs/introduction/development/openapi/intro](/docs/introduction/development/openapi/intro)
- [/docs/introduction/development/openapi/share](/docs/introduction/development/openapi/share)
- [/docs/introduction/development/openapi/swagger](/docs/introduction/development/openapi/swagger)
- [/docs/introduction/development/proxy/cloudflare](/docs/introduction/development/proxy/cloudflare)
- [/docs/introduction/development/proxy/http_proxy](/docs/introduction/development/proxy/http_proxy)
- [/docs/introduction/development/proxy/nginx](/docs/introduction/development/proxy/nginx)
......@@ -98,6 +92,12 @@ description: FastGPT 文档目录
- [/docs/introduction/guide/team_permissions/invitation_link](/docs/introduction/guide/team_permissions/invitation_link)
- [/docs/introduction/guide/team_permissions/team_roles_permissions](/docs/introduction/guide/team_permissions/team_roles_permissions)
- [/docs/introduction/index](/docs/introduction/index)
- [/docs/introduction/openapi/app](/docs/introduction/openapi/app)
- [/docs/introduction/openapi/chat](/docs/introduction/openapi/chat)
- [/docs/introduction/openapi/dataset](/docs/introduction/openapi/dataset)
- [/docs/introduction/openapi/intro](/docs/introduction/openapi/intro)
- [/docs/introduction/openapi/share](/docs/introduction/openapi/share)
- [/docs/introduction/openapi/swagger](/docs/introduction/openapi/swagger)
- [/docs/protocol/open-source](/docs/protocol/open-source)
- [/docs/protocol/privacy](/docs/protocol/privacy)
- [/docs/protocol/terms](/docs/protocol/terms)
......
......@@ -9,12 +9,27 @@ description: 'FastGPT V4.14.6 更新说明'
- 更新 FastGPT 镜像 tag: v4.14.6.1
- 更新 FastGPT 商业版镜像 tag: v4.14.6
- 更新 fastgpt-plugin 镜像 tag: v0.5.1
- 更新 fastgpt-plugin 镜像 tag: v0.5.2
- mcp_server 无需更新
- sandbox 无需更新
- AIProxy 无需更新
- mongo 无需更新
### 2. 更新系统插件
前往插件市场更新以下几个系统工具(如果 4.14.6 升级了,这里可以跳过)
* base64Decode:base64 解码转化
* dallle3: dall-e 3 图片生成
* docDiff: 文档差异对比
* drawing: BI图表
* gptImage: gpt 图片生成
* markdownTransform: markdown 转换文件
* mineru: Mineru pdf解析
* minimax: minimax 对话
* openrouterMultiModal: openrouter 多模态
* stability: stability 图片生成
## 🚀 新增内容
1. 系统工具可配置自定义的分类属性。
......@@ -32,8 +47,7 @@ description: 'FastGPT V4.14.6 更新说明'
### 代码质量
1. useRequest2 替代 useRequest。
1. useRequest2 替代 useRequest。减少无用代码。
## 🐛 修复
......
---
title: 'V4.14.7(进行中)'
title: 'V4.14.7(包含升级脚本)'
description: 'FastGPT V4.14.7 更新说明'
---
## 更新指南
### 1. 更新镜像
- 更新 FastGPT 镜像 tag: v4.14.7
- 更新 FastGPT 商业版镜像 tag: v4.14.7
- 更新 fastgpt-plugin 镜像 tag: v0.5.3
- mcp_server 无需更新
- sandbox 无需更新
- 更新 AIProxy 镜像 tag: 0.3.15
- mongo 无需更新
### 2. 更新系统环境变量
更新了日志系统,包括但不限于日志打印、日志采集和日志分析等
```dotenv
# 移除环境变量
LOG_LEVEL=
STORE_LOG_LEVEL=
SIGNOZ_BASE_URL=
SIGNOZ_SERVICE_NAME=
SIGNOZ_STORE_LEVEL=
# 新增以下 6 个变量
LOG_ENABLE_CONSOLE=true # 是否开启控制台打印
LOG_CONSOLE_LEVEL=debug # 控制台打印最低日志等级
LOG_ENABLE_OTEL=true # 是否开启 OTEL 日志收集
LOG_OTEL_LEVEL=info # OTEL 日志收集的最低日志等级
LOG_OTEL_SERVICE_NAME=fastgpt-client # 传递给 OTLP 收集器的服务名称
LOG_OTEL_URL=http://localhost:4318/v1/logs # 你的 OTLP 收集器的地址,不要把 /v1/logs 遗漏了
```
### 3. 更新系统插件
前往插件市场更新以下几个系统工具(如果 4.14.6 升级了,这里可以跳过)。可以直接下载[zip 包](https://github.com/labring/fastgpt-plugin/raw/refs/heads/main/.github/assets/upgrade_pkg.zip)直接安装。
* base64Decode:base64 解码转化
* dallle3: dall-e 3 图片生成
* docDiff: 文档差异对比
* drawing: BI图表
* gptImage: gpt 图片生成
* markdownTransform: markdown 转换文件
* mineru: Mineru pdf解析
* minimax: minimax 对话
* openrouterMultiModal: openrouter 多模态
* stability: stability 图片生成
### 4. 执行升级脚本
从任意终端,发起 1 个 HTTP 请求。其中 `{{rootkey}}` 替换成环境变量里的 `rootkey`;`{{host}}` 替换成**FastGPT 域名**。
```bash
curl --location --request POST 'https://{{host}}/api/admin/initv4147' \
--header 'rootkey: {{rootkey}}' \
--header 'Content-Type: application/json'
```
1. 会将对话日志中,含错误的记录添加到统计表里。
### 5. 接口更新
在新版本的对话记录中,value 值的 type 已被移除,`/api/core/chat/getPaginationRecords`暂时做了适配,请使用该 API 的用户尽快调整 value 解析方案,直接判断 `text`,`tools`等字段是否存在即可。
## 🚀 新增内容
1. 知识库搜索,支持指定 collectionIds 来进行筛选。
1. 基于上下文工程的 Agent 模式,适合长任务拆解的场景。(测试版)
2. 临时增加 LLM 请求追踪,方便调试。会保留所有 LLM 的请求体和响应(默认保留 6 小时,通过 `LLM_REQUEST_TRACKING_RETENTION_HOURS` 变量调整)
3. 知识库搜索,支持指定 collectionIds 来进行筛选。
4. 模型监控增加缓存命中率。
5. 分享链接,自定义鉴权模式下,finish 事件会传输 chatId。
6. 对话日志列表,增加仅看错误日志过滤选项。
7. 对话日志列表,精准的过滤使用者。
8. 依赖预检查,启动项目时进行infra/子服务有效性检测,便于准确定位不可用的服务。
9. MCP 服务解析时,支持解析 schema 中的 $ref 语法。
10. 使用 [LogTape](https://logtape.org/) 重构了日志系统,包括但不限于日志打印、日志采集和日志分析等。同时移除了 mongo 的日志存储,可使用 OTEL 收集器进行收集。
## ⚙️ 优化
1. Chat Agent 中工具选择和知识库选择 UX。
2. MCP 保存时,自动过滤掉多余的字段,避免 mongo4.x 不兼容。
3. 后端自动过滤掉未配置的工具,避免模型调用未配置的工具导致报错。采用相同的过滤函数,保证前后端逻辑一致性。
4. 增加对话日志模式,工作流 AI 模型的记忆选择。
5. 工具调用时,自动补充空的 arguments 成 "{}",避免部分模型服务商不支持空字符串导致报错。
6. 适配 kimi2.5 思考模式下工具调用。
7. 内网域名检查方式。
8. 工作流运行前,去除孤立的边。
9. 通过 API 调用工作流,传入文件链接时,不再采用根据链接推测类型的方式,直接保存输入的 type,确保文件类型 100% 正确。
## 🐛 修复
1. 工作流全局变量中,部分类型赋值错误的 defaultValueType。
2. 工作流 AI 节点,思考输出值未正常渲染。
3. 精确获取 MCP 单个子工具的权限,避免越权调用。
4. 工具集 ToolName 避免数字开头导致工具调用失败。
5. 简易应用转工作流,未复制一份头像。
6. 导入工作流时,引用类型的模型字段被误判为无效模型而清空。
7. Iphone safari 浏览器下,分享链接首次进入有概率触发 uid 为空的请求。
8. MCP 暴露 Agent 时,无法传入文件链接。
9. 创建 http 工具时,body 包含变量会报错 JSON 解析错误。
10. 工作流切换 Tab 后画布自动定位失效。
11. 工作流节点出现系统未捕获的错误时,未正确走报错捕获分支。
## 插件
1. 新增获取用户信息工具。
2. 增加 kimi2.5 模型预设。
## 代码质量
1. 增加向量数据库集成测试。
2. 完善 packages/global 单元测试,提高覆盖到 90+。
{
"title": "4.14.x",
"description": "",
"pages": ["4146","41451","4145", "4144", "4143", "4142", "4141", "4140"]
"pages": ["4147", "4146", "41451", "4145", "4144", "4143", "4142", "4141", "4140"]
}
......@@ -20,7 +20,7 @@
"document/content/docs/introduction/development/custom-models/xinference.mdx": "2025-08-05T23:20:39+08:00",
"document/content/docs/introduction/development/design/dataset.mdx": "2025-07-23T21:35:03+08:00",
"document/content/docs/introduction/development/design/design_plugin.mdx": "2025-11-06T14:47:55+08:00",
"document/content/docs/introduction/development/docker.mdx": "2026-01-30T18:47:43+08:00",
"document/content/docs/introduction/development/docker.mdx": "2026-02-11T13:31:15+08:00",
"document/content/docs/introduction/development/faq.mdx": "2025-08-12T22:22:18+08:00",
"document/content/docs/introduction/development/intro.mdx": "2025-09-29T11:34:11+08:00",
"document/content/docs/introduction/development/migration/docker_db.mdx": "2025-07-23T21:35:03+08:00",
......@@ -31,18 +31,12 @@
"document/content/docs/introduction/development/modelConfig/ppio.mdx": "2025-09-29T11:52:39+08:00",
"document/content/docs/introduction/development/modelConfig/siliconCloud.mdx": "2025-08-05T23:20:39+08:00",
"document/content/docs/introduction/development/object-storage.mdx": "2026-01-09T18:25:02+08:00",
"document/content/docs/introduction/development/openapi/app.mdx": "2025-09-26T13:18:51+08:00",
"document/content/docs/introduction/development/openapi/chat.mdx": "2025-12-18T13:49:45+08:00",
"document/content/docs/introduction/development/openapi/dataset.mdx": "2025-09-29T11:34:11+08:00",
"document/content/docs/introduction/development/openapi/intro.mdx": "2025-09-29T11:34:11+08:00",
"document/content/docs/introduction/development/openapi/share.mdx": "2025-12-09T23:33:32+08:00",
"document/content/docs/introduction/development/openapi/swagger.mdx": "2026-01-06T13:25:46+08:00",
"document/content/docs/introduction/development/proxy/cloudflare.mdx": "2025-07-23T21:35:03+08:00",
"document/content/docs/introduction/development/proxy/http_proxy.mdx": "2025-07-23T21:35:03+08:00",
"document/content/docs/introduction/development/proxy/nginx.mdx": "2025-07-23T21:35:03+08:00",
"document/content/docs/introduction/development/quick-start.mdx": "2025-10-21T11:58:25+08:00",
"document/content/docs/introduction/development/sealos.mdx": "2025-11-11T14:05:02+08:00",
"document/content/docs/introduction/development/signoz.mdx": "2025-09-17T22:29:56+08:00",
"document/content/docs/introduction/development/signoz.mdx": "2026-02-12T11:32:33+08:00",
"document/content/docs/introduction/guide/DialogBoxes/htmlRendering.mdx": "2025-07-23T21:35:03+08:00",
"document/content/docs/introduction/guide/DialogBoxes/quoteList.mdx": "2025-07-23T21:35:03+08:00",
"document/content/docs/introduction/guide/admin/sso.mdx": "2026-01-05T20:53:39+08:00",
......@@ -96,6 +90,12 @@
"document/content/docs/introduction/guide/team_permissions/team_roles_permissions.mdx": "2025-07-23T21:35:03+08:00",
"document/content/docs/introduction/index.en.mdx": "2025-07-23T21:35:03+08:00",
"document/content/docs/introduction/index.mdx": "2025-09-29T11:34:11+08:00",
"document/content/docs/introduction/openapi/app.mdx": "2026-02-11T13:31:15+08:00",
"document/content/docs/introduction/openapi/chat.mdx": "2026-02-11T13:31:15+08:00",
"document/content/docs/introduction/openapi/dataset.mdx": "2026-02-11T13:31:15+08:00",
"document/content/docs/introduction/openapi/intro.mdx": "2026-02-11T13:31:15+08:00",
"document/content/docs/introduction/openapi/share.mdx": "2026-02-11T13:31:15+08:00",
"document/content/docs/introduction/openapi/swagger.mdx": "2026-02-11T13:31:15+08:00",
"document/content/docs/protocol/index.mdx": "2025-07-30T15:38:30+08:00",
"document/content/docs/protocol/open-source.en.mdx": "2025-08-05T23:20:39+08:00",
"document/content/docs/protocol/open-source.mdx": "2025-08-05T23:20:39+08:00",
......@@ -104,7 +104,7 @@
"document/content/docs/protocol/terms.en.mdx": "2025-12-15T23:36:54+08:00",
"document/content/docs/protocol/terms.mdx": "2025-12-15T23:36:54+08:00",
"document/content/docs/toc.en.mdx": "2025-08-04T13:42:36+08:00",
"document/content/docs/toc.mdx": "2026-02-02T18:48:25+08:00",
"document/content/docs/toc.mdx": "2026-02-11T13:31:15+08:00",
"document/content/docs/upgrading/4-10/4100.mdx": "2025-08-02T19:38:37+08:00",
"document/content/docs/upgrading/4-10/4101.mdx": "2025-09-08T20:07:20+08:00",
"document/content/docs/upgrading/4-11/4110.mdx": "2025-08-05T23:20:39+08:00",
......@@ -124,8 +124,8 @@
"document/content/docs/upgrading/4-14/4144.mdx": "2026-02-04T14:27:58+08:00",
"document/content/docs/upgrading/4-14/4145.mdx": "2026-01-18T23:59:15+08:00",
"document/content/docs/upgrading/4-14/41451.mdx": "2026-01-20T11:53:27+08:00",
"document/content/docs/upgrading/4-14/4146.mdx": "2026-02-04T14:27:58+08:00",
"document/content/docs/upgrading/4-14/4147.mdx": "2026-02-02T18:48:25+08:00",
"document/content/docs/upgrading/4-14/4146.mdx": "2026-02-09T10:22:42+08:00",
"document/content/docs/upgrading/4-14/4147.mdx": "2026-02-12T11:32:33+08:00",
"document/content/docs/upgrading/4-8/40.mdx": "2025-08-02T19:38:37+08:00",
"document/content/docs/upgrading/4-8/41.mdx": "2025-08-02T19:38:37+08:00",
"document/content/docs/upgrading/4-8/42.mdx": "2025-08-02T19:38:37+08:00",
......
......@@ -4,7 +4,7 @@ import { ERROR_RESPONSE } from './errorCode';
export const getErrText = (err: any, def = ''): any => {
const msg: string =
typeof err === 'string'
? err
? err || def
: err?.response?.data?.message ||
err?.response?.message ||
err?.message ||
......
import { detect } from 'jschardet';
import { imageFileType } from './constants';
import { ChatFileTypeEnum } from '../../core/chat/constants';
import { type UserChatItemFileItemType } from '../../core/chat/type';
import * as fs from 'fs';
import path from 'path';
export const formatFileSize = (bytes: number): string => {
if (bytes === 0) return '0 B';
......@@ -18,86 +13,3 @@ export const formatFileSize = (bytes: number): string => {
export const detectFileEncoding = (buffer: Buffer) => {
return detect(buffer.slice(0, 200))?.encoding?.toLocaleLowerCase();
};
export const detectFileEncodingByPath = async (path: string) => {
// Get 64KB file head
const MAX_BYTES = 64 * 1024;
const buffer = Buffer.alloc(MAX_BYTES);
const fd = await fs.promises.open(path, 'r');
try {
// Read file head
// @ts-ignore
const { bytesRead } = await fd.read(buffer, 0, MAX_BYTES, 0);
const actualBuffer = buffer.slice(0, bytesRead);
return detect(actualBuffer)?.encoding?.toLocaleLowerCase();
} finally {
await fd.close();
}
};
// Url => user upload file type
export const parseUrlToFileType = (url: string): UserChatItemFileItemType | undefined => {
if (typeof url !== 'string') return;
// Handle base64 image
if (url.startsWith('data:')) {
const matches = url.match(/^data:([^;]+);base64,/);
if (!matches) return;
const mimeType = matches[1].toLowerCase();
if (!mimeType.startsWith('image/')) return;
const extension = mimeType.split('/')[1];
return {
type: ChatFileTypeEnum.image,
name: `image.${extension}`,
url
};
}
try {
const parseUrl = new URL(url, 'http://localhost:3000');
// Get filename from URL
const filename = (() => {
// Here is a S3 Object Key
if (url.startsWith('chat/')) {
const basename = path.basename(url);
// Return empty if no extension
return basename.includes('.') ? basename : '';
}
const fromParam = parseUrl.searchParams.get('filename');
if (fromParam) {
return fromParam;
}
const basename = path.basename(parseUrl.pathname);
// Return empty if no extension
return basename.includes('.') ? basename : '';
})();
const extension = filename?.split('.').pop()?.toLowerCase() || '';
if (extension && imageFileType.includes(extension)) {
// Default to file type for non-extension files
return {
type: ChatFileTypeEnum.image,
name: filename || 'null',
url
};
}
// If it's a document type, return as file, otherwise treat as image
return {
type: ChatFileTypeEnum.file,
name: filename || 'null',
url
};
} catch (error) {
return {
type: ChatFileTypeEnum.file,
name: url,
url
};
}
};
export type I18nStringType = {
'zh-CN'?: string;
'zh-Hant'?: string;
en: string;
};
import z from 'zod';
export const I18nStringSchema = z.object({
en: z.string(),
'zh-CN': z.string().optional(),
'zh-Hant': z.string().optional()
});
export type I18nStringType = z.infer<typeof I18nStringSchema>;
export enum LangEnum {
'zh_CN' = 'zh-CN',
......
......@@ -4,8 +4,8 @@ export const parseI18nString = (str: I18nStringType | string = '', lang = 'en')
if (!str || typeof str === 'string') return str;
// 尝试使用当前语言
if (str[lang as localeType]) {
return str[lang as localeType] || '';
if (lang in str) {
return str[lang as keyof I18nStringType] || '';
}
// 如果当前语言是繁体中文但没有对应翻译,优先回退到简体中文
......
......@@ -19,5 +19,6 @@ export enum TrackEnum {
chatHistoryCleanup = 'chatHistoryCleanup',
// web tracks
clientError = 'clientError'
clientError = 'clientError',
workflowDemoMode = 'workflowDemoMode'
}
......@@ -9,7 +9,7 @@ export type GetPathProps = {
};
export type ParentTreePathItemType = {
parentId: string;
parentId: ParentIdType;
parentName: string;
};
......
import { i18nT } from '../../../web/i18n/utils';
export enum HeaderSecretTypeEnum {
None = 'None',
Bearer = 'Bearer',
......
export type SecretValueType = {
value: string;
secret: string;
};
export type StoreSecretValueType = Record<string, SecretValueType>;
import z from 'zod';
export const SecretValueTypeSchema = z
.object({
value: z.string().optional(),
secret: z.string().optional()
})
.meta({
description: '密钥值类型,value 为明文,secret 为密文,如果了 value 则优先使用 value。',
example: {
value: '1234567890',
secret: ''
}
});
export type SecretValueType = z.infer<typeof SecretValueTypeSchema>;
export const StoreSecretValueTypeSchema = z.record(z.string(), SecretValueTypeSchema).meta({
description: '存储密钥值类型,key 为密钥名称,value 为密钥值。',
example: {
Authorization: {
value: '1234567890',
secret: ''
}
}
});
export type StoreSecretValueType = z.infer<typeof StoreSecretValueTypeSchema>;
/* v8 ignore file */
import SwaggerParser from '@apidevtools/swagger-parser';
export const loadOpenAPISchemaFromUrl = async (url: string) => {
......
......@@ -134,14 +134,6 @@ export const customNanoid = (str: string, size: number) => customAlphabet(str, s
/* Custom text to reg, need to replace special chats */
export const replaceRegChars = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
export const getRegQueryStr = (text: string, flags = 'i') => {
const formatText = replaceRegChars(text);
const chars = formatText.split('');
const regexPattern = chars.join('.*');
return new RegExp(regexPattern, flags);
};
/* slice json str */
export const sliceJsonStr = (str: string) => {
str = str.trim();
......@@ -174,7 +166,9 @@ export const sliceJsonStr = (str: string) => {
return str;
};
export const sliceStrStartEnd = (str: string, start: number, end: number) => {
export const sliceStrStartEnd = (str: string | null = '', start: number, end: number) => {
if (!str) return '';
const overSize = str.length > start + end;
if (!overSize) return str;
......
......@@ -8,7 +8,7 @@ import type {
AudioSpeechModels,
STTModelType,
RerankModelItemType
} from '../../../core/ai/model.d';
} from '../../../core/ai/model.schema';
import { SubTypeEnum } from '../../../support/wallet/sub/constants';
export type NavbarItemType = {
......
......@@ -8,7 +8,7 @@ export const delay = (ms: number) =>
export const retryFn = async <T>(fn: () => Promise<T>, attempts = 3): Promise<T> => {
while (true) {
try {
return fn();
return await fn();
} catch (error) {
if (attempts <= 0) {
return Promise.reject(error);
......@@ -19,23 +19,19 @@ export const retryFn = async <T>(fn: () => Promise<T>, attempts = 3): Promise<T>
}
};
export const batchRun = async <T>(arr: T[], fn: (arr: T) => any, batchSize = 10) => {
const batchArr = new Array(batchSize).fill(null);
const result: any[] = [];
export const batchRun = async <T, R>(
arr: T[],
fn: (item: T, index: number) => Promise<R>,
batchSize = 10
): Promise<R[]> => {
const result: R[] = new Array(arr.length);
let nextIndex = 0;
const batchFn = async () => {
const data = arr.shift();
if (data) {
result.push(await fn(data));
return batchFn();
while (nextIndex < arr.length) {
const currentIndex = nextIndex++;
result[currentIndex] = await fn(arr[currentIndex], currentIndex);
}
};
await Promise.all(
batchArr.map(async () => {
await batchFn();
})
);
await Promise.all(Array.from({ length: Math.min(batchSize, arr.length) }, () => batchFn()));
return result;
};
......@@ -21,7 +21,8 @@ export const getTimezoneOffset = (timeZone: string): number => {
const localString = now.toLocaleString('en-US');
const diff = (Date.parse(localString) - Date.parse(tzString)) / 3600000;
const offset = diff + now.getTimezoneOffset() / 60;
return -offset;
// Ensure we return +0 instead of -0 for UTC
return offset === 0 ? 0 : -offset;
};
/**
......@@ -78,15 +79,14 @@ export const getTimezoneCodeFromStr = (timeString: string | Date) => {
return '+00:00';
}
if (timeString.includes('+')) {
const timezoneMatch = timeString.split('+');
return `+${timezoneMatch[1]}`;
} else if (timeString.includes('-')) {
const timezoneMatch = timeString.split('-');
return `-${timezoneMatch[1]}`;
} else {
return '+00:00';
// Match timezone offset pattern at the end of string: +HH:MM or -HH:MM
const timezoneMatch = timeString.match(/([+-]\d{2}:\d{2})$/);
if (timezoneMatch) {
return timezoneMatch[1];
}
return '+00:00';
};
export const getSystemTime = (timeZone: string) => {
......
import { z } from 'zod';
export const ObjectIdSchema = z
export const ObjectIdSchema = z.preprocess(
(value) => (typeof value === 'object' ? String(value) : value),
z
.string()
.regex(/^[0-9a-fA-F]{24}$/)
.meta({ example: '68ee0bd23d17260b7829b137', description: 'ObjectId' });
.meta({ example: '68ee0bd23d17260b7829b137', description: 'ObjectId' })
);
import { getNanoid } from '../../../common/string/tools';
import z from 'zod';
export const AgentStepItemSchema = z.object({
id: z.string().default(getNanoid(6)),
title: z.string(),
description: z.string(),
depends_on: z.array(z.string()).nullish(),
response: z.string().nullish(),
summary: z.string().nullish()
});
export type AgentStepItemType = z.infer<typeof AgentStepItemSchema>;
export const AgentPlanSchema = z.object({
planId: z.string().default(getNanoid(6)),
task: z.string(),
description: z.string(),
background: z.string().nullish(),
steps: z.array(AgentStepItemSchema)
});
export type AgentPlanType = z.infer<typeof AgentPlanSchema>;
import { i18nT } from '../../../web/i18n/utils';
import type { CompletionUsage } from './type';
import type { LLMModelItemType, EmbeddingModelItemType, STTModelType } from './model.schema';
export const getLLMDefaultUsage = (): CompletionUsage => {
return {
......@@ -9,6 +10,66 @@ export const getLLMDefaultUsage = (): CompletionUsage => {
};
};
export enum ModelTypeEnum {
llm = 'llm',
embedding = 'embedding',
tts = 'tts',
stt = 'stt',
rerank = 'rerank'
}
export const defaultQAModels: LLMModelItemType[] = [
{
type: ModelTypeEnum.llm,
provider: 'OpenAI',
model: 'gpt-5',
name: 'gpt-5',
maxContext: 16000,
maxResponse: 16000,
quoteMaxToken: 13000,
maxTemperature: 1.2,
charsPointsPrice: 0,
censor: false,
vision: true,
datasetProcess: true,
toolChoice: true,
functionCall: false,
defaultSystemChatPrompt: '',
defaultConfig: {}
}
];
export const defaultVectorModels: EmbeddingModelItemType[] = [
{
type: ModelTypeEnum.embedding,
provider: 'OpenAI',
model: 'text-embedding-3-small',
name: 'Embedding-2',
charsPointsPrice: 0,
defaultToken: 500,
maxToken: 3000,
weight: 100
}
];
export const defaultSTTModels: STTModelType[] = [
{
type: ModelTypeEnum.stt,
provider: 'OpenAI',
model: 'whisper-1',
name: 'whisper-1',
charsPointsPrice: 0
}
];
export const modelTypeList = [
{ label: i18nT('common:model.type.chat'), value: ModelTypeEnum.llm },
{ label: i18nT('common:model.type.embedding'), value: ModelTypeEnum.embedding },
{ label: i18nT('common:model.type.tts'), value: ModelTypeEnum.tts },
{ label: i18nT('common:model.type.stt'), value: ModelTypeEnum.stt },
{ label: i18nT('common:model.type.reRank'), value: ModelTypeEnum.rerank }
];
export enum ChatCompletionRequestMessageRoleEnum {
'System' = 'system',
'User' = 'user',
......
import type { ModelTypeEnum } from './model';
type PriceType = {
charsPointsPrice?: number; // 1k chars=n points; 60s=n points;
// If inputPrice is set, the input-output charging scheme is adopted
inputPrice?: number; // 1k tokens=n points
outputPrice?: number; // 1k tokens=n points
};
type BaseModelItemType = {
provider: string;
model: string;
name: string;
avatar?: string; // model icon, from provider
isActive?: boolean;
isCustom?: boolean;
isDefault?: boolean;
isDefaultDatasetTextModel?: boolean;
isDefaultDatasetImageModel?: boolean;
// If has requestUrl, it will request the model directly
requestUrl?: string;
requestAuth?: string;
};
export type LLMModelItemType = PriceType &
BaseModelItemType & {
type: ModelTypeEnum.llm;
// Model params
maxContext: number;
maxResponse: number;
quoteMaxToken: number;
maxTemperature?: number;
showTopP?: boolean;
responseFormatList?: string[];
showStopSign?: boolean;
censor?: boolean;
vision?: boolean;
reasoning?: boolean;
// diff function model
datasetProcess?: boolean; // dataset
usedInClassify?: boolean; // classify
usedInExtractFields?: boolean; // extract fields
usedInToolCall?: boolean; // tool call
useInEvaluation?: boolean; // evaluation
functionCall: boolean;
toolChoice: boolean;
defaultSystemChatPrompt?: string;
defaultConfig?: Record<string, any>;
fieldMap?: Record<string, string>;
};
export type EmbeddingModelItemType = PriceType &
BaseModelItemType & {
type: ModelTypeEnum.embedding;
defaultToken: number; // split text default token
maxToken: number; // model max token
weight: number; // training weight
hidden?: boolean; // Disallow creation
normalization?: boolean; // normalization processing
batchSize?: number;
defaultConfig?: Record<string, any>; // post request config
dbConfig?: Record<string, any>; // Custom parameters for storage
queryConfig?: Record<string, any>; // Custom parameters for query
};
export type RerankModelItemType = PriceType &
BaseModelItemType & {
type: ModelTypeEnum.rerank;
};
export type TTSModelType = PriceType &
BaseModelItemType & {
type: ModelTypeEnum.tts;
voices: { label: string; value: string }[];
};
export type STTModelType = PriceType &
BaseModelItemType & {
type: ModelTypeEnum.stt;
};
/* v8 ignore file */
import { ModelTypeEnum } from './constants';
import z from 'zod';
const PriceTypeSchema = z.object({
charsPointsPrice: z.number().optional(), // 1k chars=n points; 60s=n points;
// If inputPrice is set, the input-output charging scheme is adopted
inputPrice: z.number().optional(), // 1k tokens=n points
outputPrice: z.number().optional() // 1k tokens=n points
});
type PriceType = z.infer<typeof PriceTypeSchema>;
const BaseModelItemSchema = z.object({
provider: z.string(),
model: z.string(),
name: z.string(),
avatar: z.string().optional(), // model icon, from provider
isActive: z.boolean().optional(),
isCustom: z.boolean().optional(),
isDefault: z.boolean().optional(),
// If has requestUrl, it will request the model directly
requestUrl: z.string().optional(),
requestAuth: z.string().optional()
});
type BaseModelItemType = z.infer<typeof BaseModelItemSchema>;
export const LLMModelItemSchema = PriceTypeSchema.extend(BaseModelItemSchema.shape).extend({
type: z.literal(ModelTypeEnum.llm),
// Model params
maxContext: z.number(),
maxResponse: z.number(),
quoteMaxToken: z.number(),
maxTemperature: z.number().optional(),
showTopP: z.boolean().optional(),
responseFormatList: z.array(z.string()).optional(),
showStopSign: z.boolean().optional(),
censor: z.boolean().optional(),
vision: z.boolean().optional(),
reasoning: z.boolean().optional(),
// diff function model
datasetProcess: z.boolean().optional(), // dataset
usedInClassify: z.boolean().optional(), // classify
usedInExtractFields: z.boolean().optional(), // extract fields
usedInToolCall: z.boolean().optional(), // tool call
useInEvaluation: z.boolean().optional(), // evaluation
functionCall: z.boolean(),
toolChoice: z.boolean(),
defaultSystemChatPrompt: z.string().optional(),
defaultConfig: z.record(z.string(), z.any()).optional(),
fieldMap: z.record(z.string(), z.string()).optional(),
// LLM
isDefaultDatasetTextModel: z.boolean().optional(),
isDefaultDatasetImageModel: z.boolean().optional(),
isDefaultHelperBotModel: z.boolean().optional()
});
export type LLMModelItemType = z.infer<typeof LLMModelItemSchema>;
export const EmbeddingModelItemSchema = PriceTypeSchema.extend(BaseModelItemSchema.shape).extend({
type: z.literal(ModelTypeEnum.embedding),
defaultToken: z.number(), // split text default token
maxToken: z.number(), // model max token
weight: z.number(), // training weight
hidden: z.boolean().optional(), // Disallow creation
normalization: z.boolean().optional(), // normalization processing
batchSize: z.number().optional(), // batch request size
defaultConfig: z.record(z.string(), z.any()).optional(), // post request config
dbConfig: z.record(z.string(), z.any()).optional(), // Custom parameters for storage
queryConfig: z.record(z.string(), z.any()).optional() // Custom parameters for query
});
export type EmbeddingModelItemType = z.infer<typeof EmbeddingModelItemSchema>;
export const RerankModelItemSchema = PriceTypeSchema.extend(BaseModelItemSchema.shape).extend({
type: z.literal(ModelTypeEnum.rerank)
});
export type RerankModelItemType = z.infer<typeof RerankModelItemSchema>;
export const TTSModelItemSchema = PriceTypeSchema.extend(BaseModelItemSchema.shape).extend({
type: z.literal(ModelTypeEnum.tts),
voices: z.array(z.object({ label: z.string(), value: z.string() }))
});
export type TTSModelType = z.infer<typeof TTSModelItemSchema>;
export const STTModelItemSchema = PriceTypeSchema.extend(BaseModelItemSchema.shape).extend({
type: z.literal(ModelTypeEnum.stt)
});
export type STTModelType = z.infer<typeof STTModelItemSchema>;
import { i18nT } from '../../../web/i18n/utils';
import type { LLMModelItemType, STTModelType, EmbeddingModelItemType } from './model.d';
export enum ModelTypeEnum {
llm = 'llm',
embedding = 'embedding',
tts = 'tts',
stt = 'stt',
rerank = 'rerank'
}
export const defaultQAModels: LLMModelItemType[] = [
{
type: ModelTypeEnum.llm,
provider: 'OpenAI',
model: 'gpt-5',
name: 'gpt-5',
maxContext: 16000,
maxResponse: 16000,
quoteMaxToken: 13000,
maxTemperature: 1.2,
charsPointsPrice: 0,
censor: false,
vision: true,
datasetProcess: true,
toolChoice: true,
functionCall: false,
defaultSystemChatPrompt: '',
defaultConfig: {}
}
];
export const defaultVectorModels: EmbeddingModelItemType[] = [
{
type: ModelTypeEnum.embedding,
provider: 'OpenAI',
model: 'text-embedding-3-small',
name: 'Embedding-2',
charsPointsPrice: 0,
defaultToken: 500,
maxToken: 3000,
weight: 100
}
];
export const defaultSTTModels: STTModelType[] = [
{
type: ModelTypeEnum.stt,
provider: 'OpenAI',
model: 'whisper-1',
name: 'whisper-1',
charsPointsPrice: 0
}
];
export const modelTypeList = [
{ label: i18nT('common:model.type.chat'), value: ModelTypeEnum.llm },
{ label: i18nT('common:model.type.embedding'), value: ModelTypeEnum.embedding },
{ label: i18nT('common:model.type.tts'), value: ModelTypeEnum.tts },
{ label: i18nT('common:model.type.stt'), value: ModelTypeEnum.stt },
{ label: i18nT('common:model.type.reRank'), value: ModelTypeEnum.rerank }
];
import { type PromptTemplateItem } from '../type.d';
/* v8 ignore file */
import { type PromptTemplateItem } from '../type';
import { i18nT } from '../../../../web/i18n/utils';
import { getPromptByVersion } from './utils';
......
import z from 'zod';
export const SkillToolSchema = z.object({
id: z.string(),
config: z.record(z.string(), z.any())
});
export type SkillToolType = z.infer<typeof SkillToolSchema>;
......@@ -2,15 +2,12 @@ import openai from 'openai';
import type {
ChatCompletion as SdkChatCompletion,
ChatCompletionMessageToolCall,
ChatCompletionMessageParam as SdkChatCompletionMessageParam,
ChatCompletionToolMessageParam,
ChatCompletionMessageParam as OpenaiChatCompletionMessageParam,
ChatCompletionContentPart as SdkChatCompletionContentPart,
ChatCompletionUserMessageParam as SdkChatCompletionUserMessageParam,
ChatCompletionToolMessageParam as SdkChatCompletionToolMessageParam,
ChatCompletionAssistantMessageParam as SdkChatCompletionAssistantMessageParam,
ChatCompletionTool
ChatCompletionAssistantMessageParam as SdkChatCompletionAssistantMessageParam
} from 'openai/resources';
import { ChatMessageTypeEnum } from './constants';
import type { WorkflowInteractiveResponseType } from '../workflow/template/system/interactive/type';
import type { Stream } from 'openai/streaming';
export * from 'openai/resources';
......@@ -26,11 +23,11 @@ export type ChatCompletionContentPartFile = {
export type ChatCompletionContentPart =
| (SdkChatCompletionContentPart & { key?: string })
| ChatCompletionContentPartFile;
type CustomChatCompletionUserMessageParam = Omit<ChatCompletionUserMessageParam, 'content'> & {
type CustomChatCompletionUserMessageParam = Omit<SdkChatCompletionUserMessageParam, 'content'> & {
role: 'user';
content: string | Array<ChatCompletionContentPart>;
};
type CustomChatCompletionToolMessageParam = SdkChatCompletionToolMessageParam & {
export type CustomChatCompletionToolMessageParam = SdkChatCompletionToolMessageParam & {
role: 'tool';
name?: string;
};
......@@ -50,14 +47,13 @@ export type ChatCompletionMessageParam = (
| CustomChatCompletionToolMessageParam
| CustomChatCompletionAssistantMessageParam
) & {
reasoning_text?: string;
reasoning_content?: string;
dataId?: string;
hideInUI?: boolean;
};
export type SdkChatCompletionMessageParam = SdkChatCompletionMessageParam;
export type SdkChatCompletionMessageParam = OpenaiChatCompletionMessageParam;
/* ToolChoice and functionCall extension */
export type ChatCompletionToolMessageParam = ChatCompletionToolMessageParam & { name: string };
export type ChatCompletionAssistantToolParam = {
role: 'assistant';
tool_calls: ChatCompletionMessageToolCall[];
......
import {
type AppTTSConfigType,
type AppFileSelectConfigType,
type AppWhisperConfigType,
type AppAutoExecuteConfigType,
type AppQGConfigType
} from './type';
import type { AppFileSelectConfigType } from './type/config.schema';
export enum AppTypeEnum {
folder = 'folder',
toolFolder = 'toolFolder',
simple = 'simple',
agent = 'agent',
chatAgent = 'chatAgent',
workflow = 'advanced',
workflowTool = 'plugin',
mcpToolSet = 'toolSet', // 'mcp'
......@@ -33,7 +33,7 @@ export const ToolTypeList = [
AppTypeEnum.httpToolSet,
AppTypeEnum.workflowTool
];
export const AppTypeList = [AppTypeEnum.simple, AppTypeEnum.agent, AppTypeEnum.workflow];
export const AppTypeList = [AppTypeEnum.simple, AppTypeEnum.chatAgent, AppTypeEnum.workflow];
export const defaultTTSConfig: AppTTSConfigType = { type: 'web' };
......@@ -61,9 +61,9 @@ export const defaultChatInputGuideConfig = {
};
export const defaultAppSelectFileConfig: AppFileSelectConfigType = {
maxFiles: 10,
canSelectFile: false,
canSelectImg: false,
maxFiles: 10,
canSelectVideo: false,
canSelectAudio: false,
canSelectCustomFileExtension: false,
......
import type { ParentIdType } from 'common/parentFolder/type';
import type { AppSchema } from './type';
import type { AppSchemaType } from './type';
import type { AppTypeEnum } from './constants';
export type CreateAppProps = {
......@@ -8,16 +8,16 @@ export type CreateAppProps = {
avatar?: string;
intro?: string;
type?: AppTypeEnum;
modules: AppSchema['modules'];
edges?: AppSchema['edges'];
modules: AppSchemaType['modules'];
edges?: AppSchemaType['edges'];
};
export type CreateHttpPluginChildrenPros = Omit<CreateAppProps, 'type'> & {
parentId: ParentIdType;
name: string;
intro: string;
avatar: string;
modules: AppSchema['modules'];
edges: AppSchema['edges'];
modules: AppSchemaType['modules'];
edges: AppSchemaType['edges'];
pluginData: {
pluginUniId: string;
};
......
import { SelectedDatasetSchema } from '../../workflow/type/io';
import { z } from 'zod';
import { AppChatConfigTypeSchema, AppDatasetSearchParamsTypeSchema } from '../type';
import { FlowNodeTemplateTypeSchema } from '../../workflow/type/node';
import { NodeInputKeyEnum } from '../../workflow/constants';
export type AgentSubAppItemType = {};
/* ===== Tool ===== */
export const SelectedToolItemTypeSchema = FlowNodeTemplateTypeSchema.extend({
configStatus: z.enum(['noConfig', 'waitingForConfig', 'configured', 'invalid']).optional()
});
export type SelectedToolItemType = z.infer<typeof SelectedToolItemTypeSchema>;
export const AppFormEditFormV1TypeSchema = z.object({
aiSettings: z.object({
[NodeInputKeyEnum.aiModel]: z.string(),
[NodeInputKeyEnum.aiSystemPrompt]: z.string().optional(),
[NodeInputKeyEnum.aiChatTemperature]: z.number().optional(),
[NodeInputKeyEnum.aiChatMaxToken]: z.number().optional(),
[NodeInputKeyEnum.aiChatIsResponseText]: z.boolean(),
maxHistories: z.int().min(0).max(100),
[NodeInputKeyEnum.aiChatReasoning]: z.boolean().optional(),
[NodeInputKeyEnum.aiChatTopP]: z.number().optional(),
[NodeInputKeyEnum.aiChatStopSign]: z.string().optional(),
[NodeInputKeyEnum.aiChatResponseFormat]: z.string().optional(),
[NodeInputKeyEnum.aiChatJsonSchema]: z.string().optional()
}),
dataset: AppDatasetSearchParamsTypeSchema.extend({
datasets: z.array(SelectedDatasetSchema)
}),
selectedTools: z.array(SelectedToolItemTypeSchema),
chatConfig: AppChatConfigTypeSchema
});
export type AppFormEditFormType = z.infer<typeof AppFormEditFormV1TypeSchema>;
import { NodeInputKeyEnum, WorkflowIOValueTypeEnum } from '../../workflow/constants';
import { FlowNodeInputTypeEnum } from '../../workflow/node/constant';
import type { FlowNodeTemplateType } from '../../workflow/type/node';
import type { SelectedToolItemType } from './type';
/* Invalid tool check
1. Reference type. but not tool description;
2. Has dataset select
3. Has dynamic external data
*/
export const validateToolConfiguration = ({
toolTemplate,
canUploadFile
}: {
toolTemplate: FlowNodeTemplateType;
canUploadFile?: boolean;
}): boolean => {
// 检查文件上传配置
const oneFileInput =
toolTemplate.inputs.filter((input) =>
input.renderTypeList.includes(FlowNodeInputTypeEnum.fileSelect)
).length === 1;
const hasValidFileInput = oneFileInput && !!canUploadFile;
// 检查是否有无效的输入配置
const hasInvalidInput = toolTemplate.inputs.some((input) => {
// 引用类型但没有工具描述
if (
input.renderTypeList.length === 1 &&
input.renderTypeList[0] === FlowNodeInputTypeEnum.reference &&
!input.toolDescription
) {
return true;
}
// 文件选择但配置无效
if (input.renderTypeList.includes(FlowNodeInputTypeEnum.fileSelect) && !hasValidFileInput) {
return true;
}
// 包含特殊输入类型
const list = [
FlowNodeInputTypeEnum.selectDataset,
FlowNodeInputTypeEnum.addInputParam,
FlowNodeInputTypeEnum.selectLLMModel,
FlowNodeInputTypeEnum.settingLLMModel,
FlowNodeInputTypeEnum.fileSelect
];
if (list.some((type) => input.renderTypeList.includes(type))) {
return true;
}
return false;
});
if (hasInvalidInput) {
return false;
}
return true;
};
export const checkNeedsUserConfiguration = (toolTemplate: {
inputs: FlowNodeTemplateType['inputs'];
}): boolean => {
const formRenderTypesMap: Record<string, boolean> = {
[FlowNodeInputTypeEnum.input]: true,
[FlowNodeInputTypeEnum.textarea]: true,
[FlowNodeInputTypeEnum.numberInput]: true,
[FlowNodeInputTypeEnum.password]: true,
[FlowNodeInputTypeEnum.switch]: true,
[FlowNodeInputTypeEnum.select]: true,
[FlowNodeInputTypeEnum.JSONEditor]: true,
[FlowNodeInputTypeEnum.timePointSelect]: true,
[FlowNodeInputTypeEnum.timeRangeSelect]: true
};
return (
(toolTemplate.inputs.length > 0 &&
toolTemplate.inputs.some((input) => {
// 有工具描述的不需要配置
if (input.toolDescription) return false;
// 禁用流的不需要配置
if (input.key === NodeInputKeyEnum.forbidStream) return false;
// 历史记录不需要配置
if (input.key === NodeInputKeyEnum.history) return false;
// 系统输入配置需要配置
if (input.key === NodeInputKeyEnum.systemInputConfig) return true;
// 检查是否包含表单类型的输入
return input.renderTypeList.some((type) => formRenderTypesMap[type]);
})) ||
false
);
};
/**
* Get the configuration status of a tool
* Checks if tool needs configuration and whether all required fields are filled
* @param tool - The tool template to check
* @returns 'active' if tool is ready to use, 'waitingForConfig' if configuration needed
*/
export const getToolConfigStatus = ({
tool
}: {
tool: {
inputs: FlowNodeTemplateType['inputs'];
};
}): {
needConfig: boolean;
status: SelectedToolItemType['configStatus'];
} => {
// Check if tool needs configuration
const needsConfig = checkNeedsUserConfiguration(tool);
if (!needsConfig) {
return {
needConfig: false,
status: 'noConfig'
};
}
// For tools that need config, check if all required fields have values
const formRenderTypesMap: Record<string, boolean> = {
[FlowNodeInputTypeEnum.input]: true,
[FlowNodeInputTypeEnum.textarea]: true,
[FlowNodeInputTypeEnum.numberInput]: true,
[FlowNodeInputTypeEnum.password]: true,
[FlowNodeInputTypeEnum.select]: true,
[FlowNodeInputTypeEnum.JSONEditor]: true,
[FlowNodeInputTypeEnum.timePointSelect]: true,
[FlowNodeInputTypeEnum.timeRangeSelect]: true
};
// Find all inputs that need configuration(Only check the required items)
const configInputs = tool.inputs.filter((input) => {
if (input.key === NodeInputKeyEnum.forbidStream) return false;
if (input.key === NodeInputKeyEnum.history) return false;
if (input.key === NodeInputKeyEnum.systemInputConfig) return true;
if (input.toolDescription || input.required !== true) return false;
return input.renderTypeList.some((type) => formRenderTypesMap[type]);
});
// Check if all required fields are filled
const allConfigured = configInputs.every((input) => {
const value = input.value;
if (value === undefined || value === null || value === '') return false;
if (Array.isArray(value) && value.length === 0) return false;
if (typeof value === 'object' && Object.keys(value).length === 0) return false;
return true;
});
return {
needConfig: !allConfigured,
status: allConfigured ? 'configured' : 'waitingForConfig'
};
};
......@@ -6,27 +6,42 @@ import yaml from 'js-yaml';
import type { OpenAPIV3 } from 'openapi-types';
import type { OpenApiJsonSchema } from './tool/httpTool/type';
import { i18nT } from '../../../web/i18n/utils';
import z from 'zod';
type SchemaInputValueType = 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object';
export type JsonSchemaPropertiesItemType = {
description?: string;
'x-tool-description'?: string;
type: SchemaInputValueType;
enum?: string[];
minimum?: number;
maximum?: number;
items?: { type: SchemaInputValueType };
};
export type JSONSchemaInputType = {
type: SchemaInputValueType;
properties?: Record<string, JsonSchemaPropertiesItemType>;
required?: string[];
};
export type JSONSchemaOutputType = {
type: SchemaInputValueType;
properties?: Record<string, JsonSchemaPropertiesItemType>;
required?: string[];
};
const SchemaInputValueTypeSchema = z.enum([
'string',
'number',
'integer',
'boolean',
'array',
'object'
]);
type SchemaInputValueType = z.infer<typeof SchemaInputValueTypeSchema>;
export const JsonSchemaPropertiesItemSchema = z.object({
description: z.string().optional(),
'x-tool-description': z.string().optional(),
type: SchemaInputValueTypeSchema,
enum: z.array(z.string()).optional(),
minimum: z.number().optional(),
maximum: z.number().optional(),
items: z.object({ type: SchemaInputValueTypeSchema }).optional()
});
export type JsonSchemaPropertiesItemType = z.infer<typeof JsonSchemaPropertiesItemSchema>;
export const JSONSchemaInputTypeSchema = z.object({
type: SchemaInputValueTypeSchema,
properties: z.record(z.string(), JsonSchemaPropertiesItemSchema).optional(),
required: z.array(z.string()).optional()
});
export type JSONSchemaInputType = z.infer<typeof JSONSchemaInputTypeSchema>;
export const JSONSchemaOutputTypeSchema = z.object({
type: SchemaInputValueTypeSchema,
properties: z.record(z.string(), JsonSchemaPropertiesItemSchema).optional(),
required: z.array(z.string()).optional()
});
export type JSONSchemaOutputType = z.infer<typeof JSONSchemaOutputTypeSchema>;
export const getNodeInputTypeFromSchemaInputType = ({
type,
......@@ -111,8 +126,7 @@ export const jsonSchema2NodeOutput = (
required: jsonSchema?.required?.includes(key),
type: FlowNodeOutputTypeEnum.static,
valueType: getNodeInputTypeFromSchemaInputType({ type: value.type, arrayItems: value.items }),
description: value.description,
toolDescription: value['x-tool-description'] ?? value.description ?? key
description: value.description
}));
};
export const str2OpenApiSchema = async (yamlStr = ''): Promise<OpenApiJsonSchema> => {
......
type PathDataType = {
name: string;
description: string;
method: string;
path: string;
params: any[];
request: any;
response: any;
};
export type OpenApiJsonSchema = {
pathData: PathDataType[];
serverPath: string;
};
import { StoreSecretValueTypeSchema } from '../../../../common/secret/type';
import { JSONSchemaInputTypeSchema, JSONSchemaOutputTypeSchema } from '../../jsonschema';
import { ContentTypes } from '../../../workflow/constants';
import z from 'zod';
const PathDataTypeSchema = z.object({
name: z.string(),
description: z.string(),
method: z.string(),
path: z.string(),
params: z.array(z.any()),
request: z.any(),
response: z.any()
});
export type PathDataType = z.infer<typeof PathDataTypeSchema>;
export const OpenApiJsonSchemaSchema = z.object({
pathData: z.array(PathDataTypeSchema),
serverPath: z.string()
});
export type OpenApiJsonSchema = z.infer<typeof OpenApiJsonSchemaSchema>;
export const HttpToolConfigTypeSchema = z.object({
name: z.string(),
description: z.string(),
inputSchema: JSONSchemaInputTypeSchema,
outputSchema: JSONSchemaOutputTypeSchema,
path: z.string(),
method: z.string(),
// manual
staticParams: z.array(z.object({ key: z.string(), value: z.string() })).optional(),
staticHeaders: z.array(z.object({ key: z.string(), value: z.string() })).optional(),
staticBody: z
.object({
type: z.enum(ContentTypes),
content: z.string().optional(),
formData: z.array(z.object({ key: z.string(), value: z.string() })).optional()
})
.optional(),
headerSecret: StoreSecretValueTypeSchema.optional()
});
export type HttpToolConfigType = z.infer<typeof HttpToolConfigTypeSchema>;
import { getNanoid } from '../../../../common/string/tools';
import type { PathDataType } from './type';
import type { PathDataType, HttpToolConfigType } from './type';
import { type RuntimeNodeItemType } from '../../../workflow/runtime/type';
import { FlowNodeOutputTypeEnum, FlowNodeTypeEnum } from '../../../workflow/node/constant';
import { type HttpToolConfigType } from '../../type';
import { AppToolSourceEnum } from '../constants';
import { jsonSchema2NodeInput, jsonSchema2NodeOutput } from '../../jsonschema';
import { type StoreSecretValueType } from '../../../../common/secret/type';
......@@ -52,21 +51,21 @@ export const getHTTPToolRuntimeNode = ({
tool,
nodeId,
avatar = 'core/app/type/httpToolsFill',
parentId
toolSetId
}: {
tool: Omit<HttpToolConfigType, 'path' | 'method'>;
nodeId?: string;
nodeId: string;
avatar?: string;
parentId: string;
toolSetId: string;
}): RuntimeNodeItemType => {
return {
nodeId: nodeId || getNanoid(16),
nodeId,
flowNodeType: FlowNodeTypeEnum.tool,
avatar,
intro: tool.description,
toolConfig: {
httpTool: {
toolId: `${AppToolSourceEnum.http}-${parentId}/${tool.name}`
toolId: `${AppToolSourceEnum.http}-${toolSetId}/${tool.name}`
}
},
inputs: jsonSchema2NodeInput({ jsonSchema: tool.inputSchema, schemaType: 'http' }),
......
import type { StoreSecretValueType } from '../../../../common/secret/type';
import type { JSONSchemaInputType } from '../../jsonschema';
export type McpToolConfigType = {
name: string;
description: string;
inputSchema: JSONSchemaInputType;
};
export type McpToolSetDataType = {
url: string;
headerSecret?: StoreSecretValueType;
toolList: McpToolConfigType[];
};
export type McpToolDataType = McpToolConfigType & {
url: string;
headerSecret?: StoreSecretValueType;
};
import { SecretValueTypeSchema } from '../../../../common/secret/type';
import { JSONSchemaInputTypeSchema } from '../../jsonschema';
import z from 'zod';
export const McpToolConfigSchema = z.object({
name: z.string(),
description: z.string(),
inputSchema: JSONSchemaInputTypeSchema
});
export type McpToolConfigType = z.infer<typeof McpToolConfigSchema>;
export const McpToolSetDataTypeSchema = z.object({
url: z.string(),
headerSecret: SecretValueTypeSchema.optional(),
toolList: z.array(McpToolConfigSchema)
});
export type McpToolSetDataType = z.infer<typeof McpToolSetDataTypeSchema>;
export const McpToolDataTypeSchema = McpToolConfigSchema.extend({
url: z.string(),
headerSecret: SecretValueTypeSchema.optional()
});
export type McpToolDataType = z.infer<typeof McpToolDataTypeSchema>;
......@@ -46,20 +46,22 @@ export const getMCPToolSetRuntimeNode = ({
export const getMCPToolRuntimeNode = ({
tool,
avatar = 'core/app/type/mcpToolsFill',
parentId
nodeId,
toolSetId
}: {
nodeId: string;
tool: McpToolConfigType;
avatar?: string;
parentId: string;
toolSetId: string;
}): RuntimeNodeItemType => {
return {
nodeId: getNanoid(),
nodeId,
flowNodeType: FlowNodeTypeEnum.tool,
avatar,
intro: tool.description,
toolConfig: {
mcpTool: {
toolId: `${AppToolSourceEnum.mcp}-${parentId}/${tool.name}`
toolId: `${AppToolSourceEnum.mcp}-${toolSetId}/${tool.name}` // When runtool is used, parentId and toolname will be employed
}
},
inputs: jsonSchema2NodeInput({ jsonSchema: tool.inputSchema, schemaType: 'mcp' }),
......
......@@ -30,18 +30,31 @@ export function splitCombineToolId(id: string) {
};
}
// mcp-appId, mcp-appId/toolname
if (source === 'mcp') {
const [parentId, toolName] = pluginId.split('/');
return {
source: AppToolSourceEnum.mcp,
pluginId
pluginId,
authAppId: parentId
};
}
if (source === 'http') {
const [parentId, toolName] = pluginId.split('/');
return {
source: AppToolSourceEnum.http,
pluginId
pluginId,
parentId
};
}
if (source === 'personal') {
return {
source: AppToolSourceEnum.personal,
pluginId,
parentId: pluginId
};
}
return { source, pluginId: id };
}
......
import type { FlowNodeTemplateType, StoreNodeItemType } from '../workflow/type/node';
import type { AppTypeEnum } from './constants';
import { PermissionTypeEnum } from '../../support/permission/constant';
import type {
ContentTypes,
NodeInputKeyEnum,
VariableInputEnum,
WorkflowIOValueTypeEnum
} from '../workflow/constants';
import type { InputComponentPropsType, SelectedDatasetType } from '../workflow/type/io';
import type { DatasetSearchModeEnum } from '../dataset/constants';
import { TeamTagSchema as TeamTagsSchemaType } from '@fastgpt/global/support/user/team/type.d';
import type { StoreEdgeItemType } from '../workflow/type/edge';
import type { AppPermission } from '../../support/permission/app/controller';
import type { ParentIdType } from '../../common/parentFolder/type';
import { FlowNodeInputTypeEnum } from '../../core/workflow/node/constant';
import type { WorkflowTemplateBasicType } from '@fastgpt/global/core/workflow/type';
import type { SourceMemberType, UserTagsEnum } from '../../support/user/type';
import type { JSONSchemaInputType, JSONSchemaOutputType } from './jsonschema';
export type AppSchema = {
_id: string;
parentId?: ParentIdType;
teamId: string;
tmbId: string;
type: AppTypeEnum;
version?: 'v1' | 'v2';
name: string;
avatar: string;
intro: string;
templateId?: string; // Create by template
updateTime: Date;
modules: StoreNodeItemType[];
edges: StoreEdgeItemType[];
pluginData?: {
nodeVersion?: string;
pluginUniId?: string; // plugin unique id(plugin name)
apiSchemaStr?: string; // api schema string
customHeaders?: string;
};
// App system config
chatConfig: AppChatConfigType;
scheduledTriggerConfig?: AppScheduledTriggerConfigType | null;
scheduledTriggerNextTime?: Date;
inheritPermission?: boolean;
// if access the app by favourite or quick
favourite?: boolean;
quick?: boolean;
/** @deprecated */
defaultPermission?: number;
/** @deprecated */
inited?: boolean;
/** @deprecated */
teamTags: string[];
// 软删除字段
deleteTime?: Date | null;
};
export type AppListItemType = {
_id: string;
parentId: ParentIdType;
tmbId: string;
name: string;
avatar: string;
intro: string;
type: AppTypeEnum;
updateTime: Date;
pluginData?: AppSchema['pluginData'];
permission: AppPermission;
inheritPermission?: boolean;
private?: boolean;
sourceMember: SourceMemberType;
hasInteractiveNode?: boolean;
};
export type AppDetailType = AppSchema & {
permission: AppPermission;
};
export type AppDatasetSearchParamsType = {
searchMode: `${DatasetSearchModeEnum}`;
limit?: number; // limit max tokens
similarity?: number;
embeddingWeight?: number; // embedding weight, fullText weight = 1 - embeddingWeight
usingReRank?: boolean;
rerankModel?: string;
rerankWeight?: number;
datasetSearchUsingExtensionQuery?: boolean;
datasetSearchExtensionModel?: string;
datasetSearchExtensionBg?: string;
};
export type AppSimpleEditFormType = {
// templateId: string;
aiSettings: {
[NodeInputKeyEnum.aiModel]: string;
[NodeInputKeyEnum.aiSystemPrompt]?: string | undefined;
[NodeInputKeyEnum.aiChatTemperature]?: number;
[NodeInputKeyEnum.aiChatMaxToken]?: number;
[NodeInputKeyEnum.aiChatIsResponseText]: boolean;
maxHistories: number;
[NodeInputKeyEnum.aiChatReasoning]?: boolean; // Is open reasoning mode
[NodeInputKeyEnum.aiChatTopP]?: number;
[NodeInputKeyEnum.aiChatStopSign]?: string;
[NodeInputKeyEnum.aiChatResponseFormat]?: string;
[NodeInputKeyEnum.aiChatJsonSchema]?: string;
};
dataset: {
datasets: SelectedDatasetType[];
} & AppDatasetSearchParamsType;
selectedTools: FlowNodeTemplateType[];
chatConfig: AppChatConfigType;
};
export type HttpToolConfigType = {
name: string;
description: string;
inputSchema: JSONSchemaInputType;
outputSchema: JSONSchemaOutputType;
path: string;
method: string;
// manual
staticParams?: Array<{ key: string; value: string }>;
staticHeaders?: Array<{ key: string; value: string }>;
staticBody?: {
type: ContentTypes;
content?: string;
formData?: Array<{ key: string; value: string }>;
};
headerSecret?: StoreSecretValueType;
};
/* app chat config type */
export type AppChatConfigType = {
welcomeText?: string;
variables?: VariableItemType[];
autoExecute?: AppAutoExecuteConfigType;
questionGuide?: AppQGConfigType;
ttsConfig?: AppTTSConfigType;
whisperConfig?: AppWhisperConfigType;
scheduledTriggerConfig?: AppScheduledTriggerConfigType;
chatInputGuide?: ChatInputGuideConfigType;
fileSelectConfig?: AppFileSelectConfigType;
// plugin
instruction?: string;
};
export type SettingAIDataType = {
model: string;
temperature?: number;
maxToken?: number;
isResponseAnswerText?: boolean;
maxHistories?: number;
[NodeInputKeyEnum.aiChatVision]?: boolean; // Is open vision mode
[NodeInputKeyEnum.aiChatReasoning]?: boolean; // Is open reasoning mode
[NodeInputKeyEnum.aiChatTopP]?: number;
[NodeInputKeyEnum.aiChatStopSign]?: string;
[NodeInputKeyEnum.aiChatResponseFormat]?: string;
[NodeInputKeyEnum.aiChatJsonSchema]?: string;
};
// variable
export type VariableItemType = AppFileSelectConfigType &
InputComponentPropsType & {
type: VariableInputEnum;
description: string;
};
// tts
export type AppTTSConfigType = {
type: 'none' | 'web' | 'model';
model?: string;
voice?: string;
speed?: number;
};
// whisper
export type AppWhisperConfigType = {
open: boolean;
autoSend: boolean;
autoTTSResponse: boolean;
};
// question guide
export type AppQGConfigType = {
open: boolean;
model?: string;
customPrompt?: string;
};
// question guide text
export type ChatInputGuideConfigType = {
open: boolean;
customUrl: string;
};
// interval timer
export type AppScheduledTriggerConfigType = {
cronString: string;
timezone: string;
defaultPrompt: string;
};
// auto execute
export type AppAutoExecuteConfigType = {
open: boolean;
defaultPrompt: string;
};
// File
export type AppFileSelectConfigType = {
maxFiles?: number;
canSelectFile?: boolean;
customPdfParse?: boolean;
canSelectImg?: boolean;
canSelectVideo?: boolean;
canSelectAudio?: boolean;
canSelectCustomFileExtension?: boolean;
customFileExtensionList?: string[];
};
export type AppTemplateSchemaType = {
templateId: string;
name: string;
intro: string;
avatar: string;
tags: string[];
type: string;
author?: string;
isActive?: boolean;
isPromoted?: boolean;
promoteTags?: UserTagsEnum[];
hideTags?: UserTagsEnum[];
recommendText?: string;
userGuide?: {
type: 'markdown' | 'link';
content?: string;
link?: string;
};
isQuickTemplate?: boolean;
order?: number;
// TODO: 对于建议应用,是另一个格式
workflow: WorkflowTemplateBasicType;
};
export type TemplateTypeSchemaType = {
typeName: string;
typeId: string;
typeOrder: number;
};
import { StoreNodeItemTypeSchema } from '../workflow/type/node';
import { AppTypeEnum } from './constants';
import type { NodeInputKeyEnum } from '../workflow/constants';
import { VariableInputEnum } from '../workflow/constants';
import { InputComponentPropsTypeSchema } from '../workflow/type/io';
import { DatasetSearchModeEnum } from '../dataset/constants';
import { StoreEdgeItemTypeSchema } from '../workflow/type/edge';
import type { AppPermission } from '../../support/permission/app/controller';
import { ParentIdSchema, type ParentIdType } from '../../common/parentFolder/type';
import type { WorkflowTemplateBasicType } from '../workflow/type';
import type { SourceMemberType, UserTagsEnum } from '../../support/user/type';
import z from 'zod';
import { ObjectIdSchema } from '../../common/type/mongo';
import { AppFileSelectConfigTypeSchema } from './type/config.schema';
// variable
export const VariableItemTypeSchema = AppFileSelectConfigTypeSchema.extend(
InputComponentPropsTypeSchema.shape
).extend({
type: z.enum(VariableInputEnum),
description: z.string()
});
export type VariableItemType = z.infer<typeof VariableItemTypeSchema>;
// tts
export const AppTTSConfigTypeSchema = z.object({
type: z.enum(['none', 'web', 'model']),
model: z.string().optional(),
voice: z.string().optional(),
speed: z.number().optional()
});
export type AppTTSConfigType = z.infer<typeof AppTTSConfigTypeSchema>;
// whisper
export const AppWhisperConfigTypeSchema = z.object({
open: z.boolean(),
autoSend: z.boolean(),
autoTTSResponse: z.boolean()
});
export type AppWhisperConfigType = z.infer<typeof AppWhisperConfigTypeSchema>;
// question guide
export const AppQGConfigTypeSchema = z.object({
open: z.boolean(),
model: z.string().optional(),
customPrompt: z.string().optional()
});
export type AppQGConfigType = z.infer<typeof AppQGConfigTypeSchema>;
// question guide text
export const ChatInputGuideConfigTypeSchema = z.object({
open: z.boolean(),
customUrl: z.string()
});
export type ChatInputGuideConfigType = z.infer<typeof ChatInputGuideConfigTypeSchema>;
// interval timer
export const AppScheduledTriggerConfigTypeSchema = z.object({
cronString: z.string(),
timezone: z.string(),
defaultPrompt: z.string()
});
export type AppScheduledTriggerConfigType = z.infer<typeof AppScheduledTriggerConfigTypeSchema>;
// auto execute
export const AppAutoExecuteConfigTypeSchema = z.object({
open: z.boolean(),
defaultPrompt: z.string()
});
export type AppAutoExecuteConfigType = z.infer<typeof AppAutoExecuteConfigTypeSchema>;
export const AppChatConfigTypeSchema = z.object({
welcomeText: z.string().optional(),
variables: z.array(VariableItemTypeSchema).optional(),
autoExecute: AppAutoExecuteConfigTypeSchema.optional(),
questionGuide: AppQGConfigTypeSchema.optional(),
ttsConfig: AppTTSConfigTypeSchema.optional(),
whisperConfig: AppWhisperConfigTypeSchema.optional(),
scheduledTriggerConfig: AppScheduledTriggerConfigTypeSchema.optional(),
chatInputGuide: ChatInputGuideConfigTypeSchema.optional(),
fileSelectConfig: AppFileSelectConfigTypeSchema.optional(),
instruction: z.string().optional()
});
export type AppChatConfigType = z.infer<typeof AppChatConfigTypeSchema>;
// Mongo Collection
export const AppSchemaTypeSchema = z.object({
_id: ObjectIdSchema,
parentId: ParentIdSchema.optional(),
teamId: z.string(),
tmbId: z.string(),
type: z.enum(AppTypeEnum),
version: z.enum(['v1', 'v2']).optional(),
name: z.string(),
avatar: z.string(),
intro: z.string(),
templateId: z.string().optional(),
updateTime: z.date(),
modules: z.array(StoreNodeItemTypeSchema),
edges: z.array(StoreEdgeItemTypeSchema),
pluginData: z
.object({
nodeVersion: z.string().optional(),
pluginUniId: z.string().optional(), // plugin unique id(plugin name)
apiSchemaStr: z.string().optional(), // api schema string
customHeaders: z.string().optional()
})
.optional(),
// App system config
chatConfig: AppChatConfigTypeSchema,
scheduledTriggerConfig: AppScheduledTriggerConfigTypeSchema.optional(),
scheduledTriggerNextTime: z.date().optional(),
inheritPermission: z.boolean().optional(),
// if access the app by favourite or quick
favourite: z.boolean().optional(),
quick: z.boolean().optional(),
// 软删除字段
deleteTime: z.date().nullish(),
/** @deprecated */
defaultPermission: z.number().optional(),
/** @deprecated */
inited: z.boolean().optional(),
/** @deprecated */
teamTags: z.array(z.string()).optional()
});
export type AppSchemaType = z.infer<typeof AppSchemaTypeSchema>;
export type AppListItemType = {
_id: string;
parentId: ParentIdType;
tmbId: string;
name: string;
avatar: string;
intro: string;
type: AppTypeEnum;
updateTime: Date;
pluginData?: AppSchemaType['pluginData'];
permission: AppPermission;
inheritPermission?: boolean;
private?: boolean;
sourceMember: SourceMemberType;
hasInteractiveNode?: boolean;
};
export type AppDetailType = AppSchemaType & {
permission: AppPermission;
};
export const AppDatasetSearchParamsTypeSchema = z.object({
searchMode: z.enum(DatasetSearchModeEnum),
limit: z.number().optional(), // limit max tokens
similarity: z.number().optional(),
embeddingWeight: z.number().optional(), // embedding weight, fullText weight = 1 - embeddingWeight
usingReRank: z.boolean().optional(),
rerankModel: z.string().optional(),
rerankWeight: z.number().optional(),
datasetSearchUsingExtensionQuery: z.boolean().optional(),
datasetSearchExtensionModel: z.string().optional(),
datasetSearchExtensionBg: z.string().optional(),
collectionFilterMatch: z.string().optional()
});
export type AppDatasetSearchParamsType = z.infer<typeof AppDatasetSearchParamsTypeSchema>;
export type SettingAIDataType = {
model: string;
temperature?: number;
maxToken?: number;
isResponseAnswerText?: boolean;
maxHistories?: number;
[NodeInputKeyEnum.aiChatVision]?: boolean; // Is open vision mode
[NodeInputKeyEnum.aiChatReasoning]?: boolean; // Is open reasoning mode
[NodeInputKeyEnum.aiChatTopP]?: number;
[NodeInputKeyEnum.aiChatStopSign]?: string;
[NodeInputKeyEnum.aiChatResponseFormat]?: string;
[NodeInputKeyEnum.aiChatJsonSchema]?: string;
};
export type AppTemplateSchemaType = {
templateId: string;
name: string;
intro: string;
avatar: string;
tags: string[];
type: string;
author?: string;
isActive?: boolean;
isPromoted?: boolean;
promoteTags?: UserTagsEnum[];
hideTags?: UserTagsEnum[];
recommendText?: string;
userGuide?: {
type: 'markdown' | 'link';
content?: string;
link?: string;
};
isQuickTemplate?: boolean;
order?: number;
// TODO: 对于chat agent,是另一个格式
workflow: WorkflowTemplateBasicType;
};
export type TemplateTypeSchemaType = {
typeName: string;
typeId: string;
typeOrder: number;
};
import z from 'zod';
/* app chat file select config type */
export const AppFileSelectConfigTypeSchema = z.object({
maxFiles: z.number().optional(),
canSelectFile: z.boolean().optional(),
customPdfParse: z.boolean().optional(),
canSelectImg: z.boolean().optional(),
canSelectVideo: z.boolean().optional(),
canSelectAudio: z.boolean().optional(),
canSelectCustomFileExtension: z.boolean().optional(),
customFileExtensionList: z.array(z.string()).optional()
});
export type AppFileSelectConfigType = z.infer<typeof AppFileSelectConfigTypeSchema>;
import type { AppChatConfigType, AppSimpleEditFormType } from '../app/type';
import { FlowNodeTypeEnum } from '../workflow/node/constant';
import { FlowNodeTemplateTypeEnum, NodeInputKeyEnum } from '../workflow/constants';
import type { FlowNodeInputItemType } from '../workflow/type/io.d';
import { getAppChatConfig } from '../workflow/utils';
import { type StoreNodeItemType } from '../workflow/type/node';
import type { AppFormEditFormType } from './formEdit/type';
import { DatasetSearchModeEnum } from '../dataset/constants';
import { type WorkflowTemplateBasicType } from '../workflow/type';
import { AppTypeEnum } from './constants';
import appErrList from '../../common/error/code/app';
import pluginErrList from '../../common/error/code/plugin';
export const getDefaultAppForm = (): AppSimpleEditFormType => {
export const getDefaultAppForm = (): AppFormEditFormType => {
return {
aiSettings: {
model: '',
systemPrompt: '',
temperature: 0,
isResponseAnswerText: true,
maxHistories: 6,
maxToken: 4000,
aiChatReasoning: true
maxHistories: 6
},
dataset: {
datasets: [],
......@@ -37,143 +28,7 @@ export const getDefaultAppForm = (): AppSimpleEditFormType => {
};
};
/* format app nodes to edit form */
export const appWorkflow2Form = ({
nodes,
chatConfig
}: {
nodes: StoreNodeItemType[];
chatConfig: AppChatConfigType;
}) => {
const defaultAppForm = getDefaultAppForm();
const findInputValueByKey = (inputs: FlowNodeInputItemType[], key: string) => {
return inputs.find((item) => item.key === key)?.value;
};
nodes.forEach((node) => {
if (
node.flowNodeType === FlowNodeTypeEnum.chatNode ||
node.flowNodeType === FlowNodeTypeEnum.agent
) {
defaultAppForm.aiSettings.model = findInputValueByKey(node.inputs, NodeInputKeyEnum.aiModel);
defaultAppForm.aiSettings.systemPrompt = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.aiSystemPrompt
);
defaultAppForm.aiSettings.temperature = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.aiChatTemperature
);
defaultAppForm.aiSettings.maxToken = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.aiChatMaxToken
);
defaultAppForm.aiSettings.maxHistories = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.history
);
defaultAppForm.aiSettings.aiChatReasoning = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.aiChatReasoning
);
defaultAppForm.aiSettings.aiChatTopP = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.aiChatTopP
);
defaultAppForm.aiSettings.aiChatStopSign = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.aiChatStopSign
);
defaultAppForm.aiSettings.aiChatResponseFormat = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.aiChatResponseFormat
);
defaultAppForm.aiSettings.aiChatJsonSchema = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.aiChatJsonSchema
);
} else if (node.flowNodeType === FlowNodeTypeEnum.datasetSearchNode) {
defaultAppForm.dataset.datasets = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.datasetSelectList
);
defaultAppForm.dataset.similarity = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.datasetSimilarity
);
defaultAppForm.dataset.limit = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.datasetMaxTokens
);
defaultAppForm.dataset.searchMode =
findInputValueByKey(node.inputs, NodeInputKeyEnum.datasetSearchMode) ||
DatasetSearchModeEnum.embedding;
defaultAppForm.dataset.embeddingWeight = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.datasetSearchEmbeddingWeight
);
// Rerank
defaultAppForm.dataset.usingReRank = !!findInputValueByKey(
node.inputs,
NodeInputKeyEnum.datasetSearchUsingReRank
);
defaultAppForm.dataset.rerankModel = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.datasetSearchRerankModel
);
defaultAppForm.dataset.rerankWeight = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.datasetSearchRerankWeight
);
// Query extension
defaultAppForm.dataset.datasetSearchUsingExtensionQuery = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.datasetSearchUsingExtensionQuery
);
defaultAppForm.dataset.datasetSearchExtensionModel = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.datasetSearchExtensionModel
);
defaultAppForm.dataset.datasetSearchExtensionBg = findInputValueByKey(
node.inputs,
NodeInputKeyEnum.datasetSearchExtensionBg
);
} else if (
node.flowNodeType === FlowNodeTypeEnum.pluginModule ||
node.flowNodeType === FlowNodeTypeEnum.appModule ||
node.flowNodeType === FlowNodeTypeEnum.tool ||
node.flowNodeType === FlowNodeTypeEnum.toolSet
) {
if (!node.pluginId) return;
defaultAppForm.selectedTools.push({
id: node.nodeId,
pluginId: node.pluginId,
name: node.name,
avatar: node.avatar,
intro: node.intro || '',
flowNodeType: node.flowNodeType,
showStatus: node.showStatus,
version: node.version,
inputs: node.inputs,
outputs: node.outputs,
templateType: FlowNodeTemplateTypeEnum.other,
pluginData: node.pluginData,
toolConfig: node.toolConfig
});
} else if (node.flowNodeType === FlowNodeTypeEnum.systemConfig) {
defaultAppForm.chatConfig = getAppChatConfig({
chatConfig,
systemConfigNode: node,
isPublicFetch: true
});
}
});
return defaultAppForm;
};
export const getAppType = (config?: WorkflowTemplateBasicType | AppSimpleEditFormType) => {
export const getAppType = (config?: WorkflowTemplateBasicType | AppFormEditFormType) => {
if (!config) return '';
if ('aiSettings' in config) {
......
import { TeamMemberStatusEnum } from 'support/user/team/constant';
import { StoreEdgeItemType } from '../workflow/type/edge';
import type { AppSchema } from './type';
import { AppChatConfigType } from './type';
import type { SourceMemberType } from 'support/user/type';
export type AppVersionSchemaType = {
_id: string;
appId: string;
time: Date;
nodes: AppSchema['modules'];
edges: AppSchema['edges'];
chatConfig: AppSchema['chatConfig'];
isPublish?: boolean;
isAutoSave?: boolean;
versionName: string;
tmbId: string;
};
export type VersionListItemType = {
_id: string;
appId: string;
versionName: string;
time: Date;
isPublish: boolean | undefined;
tmbId: string;
sourceMember: SourceMemberType;
};
import { AppSchemaTypeSchema } from '../type';
import { SourceMemberSchema } from '../../../support/user/type';
import z from 'zod';
import { ObjectIdSchema } from '../../../common/type/mongo';
export const AppVersionSchema = z.object({
_id: ObjectIdSchema,
tmbId: ObjectIdSchema,
appId: ObjectIdSchema,
time: z.date(),
nodes: AppSchemaTypeSchema.shape.modules,
edges: AppSchemaTypeSchema.shape.edges,
chatConfig: AppSchemaTypeSchema.shape.chatConfig,
isPublish: z.boolean().optional(),
isAutoSave: z.boolean().optional(),
versionName: z.string()
});
export type AppVersionSchemaType = z.infer<typeof AppVersionSchema>;
export const VersionListItemSchema = z.object({
_id: ObjectIdSchema,
appId: ObjectIdSchema,
versionName: z.string(),
time: z.date(),
isPublish: z.boolean().optional(),
tmbId: ObjectIdSchema,
sourceMember: SourceMemberSchema
});
export type VersionListItemType = z.infer<typeof VersionListItemSchema>;
......@@ -21,13 +21,6 @@ export enum ChatFileTypeEnum {
image = 'image',
file = 'file'
}
export enum ChatItemValueTypeEnum {
text = 'text',
file = 'file',
tool = 'tool',
interactive = 'interactive',
reasoning = 'reasoning'
}
export enum ChatSourceEnum {
test = 'test',
......
import { ChatCompletionRequestMessageRoleEnum } from '../../ai/constants';
import type {
ChatCompletionContentPart,
ChatCompletionMessageParam,
ChatCompletionMessageToolCall,
ChatCompletionToolMessageParam
} from '../../ai/type';
import { ChatFileTypeEnum, ChatRoleEnum } from '../constants';
import type { HelperBotChatItemType } from './type';
import { simpleUserContentPart } from '../adapt';
export const helperChats2GPTMessages = ({
messages
}: {
messages: HelperBotChatItemType[];
}): ChatCompletionMessageParam[] => {
let results: ChatCompletionMessageParam[] = [];
messages.forEach((item) => {
if (item.obj === ChatRoleEnum.System) {
const content = item.value?.[0]?.text?.content;
if (content) {
results.push({
role: ChatCompletionRequestMessageRoleEnum.System,
content
});
}
} else if (item.obj === ChatRoleEnum.Human) {
const value = item.value
.map((item) => {
if (item.text) {
return {
type: 'text',
text: item.text?.content || ''
};
}
if (item.file) {
if (item.file?.type === ChatFileTypeEnum.image) {
return {
type: 'image_url',
key: item.file.key,
image_url: {
url: item.file.url
}
};
} else if (item.file?.type === ChatFileTypeEnum.file) {
return {
type: 'file_url',
name: item.file?.name || '',
url: item.file.url,
key: item.file.key
};
}
}
})
.filter(Boolean) as ChatCompletionContentPart[];
results.push({
role: ChatCompletionRequestMessageRoleEnum.User,
content: simpleUserContentPart(value)
});
} else {
const aiResults: ChatCompletionMessageParam[] = [];
//AI: 只需要把根节点转化即可
item.value.forEach((value, i) => {
if ('collectionForm' in value) {
const text = JSON.stringify(
value.collectionForm.params.inputForm.map((item) => ({
label: item.label,
type: item.type
}))
);
// Concat text
const lastValue = item.value[i - 1];
const lastResult = aiResults[aiResults.length - 1];
if (lastValue && typeof lastResult?.content === 'string') {
lastResult.content += text;
} else {
aiResults.push({
role: ChatCompletionRequestMessageRoleEnum.Assistant,
content: text
});
}
} else if ('text' in value && typeof value.text?.content === 'string') {
if (!value.text.content && item.value.length > 1) {
return;
}
// Concat text
const lastValue = item.value[i - 1];
const lastResult = aiResults[aiResults.length - 1];
if (lastValue && typeof lastResult?.content === 'string') {
lastResult.content += value.text.content;
} else {
aiResults.push({
role: ChatCompletionRequestMessageRoleEnum.Assistant,
content: value.text.content
});
}
}
});
// Auto add empty assistant message
results = results.concat(
aiResults.length > 0
? aiResults
: [
{
role: ChatCompletionRequestMessageRoleEnum.Assistant,
content: ''
}
]
);
}
});
return results;
};
import { z } from 'zod';
// TopAgent 参数配置
export const topAgentParamsSchema = z.object({
role: z.string().nullish(),
taskObject: z.string().nullish(),
systemPrompt: z.string().nullish(),
selectedTools: z.array(z.string()).nullish(),
selectedDatasets: z.array(z.string()).nullish(),
fileUpload: z.boolean().nullish()
});
export type TopAgentParamsType = z.infer<typeof topAgentParamsSchema>;
import { ObjectIdSchema } from '../../../common/type/mongo';
import { z } from 'zod';
import { ChatRoleEnum } from '../constants';
import { UserChatItemSchema, SystemChatItemSchema, ToolModuleResponseItemSchema } from '../type';
import { UserInputInteractiveSchema } from '../../workflow/template/system/interactive/type';
export enum HelperBotTypeEnum {
topAgent = 'topAgent'
}
export const HelperBotTypeEnumSchema = z.enum(Object.values(HelperBotTypeEnum));
export type HelperBotTypeEnumType = z.infer<typeof HelperBotTypeEnumSchema>;
export const HelperBotChatSchema = z.object({
_id: ObjectIdSchema,
chatId: z.string(),
type: HelperBotTypeEnum,
userId: z.string(),
createTime: z.date(),
updateTime: z.date(),
metadata: z.record(z.string(), z.any()).optional()
});
export type HelperBotChatType = z.infer<typeof HelperBotChatSchema>;
// AI schema
export const AIChatItemValueItemSchema = z.union([
z.object({
text: z.object({
content: z.string()
})
}),
z.object({
reasoning: z.object({
content: z.string()
})
}),
z.object({
collectionForm: UserInputInteractiveSchema
}),
z.object({
planHint: z.object({
type: z.literal('generation')
})
})
]);
export type AIChatItemValueItemType = z.infer<typeof AIChatItemValueItemSchema>;
const AIChatItemSchema = z.object({
obj: z.literal(ChatRoleEnum.AI),
value: z.array(AIChatItemValueItemSchema)
});
export type AIChatItemType = z.infer<typeof AIChatItemSchema>;
const HelperBotChatRoleSchema = z.discriminatedUnion('obj', [
UserChatItemSchema,
SystemChatItemSchema,
AIChatItemSchema
]);
export const HelperBotChatItemSchema = z.intersection(
z.object({
_id: ObjectIdSchema,
userId: z.string(),
chatId: z.string(),
dataId: z.string(),
createTime: z.date(),
memories: z.record(z.string(), z.any()).nullish()
}),
HelperBotChatRoleSchema
);
export type HelperBotChatItemType = z.infer<typeof HelperBotChatItemSchema>;
/* 客户端 UI User Interface 展示的类型 */
export const HelperBotChatItemSiteSchema = z.intersection(
z.object({
_id: ObjectIdSchema,
dataId: z.string(),
createTime: z.date()
}),
HelperBotChatRoleSchema
);
export type HelperBotChatItemSiteType = z.infer<typeof HelperBotChatItemSiteSchema>;
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment