Spaces:
Running
Running
refactor: Adopt OpenAI Responses API for conversation continuity and improve test reliability
42dcc4f | import { generateText } from 'ai'; | |
| import { createOpenAI } from '@ai-sdk/openai'; | |
| import { Message } from '../types/models'; | |
| // Create OpenAI provider with custom API key | |
| const openai = createOpenAI({ | |
| apiKey: process.env.CZ_OPENAI_API_KEY || '', | |
| }); | |
| /** | |
| * Generates a concise Traditional Chinese title for a conversation | |
| * based on provided messages (6-10 characters) | |
| * Caller determines which messages to include (typically first 15 messages) | |
| */ | |
| export async function generateConversationTitle(messages: Message[]): Promise<string> { | |
| if (messages.length === 0) { | |
| return '新對話'; | |
| } | |
| // Use all provided messages (caller sends first 15 for best context) | |
| const recentMessages = messages; | |
| // Format messages for the prompt | |
| const conversationText = recentMessages | |
| .map(m => { | |
| const speaker = m.speaker === 'student' ? '學生' : '老師'; | |
| return `${speaker}: ${m.content}`; | |
| }) | |
| .join('\n'); | |
| try { | |
| const { text } = await generateText({ | |
| model: openai.responses(process.env.MODEL_NAME || 'gpt-5'), | |
| prompt: `根據以下對話內容,用6-10個繁體中文字產生一個簡潔的標題。標題應該概括對話的主題或情境。只回傳標題文字,不要有其他說明。 | |
| 對話內容: | |
| ${conversationText} | |
| 標題:`, | |
| }); | |
| // Clean up the response - remove quotes, extra whitespace, etc. | |
| const cleanedTitle = text.trim().replace(/^["「『]|["」』]$/g, '').slice(0, 15); | |
| return cleanedTitle || '新對話'; | |
| } catch (error) { | |
| console.error('Error generating conversation title:', error); | |
| return '新對話'; | |
| } | |
| } | |