@baishuyun/chat-backend 0.0.15 → 0.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.env.example +4 -1
  2. package/CHANGELOG.md +17 -0
  3. package/config/default.ts +8 -0
  4. package/dist/config/default.js +20 -7
  5. package/dist/src/app/main.js +12 -3
  6. package/dist/src/config/hono.config.js +12 -0
  7. package/dist/src/controllers/common/connect.controll.js +20 -0
  8. package/dist/src/controllers/common/model.js +10 -0
  9. package/dist/src/controllers/form/build/build.controller.js +30 -7
  10. package/dist/src/controllers/form/build/model.js +5 -0
  11. package/dist/src/controllers/form/build/utils.js +30 -0
  12. package/dist/src/controllers/form/fill/createBatchFillingTransformStream.js +9 -0
  13. package/dist/src/controllers/form/fill/createFieldsFillingResultTransformStream.js +9 -0
  14. package/dist/src/controllers/form/fill/fill.controller.js +8 -4
  15. package/dist/src/controllers/form/fill/utils.js +30 -0
  16. package/dist/src/controllers/report/query/createQuerySuggestionTransStream.js +34 -0
  17. package/dist/src/controllers/report/query/createQueryTransformStream.js +96 -0
  18. package/dist/src/controllers/report/query/handler-helpers.js +31 -0
  19. package/dist/src/controllers/report/query/handler-registry.js +48 -0
  20. package/dist/src/controllers/report/query/model.js +24 -0
  21. package/dist/src/controllers/report/query/query.controller.js +42 -0
  22. package/dist/src/controllers/report/query/suggest.controller.js +39 -0
  23. package/dist/src/controllers/report/query/types.js +2 -0
  24. package/dist/src/controllers/report/query/utils.js +63 -0
  25. package/dist/src/routes/common/common.route.js +7 -0
  26. package/dist/src/routes/report/report.route.js +10 -0
  27. package/dist/src/utils/createJsonStreamTransformer.js +191 -0
  28. package/ecosystem.config.cjs +2 -2
  29. package/package.json +5 -4
  30. package/src/app/main.ts +2 -0
  31. package/src/config/hono.config.ts +14 -0
  32. package/src/controllers/common/connect.controll.ts +24 -0
  33. package/src/controllers/common/model.ts +12 -0
  34. package/src/controllers/form/build/build.controller.ts +23 -8
  35. package/src/controllers/form/build/model.ts +6 -0
  36. package/src/controllers/form/build/utils.ts +43 -0
  37. package/src/controllers/form/fill/utils.ts +1 -0
  38. package/src/controllers/report/query/createQueryTransformStream.ts +5 -4
  39. package/src/controllers/report/query/handler-registry.ts +5 -1
  40. package/src/controllers/report/query/query.controller.ts +1 -1
  41. package/src/routes/common/common.route.ts +10 -0
