| 1 | import { createAsyncThunk } from "@reduxjs/toolkit"; |
| 2 | import posthog from "posthog-js"; |
| 3 | import StreamErrorDialog from "../../pages/gui/StreamError"; |
| 4 | import { analyzeError } from "../../util/errorAnalysis"; |
| 5 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 6 | import { setDialogMessage, setShowDialog } from "../slices/uiSlice"; |
| 7 | import { ThunkApiType } from "../store"; |
| 8 | import { cancelStream } from "./cancelStream"; |
| 9 | import { saveCurrentSession } from "./session"; |
| 10 | |
| 11 | export const streamThunkWrapper = createAsyncThunk< |
| 12 | void, |
| 13 | () => Promise<void>, |
| 14 | ThunkApiType |
| 15 | >("chat/streamWrapper", async (runStream, { dispatch, extra, getState }) => { |
| 16 | const initialState = getState(); |
| 17 | try { |
| 18 | await runStream(); |
| 19 | const state = getState(); |
| 20 | if (!state.session.isInEdit) { |
| 21 | await dispatch( |
| 22 | saveCurrentSession({ |
| 23 | openNewSession: false, |
| 24 | generateTitle: true, |
| 25 | }), |
| 26 | ); |
| 27 | } |
| 28 | } catch (e) { |
| 29 | await dispatch(cancelStream()); |
| 30 | dispatch(setDialogMessage(<StreamErrorDialog error={e} />)); |
| 31 | dispatch(setShowDialog(true)); |
| 32 | |
| 33 | // Get the selected model from the state for error analysis |
| 34 | const state = getState(); |
| 35 | const selectedModel = selectSelectedChatModel(state); |
| 36 | |
| 37 | const { parsedError, statusCode, modelTitle, providerName } = analyzeError( |
| 38 | e, |
| 39 | selectedModel, |
| 40 | ); |
| 41 | |
| 42 | const errorData = { |
| 43 | error_type: statusCode ? `HTTP ${statusCode}` : "Unknown", |
| 44 | error_message: parsedError, |
| 45 | model_provider: providerName, |
| 46 | model_title: modelTitle, |
| 47 | }; |
| 48 | |
| 49 | posthog.capture("gui_stream_error", errorData); |
| 50 | } |
| 51 | }); |