logancyang_obsidian-copilot/src/langchainStream.ts
Emt-lin 3a30b5bae6
feat: Improve error handling architecture across chain runners. (#1931)
* feat: Improve error handling architecture across chain runners.

# Conflicts:
#	src/LLMProviders/chainRunner/AutonomousAgentChainRunner.ts
#	src/chainFactory.ts
#	src/chainUtils.ts

* fix: Preserve correct content ordering in streaming messages

Fix two issues that could confuse users during streaming:
- Error blocks now inserted at correct stream position instead of always appending to end, preserving visual context
- Reset lastDisplayedContent between runs to prevent stale content from appearing in new responses

* fix: fix branch conflicts.

* fix: correctly dispose error block roots by parameterizing disposal helpers with registry.
2025-10-23 17:00:23 -07:00

47 lines
1.4 KiB
TypeScript

import { AI_SENDER } from "@/constants";
import ChainManager from "@/LLMProviders/chainManager";
import { ChatMessage } from "@/types/message";
import { err2String, formatDateTime } from "./utils";
import { logError } from "@/logger";
import { v4 as uuidv4 } from "uuid";
import { formatErrorChunk } from "@/utils/toolResultUtils";
export type Role = "assistant" | "user" | "system";
export const getAIResponse = async (
userMessage: ChatMessage,
chainManager: ChainManager,
addMessage: (message: ChatMessage) => void,
updateCurrentAiMessage: (message: string) => void,
updateShouldAbort: (abortController: AbortController | null) => void,
options: {
debug?: boolean;
ignoreSystemMessage?: boolean;
updateLoading?: (loading: boolean) => void;
updateLoadingMessage?: (message: string) => void;
} = {}
) => {
const abortController = new AbortController();
updateShouldAbort(abortController);
try {
await chainManager.runChain(
userMessage,
abortController,
updateCurrentAiMessage,
addMessage,
options
);
} catch (error) {
logError("Model request failed:", error);
const errorMessage = formatErrorChunk("Model request failed: " + err2String(error));
addMessage({
id: uuidv4(),
sender: AI_SENDER,
isErrorMessage: true,
message: errorMessage,
isVisible: true,
timestamp: formatDateTime(new Date()),
});
}
};