Skip to content

Commit f5f1f34

Browse files
author
linyuan.yang
committed
fix
1 parent 87e7acc commit f5f1f34

4 files changed

Lines changed: 76 additions & 19 deletions

File tree

‎packages/backend/llm/scorpio.llm.openai/src/OpenAIResponseModelService.ts‎

Lines changed: 60 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,9 @@ export class OpenAIResponseModelService extends OpenAIServiceBase implements IMo
7070
let responseId: string | undefined;
7171
let outputText = "";
7272
const calls = new Map<number, ResponseFunctionToolCall>();
73+
const doneItems = new Map<number, ResponseOutputItem>();
7374
let yieldedFinal = false;
75+
let pendingText = "";
7476

7577
for await (const event of stream as AsyncIterable<ResponseStreamEvent>) {
7678
switch (event.type) {
@@ -80,15 +82,32 @@ export class OpenAIResponseModelService extends OpenAIServiceBase implements IMo
8082
break;
8183
case "response.output_text.delta":
8284
outputText += event.delta;
85+
pendingText += event.delta;
8386
yield service.toStreamingMessage(responseId, outputText, calls);
8487
break;
8588
case "response.output_item.added":
86-
case "response.output_item.done":
8789
if (event.item.type === "function_call") {
8890
calls.set(event.output_index, { ...event.item });
8991
yield service.toStreamingMessage(responseId, outputText, calls);
9092
}
9193
break;
94+
case "response.output_item.done": {
95+
doneItems.set(event.output_index, event.item);
96+
if (event.item.type === "message") {
97+
// 该 item 已完整落到 doneItems,从待累计文本中剔除,避免兜底 content 重复
98+
const itemText = event.item.content
99+
.map(part => (part.type === "output_text" ? part.text : part.type === "refusal" ? part.refusal : ""))
100+
.join("");
101+
if (itemText && pendingText.endsWith(itemText)) {
102+
pendingText = pendingText.slice(0, -itemText.length);
103+
}
104+
}
105+
if (event.item.type === "function_call") {
106+
calls.set(event.output_index, { ...event.item });
107+
yield service.toStreamingMessage(responseId, outputText, calls);
108+
}
109+
break;
110+
}
92111
case "response.function_call_arguments.delta": {
93112
const current = calls.get(event.output_index);
94113
if (current) {
@@ -109,8 +128,16 @@ export class OpenAIResponseModelService extends OpenAIServiceBase implements IMo
109128
}
110129
}
111130

112-
if (!yieldedFinal && (outputText || calls.size > 0)) {
113-
yield service.toStreamingMessage(responseId, outputText, calls);
131+
if (!yieldedFinal && (outputText || doneItems.size > 0 || calls.size > 0)) {
132+
// 流被中断(未收到 response.completed)时的兜底:尽量还原 output items 存入
133+
// additional_kwargs,否则下一轮回放会出现无 reasoning 配对的 function_call。
134+
const items = [...doneItems.entries()]
135+
.sort(([a], [b]) => a - b)
136+
.map(([, item]) => item);
137+
for (const [index, call] of calls) {
138+
if (!doneItems.has(index)) items.push(call as unknown as ResponseOutputItem);
139+
}
140+
yield service.toFinalMessage(responseId, pendingText, items);
114141
}
115142
})();
116143
}
@@ -258,9 +285,32 @@ export class OpenAIResponseModelService extends OpenAIServiceBase implements IMo
258285
}
259286

