Complete V2 user H5 flow
This commit is contained in:
@@ -45,7 +45,12 @@ export const api = {
|
||||
stop: (sessionId: number) => request<null>("/chat/stop", { method: "POST", body: JSON.stringify({ sessionId }) }),
|
||||
};
|
||||
|
||||
export async function streamChat(sessionId: number, message: string, onChunk: (chunk: string) => void) {
|
||||
export async function streamChat(
|
||||
sessionId: number,
|
||||
message: string,
|
||||
onChunk: (chunk: string) => void,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const token = getToken();
|
||||
const response = await fetch(`${API_BASE}/chat/completions`, {
|
||||
method: "POST",
|
||||
@@ -54,9 +59,11 @@ export async function streamChat(sessionId: number, message: string, onChunk: (c
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({ sessionId, message }),
|
||||
signal,
|
||||
});
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error("AI 回复连接失败");
|
||||
const message = await readErrorMessage(response);
|
||||
throw new Error(message || "AI 回复连接失败");
|
||||
}
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder("utf-8");
|
||||
@@ -77,3 +84,12 @@ export async function streamChat(sessionId: number, message: string, onChunk: (c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function readErrorMessage(response: Response) {
|
||||
try {
|
||||
const body = (await response.json()) as ApiResponse<unknown>;
|
||||
return body.message;
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user