( payloads: any[], )
| 1947 | |
| 1948 | const aggregateOpenAIResponses = ( |
| 1949 | payloads: any[], |
| 1950 | ): { |
| 1951 | text: string; |
| 1952 | images: AIImage[]; |
| 1953 | sources: Array<{ url: string; title?: string }>; |
| 1954 | } => { |
| 1955 | const deltaTexts: string[] = []; |
| 1956 | const deltaImages: AIImage[] = []; |
| 1957 | let fallbackText = ""; |
| 1958 | let fallbackImages: AIImage[] = []; |
| 1959 | const sources: Array<{ url: string; title?: string }> = []; |
| 1960 | const seenSources = new Set<string>(); |
| 1961 | |
| 1962 | const appendSources = (entries: Array<{ url: string; title?: string }>) => { |
| 1963 | for (const entry of entries) { |
| 1964 | if (seenSources.has(entry.url)) continue; |
| 1965 | seenSources.add(entry.url); |
| 1966 | sources.push(entry); |
| 1967 | } |
| 1968 | }; |
| 1969 | |
| 1970 | for (const payload of payloads) { |
| 1971 | const choice = payload?.choices?.[0]; |
| 1972 | |
| 1973 | if (choice?.delta?.content !== undefined) { |
| 1974 | const parsedDelta = parseOpenAIChatResponse({ |
| 1975 | choices: [{ message: { content: choice.delta.content } }], |
| 1976 | }); |
| 1977 | if (parsedDelta.text && parsedDelta.text !== "AI 回复为空") { |
| 1978 | deltaTexts.push(parsedDelta.text); |
| 1979 | } |
| 1980 | if (parsedDelta.images.length > 0) { |
| 1981 | deltaImages.push(...parsedDelta.images); |
| 1982 | } |
| 1983 | } |
| 1984 | |
| 1985 | const fallbackContent = |
| 1986 | choice?.message?.content ?? choice?.content ?? payload?.content; |
| 1987 | if (fallbackContent !== undefined) { |
| 1988 | const parsedFallback = parseOpenAIChatResponse({ |
| 1989 | choices: [{ message: { content: fallbackContent } }], |
| 1990 | }); |
| 1991 | if (parsedFallback.text && parsedFallback.text !== "AI 回复为空") { |
| 1992 | fallbackText = parsedFallback.text; |
| 1993 | } |
| 1994 | if (parsedFallback.images.length > 0) { |
| 1995 | fallbackImages = parsedFallback.images; |
| 1996 | } |
| 1997 | } else if (typeof choice?.text === "string" && choice.text.trim()) { |
| 1998 | fallbackText = choice.text.trim(); |
| 1999 | fallbackImages = []; |
| 2000 | } else if (typeof payload?.text === "string" && payload.text.trim()) { |
| 2001 | fallbackText = payload.text.trim(); |
| 2002 | fallbackImages = []; |
| 2003 | } |
| 2004 | |
| 2005 | appendSources(collectOpenAISources(payload)); |
| 2006 | } |
no test coverage detected