tia/src/app/api/ai/route.ts
2026-05-10 12:04:39 +05:30

81 lines
No EOL
2.6 KiB
TypeScript

import { NextResponse } from "next/server";
import { sql } from "@/db";
const MINIMAX_API_KEY = "289bf7d1cf0c0b12ff5ccf48d95ff3c3";
const MINIMAX_BASE_URL = "https://api.minimax.chat/v1";
export async function POST(request: Request) {
try {
const body = await request.json();
const { messages, childId } = body;
if (!messages || !Array.isArray(messages)) {
return NextResponse.json({ error: "messages array required" }, { status: 400 });
}
// Get child's profile context
let context = "";
if (childId) {
const children = await sql.unsafe(
`SELECT name, birth_date, sex FROM children WHERE id = $1`,
[childId]
);
if (children.length > 0) {
const child = children[0];
const age = calculateAge(child.birth_date);
context = `The child's name is ${child.name}, they are ${age} old. `;
}
}
// Build messages with system prompt
const systemMessage = {
role: "system",
content: `You are Tia, a helpful baby care assistant. ${context} Give caring, practical advice for new parents. Keep responses brief and helpful.`,
};
const allMessages = [systemMessage, ...messages];
// Call MiniMax API directly
const response = await fetch(`${MINIMAX_BASE_URL}/text/chatcompletion_v2`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${MINIMAX_API_KEY}`,
},
body: JSON.stringify({
model: "MiniMax-Text-01",
messages: allMessages,
max_tokens: 500,
}),
});
if (!response.ok) {
const error = await response.text();
return NextResponse.json({ error: "MiniMax error: " + error }, { status: response.status });
}
const data = await response.json();
// MiniMax response format
const reply = data.choices?.[0]?.message?.content
|| data.choices?.[0]?.delta?.content
|| "Sorry, I couldn't get a response.";
return NextResponse.json({ reply });
} catch (error) {
console.error(error);
return NextResponse.json({ error: String(error) }, { status: 500 });
}
}
function calculateAge(birthDate: string) {
const birth = new Date(birthDate);
const now = new Date();
const days = Math.floor((now.getTime() - birth.getTime()) / (1000 * 60 * 60 * 24));
const months = Math.floor(days / 30);
const years = Math.floor(months / 12);
if (years > 0) return `${years} year${years > 1 ? "s" : ""} old`;
if (months > 0) return `${months} month${months > 1 ? "s" : ""} old`;
return `${days} day${days > 1 ? "s" : ""} old`;
}