enh: generate title

This commit is contained in:
Timothy Jaeryang Baek
2025-05-05 10:36:01 +04:00
parent aa374823ce
commit 9e1400f055
2 changed files with 90 additions and 4 deletions
+34 -2
View File
@@ -539,7 +539,7 @@ export const updateTaskConfig = async (token: string, config: object) => {
export const generateTitle = async (
token: string = '',
model: string,
messages: string[],
messages: object[],
chat_id?: string
) => {
let error = null;
@@ -573,7 +573,39 @@ export const generateTitle = async (
throw error;
}
return res?.choices[0]?.message?.content.replace(/["']/g, '') ?? 'New Chat';
try {
// Step 1: Safely extract the response string
const response = res?.choices[0]?.message?.content ?? '';
// Step 2: Attempt to fix common JSON format issues like single quotes
const sanitizedResponse = response.replace(/['‘’`]/g, '"'); // Convert single quotes to double quotes for valid JSON
// Step 3: Find the relevant JSON block within the response
const jsonStartIndex = sanitizedResponse.indexOf('{');
const jsonEndIndex = sanitizedResponse.lastIndexOf('}');
// Step 4: Check if we found a valid JSON block (with both `{` and `}`)
if (jsonStartIndex !== -1 && jsonEndIndex !== -1) {
const jsonResponse = sanitizedResponse.substring(jsonStartIndex, jsonEndIndex + 1);
// Step 5: Parse the JSON block
const parsed = JSON.parse(jsonResponse);
// Step 6: If there's a "tags" key, return the tags array; otherwise, return an empty array
if (parsed && parsed.title) {
return parsed.title;
} else {
return null;
}
}
// If no valid JSON block found, return an empty array
return null;
} catch (e) {
// Catch and safely return empty array on any parsing errors
console.error('Failed to parse response: ', e);
return null;
}
};
export const generateTags = async (