feat: switch AI provider from Anthropic to DeepSeek
- lib/claude/client.ts: replace Anthropic SDK with openai package pointed at DeepSeek baseURL
- 4 AI routes: port tool definitions, tool_choice, and output parsing to OpenAI function-calling format
- Drop thinking:{type:'adaptive'} (no DeepSeek equivalent); model string → deepseek-chat
- settings/route.ts: add DEEPSEEK_API_KEY to ALLOWED_KEYS
- migration: seed DEEPSEEK_API_KEY placeholder row in app_settings
- tests: update 3 AI route tests to mock createDeepSeekClient + OpenAI response shape
Voyage AI embedding path untouched (DeepSeek has no embeddings endpoint).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CPf5Rc8QPx6V8KLEEgfKEQ
This commit is contained in:
@@ -2,7 +2,7 @@ export const dynamic = 'force-dynamic'
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { createAnthropicClient } from '@/lib/claude/client'
|
||||
import { createDeepSeekClient } from '@/lib/claude/client'
|
||||
import { getApiKey } from '@/lib/settings'
|
||||
|
||||
type ZoneAggregate = {
|
||||
@@ -92,41 +92,43 @@ export async function POST() {
|
||||
return NextResponse.json({ error: 'Rate limit: wait 60 seconds between AI requests' }, { status: 429 })
|
||||
}
|
||||
|
||||
const anthropicKey = await getApiKey(supabase, 'ANTHROPIC_API_KEY')
|
||||
const anthropic = createAnthropicClient(anthropicKey)
|
||||
const deepseekKey = await getApiKey(supabase, 'DEEPSEEK_API_KEY')
|
||||
const client = createDeepSeekClient(deepseekKey)
|
||||
|
||||
let message: Awaited<ReturnType<typeof anthropic.messages.create>>
|
||||
let res: Awaited<ReturnType<typeof client.chat.completions.create>>
|
||||
try {
|
||||
message = await anthropic.messages.create({
|
||||
model: 'claude-opus-4-8',
|
||||
thinking: { type: 'adaptive' },
|
||||
res = await client.chat.completions.create({
|
||||
model: 'deepseek-chat',
|
||||
max_tokens: 2048,
|
||||
tools: [{
|
||||
name: 'flag_rising_risk',
|
||||
description: 'Flag warehouse zones showing rising safety risk from 90-day incident aggregates',
|
||||
input_schema: {
|
||||
type: 'object' as const,
|
||||
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' },
|
||||
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'],
|
||||
},
|
||||
required: ['zone', 'site', 'risk_level', 'rationale', 'recommended_action'],
|
||||
},
|
||||
summary: { type: 'string', description: 'Two-sentence overall risk picture' },
|
||||
},
|
||||
summary: { type: 'string', description: 'Two-sentence overall risk picture' },
|
||||
required: ['flags', 'summary'],
|
||||
},
|
||||
required: ['flags', 'summary'],
|
||||
},
|
||||
}],
|
||||
tool_choice: { type: 'tool', name: 'flag_rising_risk' },
|
||||
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.
|
||||
@@ -142,11 +144,13 @@ ${JSON.stringify(aggregates, null, 2)}
|
||||
return NextResponse.json({ error: 'AI service unavailable' }, { status: 503 })
|
||||
}
|
||||
|
||||
const toolBlock = message.content.find(b => b.type === 'tool_use')
|
||||
if (!toolBlock || toolBlock.type !== 'tool_use')
|
||||
return NextResponse.json({ error: 'AI suggestion failed' }, { status: 500 })
|
||||
const call = res.choices[0]?.message?.tool_calls?.[0]
|
||||
if (!call || call.type !== 'function') return NextResponse.json({ error: 'AI suggestion failed' }, { status: 500 })
|
||||
|
||||
let input: { flags?: unknown; summary?: unknown }
|
||||
try { input = JSON.parse(call.function.arguments) }
|
||||
catch { return NextResponse.json({ error: 'AI returned unexpected structure' }, { status: 500 }) }
|
||||
|
||||
const input = toolBlock.input as { flags?: unknown; summary?: unknown }
|
||||
if (!Array.isArray(input.flags) || typeof input.summary !== 'string')
|
||||
return NextResponse.json({ error: 'AI returned unexpected structure' }, { status: 500 })
|
||||
|
||||
@@ -164,7 +168,7 @@ ${JSON.stringify(aggregates, null, 2)}
|
||||
p_table_name: 'incidents',
|
||||
p_record_id: user.id,
|
||||
p_action: 'ai_risk_flags',
|
||||
p_new_value: { flags, summary: input.summary, model: 'claude-opus-4-8' } as never,
|
||||
p_new_value: { flags, summary: input.summary, model: 'deepseek-chat' } as never,
|
||||
})
|
||||
|
||||
return NextResponse.json({ flags, summary: input.summary })
|
||||
|
||||
Reference in New Issue
Block a user