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

72 lines
No EOL
2.4 KiB
TypeScript

import { NextResponse } from "next/server";
import { sql } from "@/db";
const LITELLM_URL = process.env.LITELLM_URL || "https://litellm-gateway.manohargupta.com";
const LITELLM_KEY = process.env.LITELLM_KEY || "sk-tiger-gateway-289bf7d1cf0c0b12ff5ccf48d95ff3c3";
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 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. `;
}
}
const systemMessage = {
role: "system",
content: `You are Tia, a friendly baby care assistant. Give caring, practical advice for new parents. Keep responses brief and helpful.`,
};
// Call LiteLLM
const response = await fetch(`${LITELLM_URL}/v1/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${LITELLM_KEY}`,
},
body: JSON.stringify({
model: "tiger-minimax",
messages: [systemMessage, ...messages],
max_tokens: 500,
}),
});
if (!response.ok) {
const error = await response.text();
return NextResponse.json({ error: error }, { status: response.status });
}
const data = await response.json();
return NextResponse.json({ reply: data.choices?.[0]?.message?.content });
} 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`;
}