260287
private toChatMessage(response: Response): ChatMessage {
288+
const final = this.toFinalMessage(response.id, "", response.output);
289+
return {
290+
...final,
291+
...(final.additional_kwargs || {}),
292+
additional_kwargs: {
293+
...(final.additional_kwargs ?? {}),
294+
...(response.incomplete_details?.reason && { stop_reason: response.incomplete_details.reason }),
295+
},
296+
...(response.usage && {
297+
usage: {
298+
input_tokens: response.usage.input_tokens,
299+
output_tokens: response.usage.output_tokens,
300+
total_tokens: response.usage.total_tokens,
301+
},
302+
}),
303+
};
304+
}
305+
306+
private toFinalMessage(
307+
responseId: string | undefined,
308+
pendingText: string,
309+
outputItems: ResponseOutputItem[],
310+
): ChatMessage {
261311
const toolCalls: ChatToolCall[] = [];
262312
const text: string[] = [];
263-
for (const item of response.output) {
313+
for (const item of outputItems) {
264314
if (item.type === "function_call") {
265315
toolCalls.push({
266316
id: item.call_id,
@@ -276,22 +326,17 @@ export class OpenAIResponseModelService extends OpenAIServiceBase implements IMo
276326
}
277327
}
278328

329+
// 完整响应时 pendingText 为空(文本都在 items 里);流中断兜底时为尚未落为
330+
// 完整 item 的增量文本,追加在末尾以尽量保持原始顺序。
331+
const content = [...text, pendingText].join("");
279332
return {
280333
role: MessageRole.AI,
281-
content: text.join(""),
334+
content,
282335
...(toolCalls.length > 0 && { tool_calls: toolCalls }),
283-
id: response.id,
336+
...(responseId && { id: responseId }),
284337
additional_kwargs: {
285-
[RESPONSE_OUTPUT_KEY]: response.output,
286-
...(response.incomplete_details?.reason && { stop_reason: response.incomplete_details.reason }),
338+
[RESPONSE_OUTPUT_KEY]: outputItems,
287339
},
288-
...(response.usage && {
289-
usage: {
290-
input_tokens: response.usage.input_tokens,
291-
output_tokens: response.usage.output_tokens,
292-
total_tokens: response.usage.total_tokens,
293-
},
294-
}),
295340
};
296341
}
297342

‎packages/backend/llm/scorpio.llm/src/assets/models-dev.snapshot.json‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎packages/backend/sbot/prompts/system/environment.txt‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
---
22
vars:
3-
timezone: 时区 (如 Asia/Shanghai)
43
os: 操作系统 (如 Linux 5.15.0 linux)
54
assetsDir: 资源文件目录绝对路径
65
assetsUrl: 资源文件目录对外访问 URL 前缀
76
workPath: Agent 工作目录绝对路径
87

98
---
109
<environment>
11-
<timezone>{timezone}</timezone>
1210
<os>{os}</os>
1311
<paths>
1412
<working-directory dir="{workPath}">Your primary workspace. Scope file operations — read and write — here by default; go outside only when the user explicitly asks or the task cannot be done otherwise.</working-directory>

‎packages/backend/scorpio.ai/src/Utils/TimeUtils.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,21 @@ export class TimeUtils {
5858
// sv-SE 本身就是 "YYYY-MM-DD HH:mm:ss" 格式
5959
const localTime = date.toLocaleString('sv-SE', { timeZone: timezone, hourCycle: 'h23' });
6060
const weekday = date.toLocaleString('en-US', { timeZone: timezone, weekday: 'short' });
61-
return `${localTime} (${weekday}, ${timezone})`;
61+
const utcOffset = TimeUtils.formatUtcOffset(timezone, timestamp);
62+
return `${localTime} (${weekday}, ${timezone}${utcOffset ? `, ${utcOffset}` : ''})`;
63+
}
64+
65+
/** 目标时区相对 UTC 的偏移名(GMT 与 UTC 在此等价),如 "GMT+8"、"GMT-3:30";不支持时返回空串。 */
66+
static formatUtcOffset(timezone: string, timestamp = Date.now()): string {
67+
try {
68+
const value = new Intl.DateTimeFormat('en-US', {
69+
timeZone: timezone,
70+
timeZoneName: 'shortOffset',
71+
}).formatToParts(new Date(timestamp)).find(p => p.type === 'timeZoneName')?.value;
72+
return value ?? '';
73+
} catch {
74+
return '';
75+
}
6276
}
6377

6478
static formatDateKey(timestamp: number, timezone?: string | null): string {

0 commit comments

Comments
 (0)