bolt.diy/app/lib/hooks/usePromptEnhancer.ts

86 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-07-10 16:44:39 +00:00
import { useState } from 'react';
import { createScopedLogger } from '~/utils/logger';
2024-07-10 16:44:39 +00:00
const logger = createScopedLogger('usePromptEnhancement');
export function usePromptEnhancer() {
const [enhancingPrompt, setEnhancingPrompt] = useState(false);
const [promptEnhanced, setPromptEnhanced] = useState(false);
const resetEnhancer = () => {
setEnhancingPrompt(false);
setPromptEnhanced(false);
};
2024-11-12 00:10:54 +00:00
const enhancePrompt = async (
input: string,
setInput: (value: string) => void,
model: string,
provider: string,
apiKeys?: Record<string, string>
) => {
2024-07-10 16:44:39 +00:00
setEnhancingPrompt(true);
setPromptEnhanced(false);
2024-11-12 00:10:54 +00:00
const requestBody: any = {
message: input,
model,
provider,
};
if (apiKeys) {
requestBody.apiKeys = apiKeys;
}
2024-07-10 16:44:39 +00:00
const response = await fetch('/api/enhancer', {
method: 'POST',
2024-11-12 00:10:54 +00:00
body: JSON.stringify(requestBody),
2024-07-10 16:44:39 +00:00
});
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
const reader = response.body?.getReader();
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
const originalInput = input;
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
if (reader) {
const decoder = new TextDecoder();
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
let _input = '';
let _error;
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
try {
setInput('');
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
while (true) {
const { value, done } = await reader.read();
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
if (done) {
break;
}
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
_input += decoder.decode(value);
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
logger.trace('Set input', _input);
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
setInput(_input);
}
} catch (error) {
_error = error;
setInput(originalInput);
} finally {
if (_error) {
logger.error(_error);
}
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
setEnhancingPrompt(false);
setPromptEnhanced(true);
2024-11-12 00:10:54 +00:00
2024-07-10 16:44:39 +00:00
setTimeout(() => {
setInput(_input);
});
}
}
};
return { enhancingPrompt, promptEnhanced, enhancePrompt, resetEnhancer };
}