@@ -0,0 +1,42 @@
1
+ import {} from 'hono';
2
+ import { convertToModelMessages, streamText, generateId } from 'ai';
3
+ import { createReportQueryModel } from './model.js';
4
+ import { buildExtraMsgParts } from './utils.js';
5
+ export const queryReport = async (c) => {
6
+ let requestBody;
7
+ try {
8
+ const json = await c.req.json();
9
+ requestBody = json;
10
+ }
11
+ catch (_) {
12
+ return c.json({ error: 'Invalid JSON' }, 400);
13
+ }
14
+ const uid = c.req.header('X-User-Id') || '';
15
+ const messages = requestBody.messages;
16
+ const extraText = buildExtraMsgParts({
17
+ appId: requestBody.appId,
18
+ userId: uid,
19
+ textOnly: true,
20
+ });
21
+ const lastUserTextPartOfMessage = messages
22
+ .slice()
23
+ .reverse()
24
+ .find((msg) => msg.role === 'user')
25
+ ?.parts.findLast((part) => part.type === 'text');
26
+ if (lastUserTextPartOfMessage) {
27
+ lastUserTextPartOfMessage.text = `${extraText}${lastUserTextPartOfMessage.text}`;
28
+ }
29
+ const modelMessages = convertToModelMessages(messages);
30
+ console.log('Final messages for report query:', JSON.stringify(modelMessages, null, 2));
31
+ const stream = streamText({
32
+ model: createReportQueryModel(),
33
+ messages: modelMessages,
34
+ includeRawChunks: true,
35
+ headers: {
36
+ 'x-user-id': Date.now().toString(), // uid,
37
+ },
38
+ });
39
+ return stream.toUIMessageStreamResponse({
40
+ originalMessages: messages, // 建议添加,便于消息 ID 管理
41
+ });
42
+ };
@@ -0,0 +1,39 @@
1
+ import {} from 'hono';
2
+ import { convertToModelMessages, streamText, generateId } from 'ai';
3
+ import { createReportQueryModel } from './model.js';
4
+ export const queryReportSuggest = async (c) => {
5
+ let requestBody;
6
+ try {
7
+ const json = await c.req.json();
8
+ requestBody = json;
9
+ }
10
+ catch (_) {
11
+ return c.json({ error: 'Invalid JSON' }, 400);
12
+ }
13
+ const uid = c.req.header('X-User-Id') || '';
14
+ const messages = requestBody.messages;
15
+ const forms = requestBody.forms || [];
16
+ const modelMessages = convertToModelMessages([
17
+ {
18
+ role: 'user',
19
+ parts: [
20
+ {
21
+ type: 'text',
22
+ text: JSON.stringify(forms),
23
+ },
24
+ ],
25
+ },
26
+ ]);
27
+ console.log('Final messages for query suggestion: ', JSON.stringify(modelMessages, null, 2));
28
+ const stream = streamText({
29
+ model: createReportQueryModel(),
30
+ messages: modelMessages,
31
+ includeRawChunks: true,
32
+ headers: {
33
+ 'x-user-id': uid,
34
+ },
35
+ });
36
+ return stream.toUIMessageStreamResponse({
37
+ originalMessages: messages, // 建议添加,便于消息 ID 管理
38
+ });
39
+ };
@@ -0,0 +1,2 @@
1
+ import {} from '@baishuyun/types';
2
+ import {} from '../../../utils/createJsonStreamTransformer.js';
@@ -0,0 +1,63 @@
1
+ export const buildExtraMsgParts = ({ appId, userId, textOnly, }) => {
2
+ if (textOnly) {
3
+ return `appID为${appId};用户ID为${userId};`;
4
+ }
5
+ return [
6
+ {
7
+ type: 'text',
8
+ text: `appID为${appId};`,
9
+ },
10
+ {
11
+ type: 'text',
12
+ text: `用户ID为${userId};`,
13
+ },
14
+ ];
15
+ };
16
+ export const queryChunkGuard = (chunk) => {
17
+ if (chunk.type !== 'text-delta' || !('delta' in chunk)) {
18
+ return false;
19
+ }
20
+ return true;
21
+ };
22
+ /**
23
+ * 通用路径匹配器:判断当前解析到的元素是否命中指定的 JSONParser 路径。
24
+ *
25
+ * 支持两种路径形式:
26
+ * - 精确路径:`$.title`、`$.filter.rel` — 匹配特定 key
27
+ * - 通配路径:`$.fields.*`、`$.filter.cond.*` — 匹配数组元素
28
+ *
29
+ * path 格式与 `JSONParser` 的 `paths` 配置完全一致,无需额外转换。
30
+ *
31
+ * @example
32
+ * isTargetElement('$.title', parsedInfo)
33
+ * isTargetElement('$.filter.rel', parsedInfo)
34
+ * isTargetElement('$.fields.*', parsedInfo)
35
+ * isTargetElement('$.filter.cond.*', parsedInfo)
36
+ */
37
+ export const isTargetElement = (path, parsedInfo) => {
38
+ const { key, stack, parent } = parsedInfo;
39
+ // 去掉 '$.' 前缀,按 '.' 分割
40
+ const segments = path.replace(/^\$\./, '').split('.');
41
+ const endsWithWildcard = segments[segments.length - 1] === '*';
42
+ if (endsWithWildcard) {
43
+ // ---- 通配路径:匹配数组中的元素 ----
44
+ const parentKeys = segments.slice(0, -1);
45
+ // 当前 key 必须为数组索引,parent 必须为数组
46
+ if (typeof key !== 'number' || !Array.isArray(parent))
47
+ return false;
48
+ // stack 深度 = root(1) + parentKeys
49
+ if (stack.length !== parentKeys.length + 1)
50
+ return false;
51
+ // 从 stack[1] 开始逐段匹配(跳过 root)
52
+ return parentKeys.every((seg, i) => stack[i + 1]?.key === seg);
53
+ }
54
+ // ---- 精确路径:匹配特定 key ----
55
+ const leafKey = segments[segments.length - 1];
56
+ if (key !== leafKey)
57
+ return false;
58
+ const parentKeys = segments.slice(0, -1);
59
+ // stack 深度 = root(1) + parentKeys(叶子节点自身不在 stack 中)
60
+ if (stack.length !== parentKeys.length + 1)
61
+ return false;
62
+ return parentKeys.every((seg, i) => stack[i + 1]?.key === seg);
63
+ };
@@ -0,0 +1,7 @@
1
+ import { Hono } from 'hono';
2
+ import { connectToAgent } from '../../controllers/common/connect.controll.js';
3
+ export const createCommonRouter = () => {
4
+ const commonRouter = new Hono();
5
+ commonRouter.post('/connect', connectToAgent);
6
+ return commonRouter;
7
+ };
@@ -0,0 +1,10 @@
1
+ import { Hono } from 'hono';
2
+ import { queryReport } from '../../controllers/report/query/query.controller.js';
3
+ import { queryReportSuggest } from '../../controllers/report/query/suggest.controller.js';
4
+ export const createReportRouter = () => {
5
+ const reportRouter = new Hono();
6
+ // 智能问数
7
+ reportRouter.post('/query', queryReport);
8
+ reportRouter.post('/query/suggest', queryReportSuggest);
9
+ return reportRouter;
10
+ };
@@ -0,0 +1,191 @@
1
+ import {} from '@ai-sdk/provider';
2
+ import { createTextInfoEnqueuer } from '@baishuyun/coze-provider';
3
+ import { JSONParser } from '@streamparser/json';
4
+ import { logger } from '../logger/index.js';
5
+ /**
6
+ * 创建一个 TransformStream,将 AI 流式响应中的 JSON 片段解析为结构化数据。
7
+ *
8
+ * 使用者只需关心:
9
+ * 1. `createJSONParser` — 决定 JSON 解析的路径 / 选项
10
+ * 2. `onParseValue` — 处理每个解析出的值
11
+ * 3. 错误处理(均可选)
12
+ */
13
+ export const createJsonStreamTransformer = (options) => {
14
+ const processor = new JsonStreamProcessor(options);
15
+ return new TransformStream({
16
+ start: (ctrl) => processor.start(ctrl),
17
+ transform: (chunk, ctrl) => processor.transform(chunk, ctrl),
18
+ flush: (ctrl) => processor.flush(ctrl),
19
+ });
20
+ };
21
+ const BACKTICK_RE = /`?`?`?/g;
22
+ const JSON_PREFIX = 'json';
23
+ const ERROR_MESSAGES = {
24
+ PARSE_ERROR: '解析异常,请刷新重试',
25
+ TIMEOUT: '操作超时,请刷新重试',
26
+ GENERAL_ERROR: '发生错误,请刷新重试',
27
+ };
28
+ class JsonStreamProcessor {
29
+ // -- 配置 --
30
+ options;
31
+ // -- 运行时状态 --
32
+ parser = null;
33
+ result = {};
34
+ currentChunkId = '';
35
+ parseCompleted = null;
36
+ resolveParseCompleted = null;
37
+ terminated = false;
38
+ constructor(options) {
39
+ this.options = options;
40
+ }
41
+ // ===================== 生命周期 =====================
42
+ /** TransformStream start:创建 parser、绑定回调 */
43
+ start(controller) {
44
+ this.parser = this.options.createJSONParser();
45
+ this.parseCompleted = this.createCompletionPromise();
46
+ this.bindParserCallbacks(controller);
47
+ }
48
+ /** TransformStream transform:逐 chunk 处理 */
49
+ transform(chunk, controller) {
50
+ if (this.terminated || !this.parser) {
51
+ logger.warn('JSON parser not initialized or stream already terminated');
52
+ return;
53
+ }
54
+ try {
55
+ // 1) error chunk → 通知下游后终止
56
+ if (chunk.type === 'error') {
57
+ this.options.onErrorChunk?.(chunk);
58
+ this.enqueueError(controller, ERROR_MESSAGES.GENERAL_ERROR);
59
+ return;
60
+ }
61
+ // 2) 不需要解析的 chunk → 透传
62
+ const guard = this.options.chunkGuard ?? defaultChunkGuard;
63
+ if (!guard(chunk)) {
64
+ controller.enqueue(chunk);
65
+ return;
66
+ }
67
+ // 3) 提取 delta 写入 parser
68
+ if (isChunkWithDelta(chunk)) {
69
+ this.currentChunkId = chunk.id;
70
+ this.parser.write(stripCodeFence(chunk.delta));
71
+ }
72
+ }
73
+ catch (error) {
74
+ this.enqueueError(controller, error);
75
+ }
76
+ }
77
+ /** TransformStream flush:结束 parser 并等待所有回调完成 */
78
+ async flush(controller) {
79
+ try {
80
+ if (this.parser) {
81
+ this.parser.end();
82
+ if (this.parseCompleted)
83
+ await this.parseCompleted;
84
+ logger.debug('Parser stopped gracefully');
85
+ }
86
+ if (!this.terminated)
87
+ controller.terminate();
88
+ }
89
+ catch (error) {
90
+ controller.error(`Cleanup error: ${error}`);
91
+ }
92
+ }
93
+ // ===================== Parser 回调 =====================
94
+ bindParserCallbacks(controller) {
95
+ if (!this.parser)
96
+ return;
97
+ const enqueue = createTextInfoEnqueuer(controller);
98
+ this.parser.onValue = (parsedInfo) => {
99
+ // 超时错误特殊处理
100
+ if (isTimeoutError(parsedInfo.value)) {
101
+ if (!this.terminated) {
102
+ enqueue(JSON.stringify(parsedInfo.value), {
103
+ type: 'agent-error',
104
+ error: ERROR_MESSAGES.TIMEOUT,
105
+ });
106
+ this.terminateStream(controller);
107
+ }
108
+ return;
109
+ }
110
+ this.options.onParseValue({
111
+ parsedInfo,
112
+ deltaChunkEnqueuer: enqueue,
113
+ currentChunkId: this.currentChunkId,
114
+ ctrl: controller,
115
+ getResult: () => this.result,
116
+ clearResult: this.clearResult.bind(this),
117
+ setPartialResult: (partial) => {
118
+ this.result = { ...this.result, ...partial };
119
+ },
120
+ });
121
+ };
122
+ this.parser.onError = (err) => {
123
+ if (!this.terminated) {
124
+ const msg = this.options.onParseError
125
+ ? this.options.onParseError(err)
126
+ : ERROR_MESSAGES.GENERAL_ERROR;
127
+ logger.debug(msg);
128
+ enqueue('error', { type: 'agent-error', error: msg });
129
+ this.terminateStream(controller);
130
+ }
131
+ };
132
+ this.parser.onEnd = () => {
133
+ logger.debug('Parsing completed');
134
+ enqueue(' ', JSON.stringify({ appendConfirm: 'save-fields' }));
135
+ this.completeParsing();
136
+ };
137
+ }
138
+ /** 创建可外部 resolve 的 Promise,用于 flush 等待 parser 回调结束 */
139
+ createCompletionPromise() {
140
+ return new Promise((resolve) => {
141
+ this.resolveParseCompleted = () => {
142
+ resolve();
143
+ logger.debug('Parsing completion promise resolved');
144
+ };
145
+ });
146
+ }
147
+ clearResult() {
148
+ this.result = {};
149
+ }
150
+ /** 标记解析完成,重置状态 */
151
+ completeParsing() {
152
+ this.resolveParseCompleted?.();
153
+ this.parser = null;
154
+ this.result = {};
155
+ this.currentChunkId = '';
156
+ this.parseCompleted = null;
157
+ this.resolveParseCompleted = null;
158
+ }
159
+ /** 安全地终止流并清理状态 */
160
+ terminateStream(controller) {
161
+ this.completeParsing();
162
+ this.terminated = true;
163
+ controller.terminate();
164
+ }
165
+ /** 向下游推送 agent-error 并终止流 */
166
+ enqueueError(controller, error) {
167
+ if (this.terminated)
168
+ return;
169
+ const enqueue = createTextInfoEnqueuer(controller);
170
+ const msg = typeof error === 'string' ? error : ERROR_MESSAGES.PARSE_ERROR;
171
+ logger.error('JsonStreamProcessor error: ' + error);
172
+ // 先 enqueue 错误信息让下游能收到,再 terminate
173
+ // 注意:不能调 controller.error(),否则流进入 errored 状态,enqueue 不再生效
174
+ enqueue('error', { type: 'agent-error', error: msg });
175
+ this.terminateStream(controller);
176
+ }
177
+ }
178
+ /** 默认 chunkGuard:只处理带 delta 的 text-delta chunk */
179
+ function defaultChunkGuard(chunk) {
180
+ return chunk.type === 'text-delta' && 'delta' in chunk;
181
+ }
182
+ function isChunkWithDelta(chunk) {
183
+ return 'id' in chunk && 'delta' in chunk;
184
+ }
185
+ /** 去掉 AI 返回的代码围栏标记 (```) 和 json 前缀 */
186
+ function stripCodeFence(delta) {
187
+ return delta.replace(BACKTICK_RE, '').replace(JSON_PREFIX, '');
188
+ }
189
+ function isTimeoutError(value) {
190
+ return value?.error === true && value?.errorMessage === 'timeout';
191
+ }
@@ -8,8 +8,8 @@ module.exports = {
8
8
  watch: false, // 生产环境关闭文件监听(避免容器内文件变动触发重启)
9
9
  max_memory_restart: '2G', // 内存超过 1G 自动重启(防止内存泄漏)
10
10
 
11
- listen_timeout: 10000,
12
- kill_timeout: 5000,
11
+ listen_timeout: 120000, // 2 minutes for long streaming operations
12
+ kill_timeout: 30000, // 30 seconds for graceful shutdown
13
13
 
14
14
  env: {
15
15
  // 开发环境变量
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baishuyun/chat-backend",
3
- "version": "0.0.15",
3
+ "version": "0.0.17",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -22,8 +22,9 @@
22
22
  "parse-sse": "^0.1.0",
23
23
  "pino": "^10.1.0",
24
24
  "zod": "^4.1.13",
25
- "@baishuyun/coze-provider": "0.0.15",
26
- "@baishuyun/types": "1.0.15"
25
+ "@baishuyun/coze-provider": "0.0.17",
26
+ "@baishuyun/agents": "0.0.17",
27
+ "@baishuyun/types": "1.0.17"
27
28
  },
28
29
  "devDependencies": {
29
30
  "@types/config": "^3.3.5",
@@ -34,7 +35,7 @@
34
35
  "pm2": "^6.0.14",
35
36
  "tsx": "^4.7.1",
36
37
  "typescript": "^5.8.3",
37
- "@baishuyun/typescript-config": "0.0.15"
38
+ "@baishuyun/typescript-config": "0.0.17"
38
39
  },
39
40
  "scripts": {
40
41
  "dev": "cross-env NODE_ENV=development tsx watch src/index.ts",
package/src/app/main.ts CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  // 应用实例
6
6
  import app from '../config/hono.config.js';
7
+ import { createCommonRouter } from '../routes/common/common.route.js';
7
8
 
8
9
  // 子路由
9
10
  import { createFormRouter } from '../routes/form/form.route.js';
@@ -12,6 +13,7 @@ import { createReportRouter } from '../routes/report/report.route.js';
12
13
  // 挂载子路由
13
14
  app.route('web/api/form', createFormRouter());
14
15
  app.route('web/api/report', createReportRouter());
16
+ app.route('web/api/common', createCommonRouter());
15
17
 
16
18
  // 基础健康检查
17
19
  app.get('/web/api/health', (c) => {
@@ -16,6 +16,20 @@ app.use('web/api/*', cors());
16
16
  // Logging middleware
17
17
  app.use(logMiddleware);
18
18
 
19
+ // SSE keep-alive middleware - adds headers to prevent proxy timeouts during streaming
20
+ app.use('web/api/*', async (c, next) => {
21
+ await next();
22
+
23
+ // Add keep-alive headers to streaming responses (SSE/text-streaming)
24
+ const contentType = c.res.headers.get('content-type');
25
+ if (contentType?.includes('text/plain') || contentType?.includes('text/event-stream')) {
26
+ c.header('Connection', 'keep-alive');
27
+ c.header('Keep-Alive', 'timeout=300'); // 5 minutes
28
+ c.header('X-Accel-Buffering', 'no'); // Disable nginx buffering
29
+ c.header('Cache-Control', 'no-cache, no-transform');
30
+ }
31
+ });
32
+
19
33
  // 全局错误处理中间件(捕获所有路由/中间件异常)
20
34
  app.onError((err, c) => {
21
35
  // 记录错误日志(error 级别,包含异常堆栈)
@@ -0,0 +1,24 @@
1
+ import { convertToModelMessages, streamText } from 'ai';
2
+ import type { Context } from 'hono';
3
+ import { createBaseModel } from './model.js';
4
+
5
+ export const connectToAgent = async (c: Context) => {
6
+ let requestBody;
7
+ try {
8
+ const json = await c.req.json();
9
+ requestBody = json;
10
+ } catch (_) {
11
+ return c.json({ error: 'Invalid JSON' }, 400);
12
+ }
13
+
14
+ const botId = requestBody.botId;
15
+ const messages = requestBody.messages;
16
+
17
+ const stream = streamText({
18
+ model: createBaseModel(botId),
19
+ messages: convertToModelMessages(messages),
20
+ includeRawChunks: true,
21
+ });
22
+
23
+ return stream.toUIMessageStreamResponse();
24
+ };
@@ -0,0 +1,12 @@
1
+ import { createCoze } from '@baishuyun/coze-provider';
2
+ import config from 'config';
3
+
4
+ export const createBaseModel = (botId: string) => {
5
+ const coze = createCoze({
6
+ apiKey: config.get<string>('agent.common.apiKey'),
7
+ baseURL: config.get<string>('agent.common.baseUrl'),
8
+ botId: botId,
9
+ });
10
+
11
+ return coze.chat('chat');
12
+ };
@@ -1,10 +1,13 @@
1
- import { convertToModelMessages, streamText } from "ai";
1
+ import { convertToModelMessages, streamText, generateText, type TextUIPart } from "ai";
2
2
  import { type Context } from "hono";
3
3
  import { createModel } from "./model.js";
4
4
  import {
5
5
  createFieldsJsonTransformStream,
6
6
  SuggestionTransformStream,
7
7
  } from "@baishuyun/coze-provider";
8
+ import { logger } from "../../../logger/index.js";
9
+ import config from 'config';
10
+ import { determineUserIntentByInput } from "./utils.js";
8
11
 
9
12
  /**
10
13
  * 搭建表单
@@ -21,11 +24,19 @@ export const buildForm = async (c: Context) => {
21
24
  return c.json({ error: "Invalid JSON" }, 400);
22
25
  }
23
26
 
24
- const isBuildStage = requestBody.stage === "build";
25
- const formName = requestBody.name || "未命名表单";
27
+ const intent = await determineUserIntentByInput(requestBody.text, requestBody.stage);
28
+
29
+ const isBuildStage = intent === "build";
30
+ const formName = requestBody.name;
31
+ const model = createModel([
32
+ () => createFieldsJsonTransformStream(isBuildStage),
33
+ () => new SuggestionTransformStream(isBuildStage),
34
+ ]);
35
+
36
+ logger.debug("intent: " + intent);
26
37
 
27
38
  const allMessages = [...requestBody.messages];
28
- if (isBuildStage) {
39
+ if (isBuildStage && formName) {
29
40
  allMessages.push({
30
41
  role: "user",
31
42
  parts: [
@@ -37,11 +48,15 @@ export const buildForm = async (c: Context) => {
37
48
  });
38
49
  }
39
50
 
51
+ // clear empty text parts to avoid unnecessary streaming
52
+ allMessages.forEach((message) => {
53
+ message.parts = message.parts.filter(
54
+ (part: TextUIPart) => part.type === "text" && part.text.trim() !== ""
55
+ );
56
+ });
57
+
40
58
  const stream = streamText({
41
- model: createModel([
42
- () => createFieldsJsonTransformStream(isBuildStage),
43
- () => new SuggestionTransformStream(isBuildStage),
44
- ]),
59
+ model,
45
60
  messages: convertToModelMessages(allMessages),
46
61
  includeRawChunks: true,
47
62
  headers: {
@@ -1,4 +1,5 @@
1
1
  import type { LanguageModelV2StreamPart } from "@ai-sdk/provider";
2
+ import { createFormBuildIntentAgent } from "@baishuyun/agents";
2
3
  import { createCoze } from "@baishuyun/coze-provider";
3
4
  import config from "config";
4
5
 
@@ -14,3 +15,8 @@ export const createModel = (
14
15
 
15
16
  return coze.chat("chat");
16
17
  };
18
+
19
+ export const createUserIntentAgent = () => {
20
+ const dsApiKey = config.get<string>("agent.deepseekApiKey");
21
+ return createFormBuildIntentAgent(dsApiKey);
22
+ }
@@ -0,0 +1,43 @@
1
+ import { createUserIntentAgent } from "./model.js"
2
+
3
+ export const determineUserIntentByInput = async (input: string, userOriginIntent: "build" | "design" | null): Promise<"build" | "design" | null> => {
4
+ if (userOriginIntent === "design") {
5
+ return "design";
6
+ }
7
+
8
+ if (!input || input.trim() === "") {
9
+ return userOriginIntent;
10
+ }
11
+
12
+ const agent = createUserIntentAgent();
13
+
14
+ const intent = await agent.generate({
15
+ messages: [{
16
+ role: "user",
17
+ content: [{
18
+ type: "text",
19
+ text: input,
20
+ }]
21
+ }]
22
+ })
23
+
24
+ const result = intent.response.messages;
25
+ if (!result || result.length === 0) {
26
+ return userOriginIntent;
27
+ }
28
+
29
+ const lastMessage = result[result.length - 1];
30
+
31
+ if (!lastMessage.content || lastMessage.content.length === 0) {
32
+ return userOriginIntent;
33
+ }
34
+
35
+ const lastContent = lastMessage.content[0] as {
36
+ type: "text";
37
+ text: string;
38
+ };
39
+
40
+ const intentText = lastContent.text === "build" ? "build" : lastContent.text === "design" ? "design" : userOriginIntent;
41
+
42
+ return intentText;
43
+ }
@@ -166,6 +166,7 @@ export function trimFormStructure(fields: OriginalField[]): TrimmedField[] {
166
166
  widget: {
167
167
  type: item.widget.type,
168
168
  widgetName: item.widget.widgetName,
169
+ noRepeat: item.widget.noRepeat, // 保留 noRepeat 属性
169
170
  },
170
171
  }));
171
172
  }
@@ -32,6 +32,7 @@ function createJSONParser(): JSONParser {
32
32
  paths: [
33
33
  '$', // 保留完整结果推送
34
34
  '$.title',
35
+ '$.source',
35
36
  '$.name',
36
37
  '$.type',
37
38
  '$.userID',
@@ -55,14 +56,13 @@ function handleParsedValue(ctx: IParserCtx<IQueryResult>): void {
55
56
 
56
57
  logger.debug('Parsed JSON value: ' + JSON.stringify(value));
57
58
 
58
- // TODO: 使用约定的字段判断类型
59
- // Phase 1: aggregate 类型 —— name 字段触发,独立处理后直接返回
59
+ // aggregate 类型 —— name 字段触发,独立处理后直接返回
60
60
  if (isTargetElement('$.name', parsedInfo)) {
61
61
  handleAggregateName(ctx);
62
62
  return;
63
63
  }
64
64
 
65
- // Phase 2: 报表标题 —— 初始化结果并发送 text-start
65
+ // Phase 0: 报表标题 —— 初始化结果并发送 text-start, 必须为起始字段
66
66
  if (isTargetElement('$.title', parsedInfo)) {
67
67
  handleTitle(ctx);
68
68
  }
@@ -95,8 +95,9 @@ function handleAggregateName(ctx: IParserCtx<IQueryResult>): void {
95
95
 
96
96
  ctx.setPartialResult({
97
97
  title: value as string,
98
- isAggregate: true,
98
+ source: 'aggregate',
99
99
  type: 'data_table',
100
+ isAggregate: true,
100
101
  });
101
102
 
102
103
  logger.debug('Parsed aggregate table title: ' + value);
@@ -1,8 +1,12 @@
1
- import { type IDashWidgetType, type IQueryFilter } from '@baishuyun/types';
1
+ import { type IDashWidgetType, type IQueryFilter, type QuerySourceType } from '@baishuyun/types';
2
2
  import type { PathHandler } from './types.js';
3
3
  import { ensureFilter, pushToArray, pushToArrayWithMeta } from './handler-helpers.js';
4
4
 
5
5
  export const fieldHandlers: PathHandler[] = [
6
+ {
7
+ path: '$.source',
8
+ handler: (ctx, value) => ctx.setPartialResult({ source: value as QuerySourceType }),
9
+ },
6
10
  {
7
11
  path: '$.userID',
8
12
  handler: (ctx, value) => ctx.setPartialResult({ userID: value as number }),
@@ -40,7 +40,7 @@ export const queryReport = async (c: Context) => {
40
40
  messages: modelMessages,
41
41
  includeRawChunks: true,
42
42
  headers: {
43
- 'x-user-id': uid,
43
+ 'x-user-id': Date.now().toString(), // uid,
44
44
  },
45
45
  });
46
46