Files
biblical-guide.com/app/api/chat/route.ts
andupetcu a0969e88df Implement complete multi-language support with Romanian/English
- Added next-intl for internationalization with Romanian as default locale
- Restructured app directory with [locale] routing (/ro, /en)
- Created comprehensive translation files for both languages
- Fixed Next.js 15 async params compatibility in layout components
- Updated all components to use proper i18n hooks and translations
- Configured middleware for locale routing and fallbacks
- Fixed FloatingChat component translation array handling
- Restored complete home page with internationalized content
- Fixed Material-UI Slide component prop error (mountOnExit → unmountOnExit)

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-20 15:43:51 +03:00

161 lines
5.1 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { searchBibleHybrid, BibleVerse } from '@/lib/vector-search'
const chatRequestSchema = z.object({
message: z.string().min(1),
locale: z.string().optional().default('ro'),
history: z.array(z.object({
id: z.string(),
role: z.enum(['user', 'assistant']),
content: z.string(),
timestamp: z.string()
})).optional().default([])
})
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { message, locale, history } = chatRequestSchema.parse(body)
// Generate response using Azure OpenAI with vector search
const response = await generateBiblicalResponse(message, locale, history)
return NextResponse.json({
success: true,
response
})
} catch (error) {
console.error('Error in chat API:', error)
if (error instanceof z.ZodError) {
return NextResponse.json(
{
success: false,
error: 'Invalid request format',
details: error.errors
},
{ status: 400 }
)
}
return NextResponse.json(
{
success: false,
error: 'Failed to process chat message'
},
{ status: 500 }
)
}
}
async function generateBiblicalResponse(message: string, locale: string, history: any[]): Promise<string> {
try {
// Search for relevant Bible verses using vector search with language filtering
const relevantVerses = await searchBibleHybrid(message, locale, 5)
// Create context from relevant verses
const versesContext = relevantVerses
.map(verse => `${verse.ref}: "${verse.text_raw}"`)
.join('\n\n')
// Create conversation history for context
const conversationHistory = history
.slice(-3) // Last 3 messages for context
.map(msg => `${msg.role}: ${msg.content}`)
.join('\n')
// Create language-specific system prompts
const systemPrompts = {
ro: `Ești un asistent AI pentru întrebări biblice în limba română. Răspunde pe baza Scripturii, fiind respectuos și înțelept.
Instrucțiuni:
- Folosește versurile biblice relevante pentru a răspunde la întrebare
- Citează întotdeauna referințele biblice (ex: Ioan 3:16)
- Răspunde în română
- Fii empatic și încurajator
- Dacă nu ești sigur, încurajează studiul personal și rugăciunea
Versuri relevante pentru această întrebare:
${versesContext}
Conversația anterioară:
${conversationHistory}
Întrebarea curentă: ${message}`,
en: `You are an AI assistant for biblical questions in English. Answer based on Scripture, being respectful and wise.
Instructions:
- Use the relevant Bible verses to answer the question
- Always cite biblical references (e.g., John 3:16)
- Respond in English
- Be empathetic and encouraging
- If unsure, encourage personal study and prayer
Relevant verses for this question:
${versesContext}
Previous conversation:
${conversationHistory}
Current question: ${message}`
}
const systemPrompt = systemPrompts[locale as keyof typeof systemPrompts] || systemPrompts.en
// Call Azure OpenAI
const response = await fetch(
`${process.env.AZURE_OPENAI_ENDPOINT}/openai/deployments/${process.env.AZURE_OPENAI_DEPLOYMENT}/chat/completions?api-version=${process.env.AZURE_OPENAI_API_VERSION}`,
{
method: 'POST',
headers: {
'api-key': process.env.AZURE_OPENAI_KEY!,
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: [
{
role: 'system',
content: systemPrompt
},
{
role: 'user',
content: message
}
],
max_tokens: 800,
temperature: 0.7,
top_p: 0.9
}),
}
)
if (!response.ok) {
throw new Error(`Azure OpenAI API error: ${response.status}`)
}
const data = await response.json()
return data.choices[0].message.content
} catch (error) {
console.error('Error calling Azure OpenAI:', error)
// Language-specific fallback responses
const fallbackResponses = {
ro: `Îmi pare rău, dar întâmpin o problemă tehnică în acest moment. Te încurajez să cercetezi acest subiect în Scripturi și să te rogi pentru înțelegere.
"Cercetați Scripturile, pentru că socotiți că în ele aveți viața veșnică, și tocmai ele mărturisesc despre Mine" (Ioan 5:39).
"Dacă vreunul dintre voi duce lipsă de înțelepciune, să ceară de la Dumnezeu, care dă tuturor cu dărnicie și fără mustrare, și i se va da" (Iacov 1:5).`,
en: `Sorry, I'm experiencing a technical issue at the moment. I encourage you to research this topic in Scripture and pray for understanding.
"You study the Scriptures diligently because you think that in them you have eternal life. These are the very Scriptures that testify about me" (John 5:39).
"If any of you lacks wisdom, you should ask God, who gives generously to all without finding fault, and it will be given to you" (James 1:5).`
}
return fallbackResponses[locale as keyof typeof fallbackResponses] || fallbackResponses.en
}
}