2026-05-06 17:22:50 +08:00
|
|
|
import { NextResponse } from "next/server"
|
2026-05-08 20:15:54 +08:00
|
|
|
import { prisma } from "@/app/lib/prisma"
|
2026-05-06 17:22:50 +08:00
|
|
|
|
2026-05-08 20:15:54 +08:00
|
|
|
const FALLBACK_API_KEY = 'app-lbe2lglt7taGtZk0dG7pAhbx'
|
|
|
|
|
const FALLBACK_API_URL = 'http://df.clkeji.com/v1/chat-messages'
|
2026-05-06 17:22:50 +08:00
|
|
|
|
|
|
|
|
export async function POST(request: Request) {
|
|
|
|
|
try {
|
|
|
|
|
const body = await request.json()
|
2026-05-08 20:15:54 +08:00
|
|
|
const { agentId, ...difyBody } = body
|
2026-05-06 17:22:50 +08:00
|
|
|
|
2026-05-08 20:15:54 +08:00
|
|
|
let apiKey = FALLBACK_API_KEY
|
|
|
|
|
let apiUrl = FALLBACK_API_URL
|
|
|
|
|
|
|
|
|
|
if (agentId) {
|
|
|
|
|
const agent = await prisma.agent.findUnique({
|
|
|
|
|
where: { id: parseInt(agentId) },
|
|
|
|
|
})
|
|
|
|
|
if (agent?.difyApiUrl && agent?.difyApiKey) {
|
|
|
|
|
apiUrl = agent.difyApiUrl.replace(/\/+$/, '') + '/chat-messages'
|
|
|
|
|
apiKey = agent.difyApiKey
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const response = await fetch(apiUrl, {
|
2026-05-06 17:22:50 +08:00
|
|
|
method: 'POST',
|
|
|
|
|
headers: {
|
2026-05-08 20:15:54 +08:00
|
|
|
'Authorization': `Bearer ${apiKey}`,
|
2026-05-06 17:22:50 +08:00
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
},
|
2026-05-08 20:15:54 +08:00
|
|
|
body: JSON.stringify({ ...difyBody, response_mode: 'streaming' }),
|
2026-05-06 17:22:50 +08:00
|
|
|
})
|
|
|
|
|
|
2026-05-08 20:15:54 +08:00
|
|
|
if (!response.ok) {
|
|
|
|
|
const text = await response.text()
|
|
|
|
|
console.error('Dify API error:', response.status, text.slice(0, 500))
|
|
|
|
|
return NextResponse.json(
|
|
|
|
|
{ error: 'Dify request failed' },
|
|
|
|
|
{ status: 502 }
|
|
|
|
|
)
|
2026-05-06 17:22:50 +08:00
|
|
|
}
|
|
|
|
|
|
2026-05-08 20:15:54 +08:00
|
|
|
const headers = new Headers()
|
|
|
|
|
headers.set('Content-Type', 'text/event-stream')
|
|
|
|
|
headers.set('Cache-Control', 'no-cache')
|
|
|
|
|
headers.set('Connection', 'keep-alive')
|
|
|
|
|
|
|
|
|
|
return new Response(response.body, { headers })
|
2026-05-06 17:22:50 +08:00
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Chat API error:', error)
|
|
|
|
|
return NextResponse.json(
|
|
|
|
|
{ error: 'Failed to connect to chat service' },
|
|
|
|
|
{ status: 500 }
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
}
|