@reglow/reglow 0.14.2 → 0.15.0

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/dist/reglow/core/config.js +1 -1
  2. package/dist/reglow/core/entities.d.ts +29 -0
  3. package/dist/reglow/core/models.d.ts +4 -0
  4. package/dist/reglow/core/models.js +2 -0
  5. package/dist/reglow/core/models.js.map +1 -1
  6. package/dist/reglow/modules/ai/controller.js +250 -62
  7. package/dist/reglow/modules/ai/controller.js.map +1 -1
  8. package/dist/reglow/modules/ai/providers/deepseek_responses.d.ts +54 -0
  9. package/dist/reglow/modules/ai/providers/deepseek_responses.js +306 -0
  10. package/dist/reglow/modules/ai/providers/deepseek_responses.js.map +1 -0
  11. package/dist/reglow/modules/ai/providers/utils.d.ts +17 -0
  12. package/dist/reglow/modules/ai/providers/utils.js +103 -0
  13. package/dist/reglow/modules/ai/providers/utils.js.map +1 -0
  14. package/dist/reglow/modules/studio/controller.js +78 -1
  15. package/dist/reglow/modules/studio/controller.js.map +1 -1
  16. package/dist/reglow/modules/studio/engine.d.ts +6 -0
  17. package/dist/reglow/modules/studio/engine.js +44 -6
  18. package/dist/reglow/modules/studio/engine.js.map +1 -1
  19. package/dist/reglow/modules/studio/model.d.ts +2 -0
  20. package/dist/reglow/modules/studio/model.js +2 -0
  21. package/dist/reglow/modules/studio/model.js.map +1 -1
  22. package/dist/reglow/modules/studio/repository.d.ts +13 -1
  23. package/dist/reglow/modules/studio/repository.js +118 -2
  24. package/dist/reglow/modules/studio/repository.js.map +1 -1
  25. package/dist/reglow/modules/studio/scheduler.d.ts +53 -0
  26. package/dist/reglow/modules/studio/scheduler.js +277 -0
  27. package/dist/reglow/modules/studio/scheduler.js.map +1 -0
  28. package/dist/reglow/modules/studio/schema.d.ts +20 -0
  29. package/dist/reglow/modules/studio/schema.js +19 -0
  30. package/dist/reglow/modules/studio/schema.js.map +1 -1
  31. package/dist/reglow/modules/studio/service.d.ts +47 -0
  32. package/dist/reglow/modules/studio/service.js +109 -7
  33. package/dist/reglow/modules/studio/service.js.map +1 -1
  34. package/dist/reglow/modules/studio/tools/media_tools.d.ts +5 -3
  35. package/dist/reglow/modules/studio/tools/media_tools.js +27 -11
  36. package/dist/reglow/modules/studio/tools/media_tools.js.map +1 -1
  37. package/dist/reglow/scripts/init-data.js +12 -0
  38. package/dist/reglow/scripts/init-data.js.map +1 -1
  39. package/dist/reglow/scripts/schema.js +57 -0
  40. package/dist/reglow/scripts/schema.js.map +1 -1
  41. package/package.json +1 -1
