fix: switch AI endpoints from tool-calling to JSON output mode

DeepSeek v4-pro reasoning model rejects tool_choice parameter.
All 4 endpoints now use system prompts with JSON schema
instructions and parse content as JSON instead of tool_calls.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-07-26 10:49:44 +08:00
co-authored by Claude
parent 7bf3b6a409
commit ed2a2f65e4
4 changed files with 104 additions and 165 deletions
+31 -41
View File
@@ -111,56 +111,46 @@ export async function POST() {
res = await client.chat.completions.create({
model: 'deepseek-v4-pro',
max_tokens: 2048,
tools: [{
type: 'function',
function: {
name: 'flag_rising_risk',
description: 'Flag warehouse zones showing rising safety risk from 90-day incident aggregates',
parameters: {
type: 'object',
properties: {
flags: {
type: 'array',
items: {
type: 'object',
properties: {
zone: { type: 'string' },
site: { type: 'string' },
risk_level: { type: 'string', enum: ['low', 'medium', 'high'] },
rationale: { type: 'string', description: 'One or two sentences citing the numbers' },
recommended_action: { type: 'string', description: 'One concrete preventive action' },
},
required: ['zone', 'site', 'risk_level', 'rationale', 'recommended_action'],
},
},
summary: { type: 'string', description: 'Two-sentence overall risk picture' },
},
required: ['flags', 'summary'],
},
messages: [
{
role: 'system',
content: `You are an HSE risk analyst for a Malaysian 3PL warehouse operator. You must respond with valid JSON only — no markdown, no explanation outside the JSON object.
Output exactly this JSON structure:
{
"flags": [
{
"zone": "string",
"site": "string",
"risk_level": "low" | "medium" | "high",
"rationale": "One or two sentences citing the numbers",
"recommended_action": "One concrete preventive action"
}
],
"summary": "Two-sentence overall risk picture"
}
Flag only zones with rising or elevated risk (at most 5 flags; do not flag healthy zones). Base every rationale strictly on the numbers given. "first_half" is incidents in days 90-46, "second_half" is days 45-0 — a rising second_half means worsening trend. Near-miss and hazard reports are leading indicators; injuries are lagging.`,
},
}],
tool_choice: { type: 'function', function: { name: 'flag_rising_risk' } },
messages: [{
role: 'user',
content: `You are an HSE risk analyst for a Malaysian 3PL warehouse operator. Below are 90-day incident aggregates per zone. "first_half" is incidents in days 90-46, "second_half" is days 45-0 — a rising second_half means worsening trend. Near-miss and hazard reports are leading indicators; injuries are lagging.
Flag zones with rising or elevated risk (at most 5 flags; do not flag healthy zones). Base every rationale strictly on the numbers given.
<zone_data>
${JSON.stringify(aggregates, null, 2)}
</zone_data>`,
}],
{
role: 'user',
content: `Below are 90-day incident aggregates per zone. Respond with JSON only.\n\n<zone_data>\n${JSON.stringify(aggregates, null, 2)}\n</zone_data>`,
},
],
})
} catch (err) {
console.error('DeepSeek risk-flags error:', err)
return NextResponse.json({ error: 'AI service unavailable' }, { status: 503 })
}
const call = res.choices[0]?.message?.tool_calls?.[0]
if (!call || call.type !== 'function') return NextResponse.json({ error: 'AI suggestion failed' }, { status: 500 })
const raw = res.choices[0]?.message?.content
if (!raw) return NextResponse.json({ error: 'AI returned empty response' }, { status: 500 })
// Strip markdown code fences if present
const json = raw.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim()
let input: { flags?: unknown; summary?: unknown }
try { input = JSON.parse(call.function.arguments) }
try { input = JSON.parse(json) }
catch { return NextResponse.json({ error: 'AI returned unexpected structure' }, { status: 500 }) }
if (!Array.isArray(input.flags) || typeof input.summary !== 'string')