78 lines
1.9 KiB
TypeScript
78 lines
1.9 KiB
TypeScript
/**
|
||
* 错别字检测与修正API
|
||
* 与Dify平台交互,实现错别字检测和修正功能
|
||
*/
|
||
|
||
export interface SpellCheckParams {
|
||
user_input: string;
|
||
}
|
||
|
||
export interface SpellCheckResponse {
|
||
message?: {
|
||
content?: string;
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 发送错别字检测请求到Dify平台
|
||
* @param params 包含用户输入文本的参数
|
||
* @returns Promise<string> 返回修正后的文本内容
|
||
*/
|
||
export async function fetchSpellCheck(params: SpellCheckParams): Promise<string> {
|
||
const requestBody = {
|
||
inputs: {
|
||
user_input: params.user_input
|
||
},
|
||
query: "1",
|
||
response_mode: "streaming" as const
|
||
};
|
||
|
||
try {
|
||
const response = await fetch('https://copilot.sino-bridge.com/v1/chat-messages', {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
'Authorization': 'Bearer app-AZ3jH4bHyOPsTzDjEQyoqwOy'
|
||
},
|
||
body: JSON.stringify(requestBody)
|
||
});
|
||
|
||
if (!response.ok) {
|
||
throw new Error(`HTTP error! status: ${response.status}`);
|
||
}
|
||
|
||
// 处理流式响应
|
||
const reader = response.body?.getReader();
|
||
const decoder = new TextDecoder();
|
||
let result = '';
|
||
|
||
if (reader) {
|
||
while (true) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
|
||
const chunk = decoder.decode(value, { stream: true });
|
||
const lines = chunk.split('\n');
|
||
|
||
for (const line of lines) {
|
||
if (line.startsWith('data: ')) {
|
||
try {
|
||
const data = JSON.parse(line.slice(6)) as SpellCheckResponse;
|
||
if (data.message?.content) {
|
||
result += data.message.content;
|
||
}
|
||
} catch (e) {
|
||
// 忽略解析错误,继续处理下一行
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
return result;
|
||
} catch (error) {
|
||
console.error('错别字检测请求失败:', error);
|
||
throw error;
|
||
}
|
||
}
|