@@ -31,7 +31,7 @@ const JWT_SECRET = str(env.JWT_SECRET, "change-me-in-production");
31
31
  const settings = {
32
32
  // Application
33
33
  APP_NAME: str(env.APP_NAME, "ReglowAdmin"),
34
- APP_VERSION: str(env.APP_VERSION, "0.14.2"),
34
+ APP_VERSION: str(env.APP_VERSION, "0.15.0"),
35
35
  APP_ENV: str(env.APP_ENV, "dev"),
36
36
  DEBUG: bool(env.DEBUG, false),
37
37
  PORT: int(env.PORT, 9520),
@@ -608,6 +608,35 @@ export interface StudioRun extends TimestampFields {
608
608
  source?: string | null;
609
609
  created_by?: number | null;
610
610
  auto?: boolean | number;
611
+ tenant_id?: number | null;
612
+ trigger?: string | null;
613
+ trigger_meta?: unknown;
614
+ run_at?: AnyDate | null;
615
+ }
616
+ export interface StudioTrigger extends TimestampFields {
617
+ id: number;
618
+ name: string;
619
+ source_type: string;
620
+ mode?: string | null;
621
+ workflow_id?: number | null;
622
+ intent?: string | null;
623
+ config?: unknown;
624
+ enabled?: number;
625
+ tenant_id?: number | null;
626
+ last_fired_at?: AnyDate | null;
627
+ fire_count?: number;
628
+ created_by?: number | null;
629
+ }
630
+ export interface StudioTriggerLog extends TimestampFields {
631
+ id: number;
632
+ trigger_id?: number | null;
633
+ source_type?: string | null;
634
+ run_id?: number | null;
635
+ payload?: unknown;
636
+ status?: string | null;
637
+ error?: string | null;
638
+ tenant_id?: number | null;
639
+ created_by?: number | null;
611
640
  }
612
641
  export interface StudioAsset extends TimestampFields {
613
642
  id: number;
@@ -72,6 +72,8 @@ export declare const TableNames: {
72
72
  readonly StudioJob: "studio_job";
73
73
  readonly StudioMcpServer: "studio_mcp_server";
74
74
  readonly StudioMcpTool: "studio_mcp_tool";
75
+ readonly StudioTrigger: "studio_trigger";
76
+ readonly StudioTriggerLog: "studio_trigger_log";
75
77
  };
76
78
  export type TableName = (typeof TableNames)[keyof typeof TableNames];
77
79
  export declare const ModelRegistry: {
@@ -145,4 +147,6 @@ export declare const ModelRegistry: {
145
147
  StudioJob: "studio_job";
146
148
  StudioMcpServer: "studio_mcp_server";
147
149
  StudioMcpTool: "studio_mcp_tool";
150
+ StudioTrigger: "studio_trigger";
151
+ StudioTriggerLog: "studio_trigger_log";
148
152
  };
@@ -77,6 +77,8 @@ export const TableNames = {
77
77
  StudioJob: "studio_job",
78
78
  StudioMcpServer: "studio_mcp_server",
79
79
  StudioMcpTool: "studio_mcp_tool",
80
+ StudioTrigger: "studio_trigger",
81
+ StudioTriggerLog: "studio_trigger_log",
80
82
  };
81
83
  export const ModelRegistry = {
82
84
  ...TableNames,
@@ -1 +1 @@
1
- {"version":3,"file":"models.js","sourceRoot":"","sources":["../../../reglow/core/models.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,QAAQ,EAAE,cAAc;IACxB,YAAY,EAAE,mBAAmB;IACjC,YAAY,EAAE,mBAAmB;IACjC,IAAI,EAAE,UAAU;IAChB,QAAQ,EAAE,eAAe;IACzB,QAAQ,EAAE,eAAe;IACzB,IAAI,EAAE,UAAU;IAChB,IAAI,EAAE,UAAU;IAChB,IAAI,EAAE,UAAU;IAEhB,SAAS,EAAE,YAAY;IACvB,UAAU,EAAE,aAAa;IACzB,YAAY,EAAE,mBAAmB;IACjC,QAAQ,EAAE,eAAe;IAEzB,IAAI,EAAE,UAAU;IAChB,SAAS,EAAE,gBAAgB;IAC3B,aAAa,EAAE,o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oB;CAC9B,CAAC;AAIX,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,GAAG,UAAU;IACb,GAAG,CAAC,IAA6B;QAC/B,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;CACF,CAAC"}
@@ -13,6 +13,7 @@ import settings from "../../core/config.js";
13
13
  import { ChatRequestSchema, SaveProviderSchema, DeleteProviderSchema, VideoGenerateSchema, ImageGenerateSchema, } from "./schema.js";
14
14
  import { queryImageTask } from "./service.js";
15
15
  import { recordUsage } from "../ai_usage/recorder.js";
16
+ import { buildResponsesPayload, buildSearchContext, buildFetchContext, extractSearchQuery, extractUrl, fetchWeb, parseResponsesOutput, parseResponsesUsage, searchWeb, shouldUseResponses, translateStream, } from "./providers/deepseek_responses.js";
16
17
  const SS = ModelRegistry.get("SysSetting");
17
18
  // ===================== 默认配置 =====================
18
19
  const DEEPSEEK_DEFAULT_MODELS = [
@@ -30,14 +31,14 @@ export const DEFAULT_PROVIDERS = {
30
31
  {
31
32
  name: "DeepSeek V4 Flash",
32
33
  model_id: "deepseek-v4-flash",
33
- type: "t2t",
34
- desc: "新一代快速模型,响应速度极快,适合日常对话和内容生成",
34
+ type: "all",
35
+ desc: "新一代快速模型,支持图片理解,响应速度极快,适合日常对话和内容生成",
35
36
  },
36
37
  {
37
38
  name: "DeepSeek V4 Pro",
38
39
  model_id: "deepseek-v4-pro",
39
- type: "t2t",
40
- desc: "旗舰级深度推理模型,支持长上下文与复杂逻辑推理",
40
+ type: "all",
41
+ desc: "旗舰级深度推理模型,支持图片理解、联网搜索、长上下文与复杂逻辑推理",
41
42
  },
42
43
  ],
43
44
  },
@@ -49,20 +50,20 @@ export const DEFAULT_PROVIDERS = {
49
50
  {
50
51
  name: "通义千问 Max",
51
52
  model_id: "qwen-max",
52
- type: "t2t",
53
- desc: "通义千问旗舰模型,适合复杂任务",
53
+ type: "all",
54
+ desc: "通义千问旗舰模型,支持图片理解,适合复杂任务",
54
55
  },
55
56
  {
56
57
  name: "通义千问 Plus",
57
58
  model_id: "qwen-plus",
58
- type: "t2t",
59
- desc: "通义千问增强模型,均衡性能与速度",
59
+ type: "all",
60
+ desc: "通义千问增强模型,支持图片理解,均衡性能与速度",
60
61
  },
61
62
  {
62
63
  name: "通义千问 Turbo",
63
64
  model_id: "qwen-turbo",
64
- type: "t2t",
65
- desc: "通义千问极速模型,响应最快",
65
+ type: "all",
66
+ desc: "通义千问极速模型,支持图片理解,响应最快",
66
67
  },
67
68
  {
68
69
  name: "万相 2.7 文生图",
@@ -894,6 +895,81 @@ function parameterInt(parameters, keys) {
894
895
  return 0;
895
896
  }
896
897
  // ===================== 路由处理器 =====================
898
+ /**
899
+ * DeepSeek 联网:先检索(Search API)/ 抓取(Fetch API)再生成,
900
+ * 结果为 system 上下文注入;按次记账(billing_unit=request,失败/无结果记 0 成本)。
901
+ */
902
+ async function deepSeekSearchContext(opts) {
903
+ const { messages, apiKey, baseUrl, scene, employeeId, provider } = opts;
904
+ const query = extractSearchQuery(messages);
905
+ if (!query)
906
+ return messages;
907
+ const started = Date.now();
908
+ let status = "failed";
909
+ let httpStatus = null;
910
+ let contextText = "";
911
+ try {
912
+ const url = extractUrl(messages);
913
+ if (url) {
914
+ const data = await fetchWeb(apiKey, baseUrl, url);
915
+ httpStatus = data ? 200 : 0;
916
+ if (data)
917
+ contextText = buildFetchContext(data, url);
918
+ }
919
+ else {
920
+ const results = await searchWeb(apiKey, baseUrl, query);
921
+ if (results.length)
922
+ contextText = buildSearchContext(results);
923
+ }
924
+ status = contextText ? "success" : "failed";
925
+ }
926
+ catch (e) {
927
+ logger.error("DeepSeek 联网搜索失败,继续走无搜索链路", e.message);
928
+ }
929
+ const out = contextText
930
+ ? [{ role: "system", content: contextText }, ...messages]
931
+ : messages;
932
+ // 按次记账事件(billing_unit=request;失败/无结果仍记 0 成本事件)
933
+ void recordUsage({
934
+ ctx: { scene, source: "admin", employee_id: employeeId },
935
+ provider,
936
+ model: "tools/search",
937
+ model_type: "search",
938
+ billing_unit: "request",
939
+ pricing_mode: "per_request",
940
+ status,
941
+ http_status: httpStatus,
942
+ error_message: status === "success" ? null : "搜索无结果或失败",
943
+ latency_ms: Date.now() - started,
944
+ request_count: 1,
945
+ quantity: 1,
946
+ actual_quantity: 1,
947
+ usage: { source: "none" },
948
+ }).catch(() => undefined);
949
+ return out;
950
+ }
951
+ /** 读取 SSE 流并按事件切分回调。 */
952
+ async function forEachSseEvent(reader, onEvent) {
953
+ const decoder = new TextDecoder();
954
+ let buffer = "";
955
+ for (;;) {
956
+ const { done, value } = await reader.read();
957
+ if (done)
958
+ break;
959
+ buffer += decoder.decode(value, { stream: true });
960
+ const events = buffer.split("\n\n");
961
+ buffer = events.pop() ?? "";
962
+ for (const rawEvent of events) {
963
+ const line = rawEvent.split("\n").find((l) => l.startsWith("data:"));
964
+ if (!line)
965
+ continue;
966
+ const jsonText = line.slice(5).trim();
967
+ if (!jsonText || jsonText === "[DONE]")
968
+ continue;
969
+ onEvent(jsonText);
970
+ }
971
+ }
972
+ }
897
973
  export async function aiRoutes(fastify, _opts) {
898
974
  // 获取供应商配置列表
899
975
  fastify.get("/providers", {
@@ -949,6 +1025,20 @@ export async function aiRoutes(fastify, _opts) {
949
1025
  const modelNames = config.models.map((m) => m.name);
950
1026
  return ApiResponse.success(modelNames.length ? modelNames : DEEPSEEK_DEFAULT_MODELS);
951
1027
  });
1028
+ // 模型选择列表(只读,剥离 api_key;普通登录用户下拉框用)
1029
+ fastify.get("/models/select", {
1030
+ schema: { summary: "模型选择列表(只读,不含 API Key)" },
1031
+ preHandler: [fastify.requireAuth],
1032
+ }, async () => {
1033
+ const providers = await getAllProviderConfigs();
1034
+ const items = providers.map((p) => ({
1035
+ provider: p.provider,
1036
+ provider_label: p.provider,
1037
+ is_default: false,
1038
+ models: p.models ?? [],
1039
+ }));
1040
+ return ApiResponse.success({ providers: items });
1041
+ });
952
1042
  // AI 对话代理(支持流式/非流式)
953
1043
  fastify.post("/chat", {
954
1044
  preHandler: [fastify.requirePermission("content:article:create")],
@@ -968,31 +1058,63 @@ export async function aiRoutes(fastify, _opts) {
968
1058
  const employeeId = request.currentEmployee?.id ?? null;
969
1059
  const scene = "ai_chat";
970
1060
  resolveLocalImageUrls(data.messages);
971
- const url = `${config.base_url}/chat/completions`;
1061
+ const features = {
1062
+ deep_think: Boolean(data.deep_think),
1063
+ web_search: Boolean(data.web_search),
1064
+ };
1065
+ const useResponses = shouldUseResponses(provider, model, features);
1066
+ const apiKey = config.api_key;
1067
+ const baseUrl = config.base_url;
1068
+ let messages = data.messages.map((m) => ({
1069
+ role: m.role,
1070
+ content: m.content,
1071
+ }));
1072
+ // DeepSeek 联网搜索:先检索/抓取再生成,注入结果为 system 上下文,按次记账
1073
+ if (provider === "deepseek" && data.web_search) {
1074
+ messages = await deepSeekSearchContext({
1075
+ messages,
1076
+ apiKey,
1077
+ baseUrl,
1078
+ scene,
1079
+ employeeId,
1080
+ provider,
1081
+ });
1082
+ }
1083
+ const url = `${baseUrl}/${useResponses ? "responses" : "chat/completions"}`;
972
1084
  const headers = {
973
- Authorization: `Bearer ${config.api_key}`,
1085
+ Authorization: `Bearer ${apiKey}`,
974
1086
  "Content-Type": "application/json",
975
1087
  };
976
- const payload = {
977
- model,
978
- messages: data.messages.map((m) => ({
979
- role: m.role,
980
- content: m.content,
981
- })),
982
- temperature: 0.7,
983
- max_tokens: 4096,
984
- };
985
- const featureParams = PROVIDER_FEATURE_PARAMS[provider] ?? {};
986
- if (data.deep_think) {
987
- const dp = featureParams.deep_think;
988
- if (dp)
989
- Object.assign(payload, dp);
990
- }
991
- if (data.web_search) {
992
- const sp = featureParams.web_search;
993
- if (sp)
994
- Object.assign(payload, sp);
1088
+ const payload = useResponses
1089
+ ? buildResponsesPayload(messages, {
1090
+ model,
1091
+ temperature: 0.7,
1092
+ maxTokens: 4096,
1093
+ stream: Boolean(data.stream),
1094
+ deepThink: Boolean(data.deep_think),
1095
+ })
1096
+ : {
1097
+ model,
1098
+ messages,
1099
+ temperature: 0.7,
1100
+ max_tokens: 4096,
1101
+ };
1102
+ if (!useResponses) {
1103
+ const featureParams = PROVIDER_FEATURE_PARAMS[provider] ?? {};
1104
+ if (data.deep_think) {
1105
+ const dp = featureParams.deep_think;
1106
+ if (dp)
1107
+ Object.assign(payload, dp);
1108
+ }
1109
+ if (data.web_search) {
1110
+ const sp = featureParams.web_search;
1111
+ if (sp)
1112
+ Object.assign(payload, sp);
1113
+ }
995
1114
  }
1115
+ const record = (event) => {
1116
+ void recordUsage(event).catch(() => undefined);
1117
+ };
996
1118
  // 流式模式:实时推送 SSE
997
1119
  if (data.stream) {
998
1120
  payload.stream = true;
@@ -1003,6 +1125,21 @@ export async function aiRoutes(fastify, _opts) {
1003
1125
  Connection: "keep-alive",
1004
1126
  "X-Accel-Buffering": "no",
1005
1127
  });
1128
+ let streamStatus = "success";
1129
+ let usage = null;
1130
+ const recordStream = (s) => {
1131
+ record({
1132
+ ctx: { scene, source: "admin", employee_id: employeeId },
1133
+ provider,
1134
+ model,
1135
+ model_type: "t2t",
1136
+ billing_unit: "token",
1137
+ status: s,
1138
+ is_stream: true,
1139
+ latency_ms: Date.now() - startedAt,
1140
+ usage: usage ?? { source: "none" },
1141
+ });
1142
+ };
1006
1143
  try {
1007
1144
  const resp = await fetch(url, {
1008
1145
  method: "POST",
@@ -1024,42 +1161,73 @@ export async function aiRoutes(fastify, _opts) {
1024
1161
  catch {
1025
1162
  // ignore
1026
1163
  }
1164
+ streamStatus = "failed";
1027
1165
  reply.raw.write(`data: ${JSON.stringify({ type: "error", content: msg })}\n\n`);
1028
1166
  reply.raw.end();
1167
+ recordStream("failed");
1029
1168
  return;
1030
1169
  }
1031
1170
  if (resp.body) {
1032
1171
  const reader = resp.body.getReader();
1033
- while (true) {
1034
- const { done, value } = await reader.read();
1035
- if (done)
1036
- break;
1037
- if (value && value.length)
1038
- reply.raw.write(value);
1172
+ if (useResponses) {
1173
+ // Responses 流:SSE 事件翻译成 chat-completions 形态
1174
+ let streamDone = false;
1175
+ await forEachSseEvent(reader, (jsonText) => {
1176
+ if (streamDone)
1177
+ return;
1178
+ let parsed;
1179
+ try {
1180
+ parsed = JSON.parse(jsonText);
1181
+ }
1182
+ catch {
1183
+ return;
1184
+ }
1185
+ const translated = translateStream(parsed);
1186
+ if (!translated)
1187
+ return;
1188
+ if (translated.type === "error") {
1189
+ streamDone = true;
1190
+ streamStatus = "failed";
1191
+ reply.raw.write(`data: ${JSON.stringify({
1192
+ type: "error",
1193
+ content: translated.content,
1194
+ })}\n\n`);
1195
+ return;
1196
+ }
1197
+ if (translated.done) {
1198
+ streamDone = true;
1199
+ if (translated.usage) {
1200
+ usage = parseResponsesUsage(translated.usage);
1201
+ }
1202
+ reply.raw.write(`data: ${JSON.stringify(translated)}\n\n`);
1203
+ return;
1204
+ }
1205
+ reply.raw.write(`data: ${JSON.stringify(translated)}\n\n`);
1206
+ });
1207
+ }
1208
+ else {
1209
+ while (true) {
1210
+ const { done, value } = await reader.read();
1211
+ if (done)
1212
+ break;
1213
+ if (value && value.length)
1214
+ reply.raw.write(value);
1215
+ }
1039
1216
  }
1040
1217
  }
1041
1218
  reply.raw.write("data: [DONE]\n\n");
1042
1219
  reply.raw.end();
1043
- // 流式无法稳定拿到 usage:成功结束后记一笔,标记为 none
1044
- void recordUsage({
1045
- ctx: { scene, source: "admin", employee_id: employeeId },
1046
- provider,
1047
- model,
1048
- model_type: "t2t",
1049
- billing_unit: "token",
1050
- status: "success",
1051
- is_stream: true,
1052
- latency_ms: Date.now() - startedAt,
1053
- usage: { source: "none" },
1054
- }).catch(() => undefined);
1220
+ recordStream(streamStatus);
1055
1221
  }
1056
1222
  catch (e) {
1057
1223
  logger.error("AI 流式调用异常", e);
1224
+ streamStatus = "failed";
1058
1225
  reply.raw.write(`data: ${JSON.stringify({
1059
1226
  type: "error",
1060
1227
  content: `AI 调用失败: ${e.message}`,
1061
1228
  })}\n\n`);
1062
1229
  reply.raw.end();
1230
+ recordStream("failed");
1063
1231
  }
1064
1232
  return;
1065
1233
  }
@@ -1077,14 +1245,36 @@ export async function aiRoutes(fastify, _opts) {
1077
1245
  throw new AppException(ErrorCode.PARAM_ERROR, `AI 服务返回错误 (${resp.status}): ${body.slice(0, 300)}`);
1078
1246
  }
1079
1247
  const result = (await resp.json());
1080
- const message = (result.choices?.[0]
1081
- ?.message ?? {});
1082
- const replyContent = typeof message.content === "string" ? message.content : "";
1083
- const thinking = typeof message.reasoning_content === "string"
1084
- ? message.reasoning_content
1085
- : "";
1086
- const usage = extractChatUsage(result);
1087
- void recordUsage({
1248
+ let replyContent = "";
1249
+ let thinking = "";
1250
+ let usage = null;
1251
+ let requestId = null;
1252
+ let rawUsage = null;
1253
+ if (useResponses) {
1254
+ const parsed = parseResponsesOutput(result);
1255
+ replyContent = parsed.content;
1256
+ thinking = parsed.thinking;
1257
+ requestId = typeof result.id === "string" ? result.id : null;
1258
+ rawUsage = parsed.usage;
1259
+ usage = parsed.usage ? parseResponsesUsage(parsed.usage) : null;
1260
+ }
1261
+ else {
1262
+ const message = (result.choices?.[0]
1263
+ ?.message ?? {});
1264
+ replyContent =
1265
+ typeof message.content === "string" ? message.content : "";
1266
+ thinking =
1267
+ typeof message.reasoning_content === "string"
1268
+ ? message.reasoning_content
1269
+ : "";
1270
+ usage = extractChatUsage(result);
1271
+ requestId = typeof result.id === "string" ? result.id : null;
1272
+ rawUsage =
1273
+ result.usage && typeof result.usage === "object"
1274
+ ? result.usage
1275
+ : null;
1276
+ }
1277
+ record({
1088
1278
  ctx: { scene, source: "admin", employee_id: employeeId },
1089
1279
  provider,
1090
1280
  model,
@@ -1092,12 +1282,10 @@ export async function aiRoutes(fastify, _opts) {
1092
1282
  billing_unit: "token",
1093
1283
  status: "success",
1094
1284
  latency_ms: Date.now() - startedAt,
1095
- provider_request_id: typeof result.id === "string" ? result.id : null,
1285
+ provider_request_id: requestId,
1096
1286
  usage: usage ?? { source: "none" },
1097
- raw_usage: result.usage && typeof result.usage === "object"
1098
- ? result.usage
1099
- : null,
1100
- }).catch(() => undefined);
1287
+ raw_usage: rawUsage,
1288
+ });
1101
1289
  return ApiResponse.success({ reply: replyContent, thinking });
1102
1290
  }
1103
1291
  catch (e) {