Merge pull request 'Chats de la IA en segundo plano #42' (#50) from issue/42-chats-de-la-ia-en-segundo-plano into main
Reviewed-on: AlexRG/genesis-2#50
This commit was merged in pull request #50.
This commit is contained in:
@@ -3,7 +3,8 @@ import { corsHeaders, withCors } from "./lib/cors.ts";
|
|||||||
import { HttpError, jsonResponse } from "./lib/errors.ts";
|
import { HttpError, jsonResponse } from "./lib/errors.ts";
|
||||||
import { getOpenAI } from "./lib/openai.ts";
|
import { getOpenAI } from "./lib/openai.ts";
|
||||||
import { getSupabaseServiceClient, requireUser } from "./lib/supabase.ts";
|
import { getSupabaseServiceClient, requireUser } from "./lib/supabase.ts";
|
||||||
import { assertUuid, pickSchemaFields, safePlanForPrompt } from "./lib/plan.ts";
|
import { assertUuid, pickSchemaFields, safePlanForPrompt,pickSchemaAsignaturaFields } from "./lib/plan.ts";
|
||||||
|
import { OpenAIService } from "../_shared/openai-service.ts";
|
||||||
|
|
||||||
type CreateBody = {
|
type CreateBody = {
|
||||||
plan_estudio_id: string;
|
plan_estudio_id: string;
|
||||||
@@ -125,20 +126,17 @@ app.post(`${prefix}/plan/conversations`, async (c) => {
|
|||||||
app.post(`${prefix}/asignatura/conversations`, async (c) => {
|
app.post(`${prefix}/asignatura/conversations`, async (c) => {
|
||||||
try {
|
try {
|
||||||
const body = (await c.req.json().catch(() => ({}))) as Partial<CreateBody>;
|
const body = (await c.req.json().catch(() => ({}))) as Partial<CreateBody>;
|
||||||
|
|
||||||
const asignatura_id = body.asignatura_id;
|
const asignatura_id = body.asignatura_id;
|
||||||
assertUuid(asignatura_id ?? "", "asignatura_id");
|
assertUuid(asignatura_id ?? "", "asignatura_id");
|
||||||
|
|
||||||
const instanciador = body.instanciador ?? "unknown";
|
const instanciador = body.instanciador ?? "unknown";
|
||||||
|
const system_prompt = body.system_prompt ??
|
||||||
const system_prompt =
|
"Eres un asistente experto en currículo académico. Si te piden algo ajeno a la asignatura, responde con un refusal.";
|
||||||
body.system_prompt ??
|
|
||||||
"En caso de que te pidan algo que no tiene nada que ver con la asignatura responde con un refusal.";
|
|
||||||
|
|
||||||
const supabase = getSupabaseServiceClient();
|
const supabase = getSupabaseServiceClient();
|
||||||
const openai = getOpenAI();
|
const openai = getOpenAI();
|
||||||
|
|
||||||
// 🔥 Cargar asignatura
|
// 1. Verificar que la asignatura existe
|
||||||
const { data: asignatura, error: asigErr } = await supabase
|
const { data: asignatura, error: asigErr } = await supabase
|
||||||
.from("asignaturas")
|
.from("asignaturas")
|
||||||
.select("*")
|
.select("*")
|
||||||
@@ -146,15 +144,10 @@ app.post(`${prefix}/asignatura/conversations`, async (c) => {
|
|||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (asigErr || !asignatura) {
|
if (asigErr || !asignatura) {
|
||||||
throw new HttpError(
|
throw new HttpError(404, "asignatura_not_found", "Asignatura no encontrada");
|
||||||
404,
|
|
||||||
"asignatura_not_found",
|
|
||||||
"Asignatura no encontrada",
|
|
||||||
asigErr,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🔥 Crear conversación en OpenAI
|
// 2. Crear conversación en OpenAI
|
||||||
const conv = await openai.conversations.create({
|
const conv = await openai.conversations.create({
|
||||||
metadata: {
|
metadata: {
|
||||||
tabla: "asignaturas",
|
tabla: "asignaturas",
|
||||||
@@ -164,28 +157,22 @@ app.post(`${prefix}/asignatura/conversations`, async (c) => {
|
|||||||
items: [{ type: "message", role: "system", content: system_prompt }],
|
items: [{ type: "message", role: "system", content: system_prompt }],
|
||||||
});
|
});
|
||||||
|
|
||||||
// 🔥 Insertar en conversaciones_asignatura
|
// 3. Insertar en conversaciones_asignatura (coincidiendo con tu SQL)
|
||||||
const { data: row, error: insErr } = await supabase
|
const { data: row, error: insErr } = await supabase
|
||||||
.from("conversaciones_asignatura")
|
.from("conversaciones_asignatura")
|
||||||
.insert({
|
.insert({
|
||||||
openai_conversation_id: conv.id,
|
openai_conversation_id: conv.id,
|
||||||
asignatura_id: asignatura.id, // ✅ CORRECTO
|
asignatura_id: asignatura.id,
|
||||||
estado: "ACTIVA",
|
estado: "ACTIVA",
|
||||||
|
conversacion_json: [], // Inicializamos como array vacío para los mensajes
|
||||||
|
// creado_por: user.id // Opcional si tienes el ID del usuario
|
||||||
})
|
})
|
||||||
.select("id, asignatura_id, openai_conversation_id, estado")
|
.select("id, asignatura_id, openai_conversation_id, estado")
|
||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (insErr || !row) {
|
if (insErr || !row) {
|
||||||
try {
|
try { await openai.conversations.delete(conv.id); } catch (_) {}
|
||||||
await openai.conversations.delete(conv.id);
|
throw new HttpError(500, "db_insert_failed", "Error al registrar conversación", insErr);
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
throw new HttpError(
|
|
||||||
500,
|
|
||||||
"db_insert_failed",
|
|
||||||
"No se pudo registrar la conversación",
|
|
||||||
insErr,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return withCors(jsonResponse({ conversation_asignatura: row }, 201));
|
return withCors(jsonResponse({ conversation_asignatura: row }, 201));
|
||||||
@@ -210,389 +197,218 @@ app.post(`${prefix}/conversations/plan/:id/messages`, async (c) => {
|
|||||||
throw new HttpError(400, "bad_input", "content es requerido");
|
throw new HttpError(400, "bad_input", "content es requerido");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log("Iniciando generación en background para mensaje_id:");
|
||||||
const supabase = getSupabaseServiceClient();
|
const supabase = getSupabaseServiceClient();
|
||||||
const openai = getOpenAI();
|
const svc = OpenAIService.fromEnv();
|
||||||
|
|
||||||
// 1. Traer datos de la conversación y el plan
|
// 1. Validar existencia y estado de la conversación
|
||||||
const { data: row, error } = await supabase
|
const { data: row, error } = await supabase
|
||||||
.from("conversaciones_plan")
|
.from("conversaciones_plan")
|
||||||
.select(
|
.select("id, openai_conversation_id, plan_estudio_id, estado, planes_estudio(*, estructuras_plan(definicion))")
|
||||||
"id, openai_conversation_id, plan_estudio_id, estado, planes_estudio(*, estructuras_plan(definicion))",
|
|
||||||
)
|
|
||||||
.eq("id", conversation_plan_id)
|
.eq("id", conversation_plan_id)
|
||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (error || !row) {
|
if (error || !row) throw new HttpError(404, "not_found", "Conversación no encontrada");
|
||||||
throw new HttpError(404, "conversation_not_found", "Conversación no encontrada", error);
|
if (row.estado === "ARCHIVADA") throw new HttpError(409, "archived", "Conversación archivada");
|
||||||
}
|
|
||||||
|
|
||||||
if (row.estado === "ARCHIVADA") {
|
|
||||||
throw new HttpError(409, "already_archived", "La conversación ya está archivada");
|
|
||||||
}
|
|
||||||
|
|
||||||
const plan = (row as any).planes_estudio;
|
const plan = (row as any).planes_estudio;
|
||||||
const definicion = plan?.estructuras_plan?.definicion;
|
const definicion = plan?.estructuras_plan?.definicion;
|
||||||
const wantsStructured = !!definicion;
|
const isStructured = !!definicion;
|
||||||
|
|
||||||
// --- LÓGICA PARA CASO NO ESTRUCTURADO ---
|
// 2. Insertar el mensaje en estado PENDIENTE
|
||||||
if (!wantsStructured) {
|
// Guardamos los metadatos necesarios para procesar la respuesta después
|
||||||
const resp = await openai.responses.create({
|
const { data: mensajeInsertado, error: insertErr } = await supabase
|
||||||
conversation: row.openai_conversation_id,
|
.from("plan_mensajes_ia")
|
||||||
model: CREATE_CHAT_CONVERSATION_NONSTRUCTURED_MODELO,
|
.insert({
|
||||||
input: [
|
conversacion_plan_id:conversation_plan_id,
|
||||||
{
|
enviado_por: "00000000-0000-0000-0000-000000000000",
|
||||||
role: "system",
|
|
||||||
content: `Este es el plan de estudios actual ${JSON.stringify(plan)}. Si la pregunta no tiene que ver con el plan, responde con un refusal.`,
|
|
||||||
},
|
|
||||||
{ role: "user", content: body.content },
|
|
||||||
],
|
|
||||||
text: {
|
|
||||||
format: {
|
|
||||||
type: "json_schema",
|
|
||||||
name: "definicion",
|
|
||||||
schema: {
|
|
||||||
type: "object",
|
|
||||||
properties: {
|
|
||||||
"ai-message": { type: "string" },
|
|
||||||
"is_refusal": { type: "boolean" },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const respuestaJSON = JSON.parse(resp.output_text ?? "{}");
|
|
||||||
|
|
||||||
// Guardar en la nueva tabla aunque no sea estructurado
|
|
||||||
await supabase.from("plan_mensajes_ia").insert({
|
|
||||||
conversacion_plan_id,
|
|
||||||
enviado_por: "00000000-0000-0000-0000-000000000000",
|
|
||||||
mensaje: body.content,
|
mensaje: body.content,
|
||||||
respuesta: respuestaJSON?.["ai-message"] ?? "",
|
campos: body.campos ?? [],
|
||||||
campos: [],
|
estado: "PROCESANDO", // Estado inicial
|
||||||
propuesta: { recommendations: [] },
|
})
|
||||||
is_refusal: !!respuestaJSON.is_refusal,
|
.select()
|
||||||
estado: "COMPLETADO",
|
.single();
|
||||||
});
|
|
||||||
|
|
||||||
return withCors(jsonResponse({ ok: true }));
|
if (insertErr) throw new HttpError(500, "db_error", "No se pudo crear el registro");
|
||||||
}
|
|
||||||
|
|
||||||
// --- LÓGICA PARA CASO ESTRUCTURADO ---
|
// 3. Preparar Schema y Prompt
|
||||||
const schema = pickSchemaFields(definicion, body.campos ?? []);
|
const schema = isStructured ? pickSchemaFields(definicion, body.campos ?? []) : {
|
||||||
const planForPrompt = safePlanForPrompt(plan);
|
type: "object",
|
||||||
const prompt = body.user_prompt ?? body.content;
|
properties: { "ai-message": { type: "string" }, "is_refusal": { type: "boolean" } }
|
||||||
|
};
|
||||||
|
|
||||||
const resp = await openai.responses.create({
|
// 4. Llamada asincrónica a OpenAI con Webhook
|
||||||
|
// Nota: El SDK de OpenAI permite pasar webhooks en ciertos modelos/endpoints
|
||||||
|
console.log("mandando a openaai ");
|
||||||
|
|
||||||
|
const aiResult = await svc.createStructuredResponse({
|
||||||
conversation: row.openai_conversation_id,
|
conversation: row.openai_conversation_id,
|
||||||
model: CREATE_CHAT_CONVERSATION_STRUCTURED_MODELO,
|
model: isStructured ? CREATE_CHAT_CONVERSATION_STRUCTURED_MODELO : CREATE_CHAT_CONVERSATION_NONSTRUCTURED_MODELO,
|
||||||
text: { format: { type: "json_schema", name: "definicion", schema } },
|
background: true, // <--- ESTO ES LO QUE TE FALTABA
|
||||||
|
metadata: {
|
||||||
|
tabla: "plan_mensajes_ia",
|
||||||
|
mensaje_id: String(mensajeInsertado.id), // Siempre string
|
||||||
|
is_structured: String(isStructured)
|
||||||
|
},
|
||||||
|
text: {
|
||||||
|
format: {
|
||||||
|
type: "json_schema",
|
||||||
|
name: "definicion",
|
||||||
|
schema: schema
|
||||||
|
}
|
||||||
|
},
|
||||||
input: [
|
input: [
|
||||||
{
|
{ role: "system", content: `Asistente de plan: ${JSON.stringify(safePlanForPrompt(plan))}` },
|
||||||
role: "system",
|
{ role: "user", content: body.content },
|
||||||
content: `Eres un asistente que ayuda a mejorar este plan: ${JSON.stringify(planForPrompt)}. Si la pregunta no es pertinente, responde con un refusal.`,
|
|
||||||
},
|
|
||||||
{ role: "user", content: prompt },
|
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const respuestaJSON = JSON.parse(resp.output_text ?? "{}");
|
if (!aiResult.ok) {
|
||||||
const refusal = respuestaJSON["is-refusal"] === true;
|
throw new HttpError(500, "openai_error", "No se pudo encolar la respuesta");
|
||||||
delete respuestaJSON["is-refusal"];
|
|
||||||
|
|
||||||
// 2. Construir el objeto de propuestas/recomendaciones
|
|
||||||
const recommendations = resp.output_text
|
|
||||||
? Object.entries(respuestaJSON)
|
|
||||||
.filter(([k]) => k !== "ai-message")
|
|
||||||
.map(([campo_afectado, texto_mejora]) => ({
|
|
||||||
campo_afectado,
|
|
||||||
texto_mejora,
|
|
||||||
aplicada: false,
|
|
||||||
}))
|
|
||||||
: [];
|
|
||||||
|
|
||||||
// 3. Insertar ÚNICAMENTE en plan_mensajes_ia
|
|
||||||
const { error: insertErr } = await supabase
|
|
||||||
.from("plan_mensajes_ia")
|
|
||||||
.insert({
|
|
||||||
conversacion_plan_id: conversation_plan_id,
|
|
||||||
enviado_por: "00000000-0000-0000-0000-000000000000",
|
|
||||||
mensaje: prompt,
|
|
||||||
respuesta: respuestaJSON?.["ai-message"] ?? "",
|
|
||||||
campos: body.campos ?? [],
|
|
||||||
propuesta: { recommendations },
|
|
||||||
is_refusal: refusal,
|
|
||||||
estado: "COMPLETADO",
|
|
||||||
});
|
|
||||||
|
|
||||||
if (insertErr) {
|
|
||||||
throw new HttpError(500, "insert_plan_mensaje_failed", "Error al guardar mensaje", insertErr);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 5. Responder al cliente de inmediato
|
||||||
return withCors(jsonResponse({
|
return withCors(jsonResponse({
|
||||||
ok: true,
|
ok: true,
|
||||||
openai_response_id: resp.id,
|
mensaje_id: mensajeInsertado.id,
|
||||||
|
openai_response_id: aiResult.responseId // Para seguimiento
|
||||||
}));
|
}));
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return withCors(handleErr(err));
|
return withCors(handleErr(err));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
app.post(`${prefix}/conversations/asignatura/:id/messages`, async (c) => {
|
app.post(`${prefix}/conversations/asignatura/:id/messages`, async (c) => {
|
||||||
try {
|
try {
|
||||||
/* const auth = c.req.header("authorization");
|
const conversation_asig_id = c.req.param("id");
|
||||||
const user = await requireUser(auth); */
|
assertUuid(conversation_asig_id, "conversation_asig_id");
|
||||||
|
|
||||||
const conversation_plan_id = c.req.param("id");
|
const body = (await c.req.json().catch(() => ({}))) as Partial<AddMessageBody>;
|
||||||
assertUuid(conversation_plan_id, "conversation_plan_id");
|
if (!body.content) throw new HttpError(400, "bad_input", "content es requerido");
|
||||||
|
|
||||||
const body = (await c.req.json().catch(() => ({}))) as Partial<
|
|
||||||
AddMessageBody
|
|
||||||
>;
|
|
||||||
if (!body.content || typeof body.content !== "string") {
|
|
||||||
throw new HttpError(400, "bad_input", "content es requerido");
|
|
||||||
}
|
|
||||||
|
|
||||||
const supabase = getSupabaseServiceClient();
|
const supabase = getSupabaseServiceClient();
|
||||||
const openai = getOpenAI();
|
const openai = getOpenAI();
|
||||||
|
|
||||||
// Traer conversacion + plan + estructura
|
// 1. Traer datos
|
||||||
const { data: row, error } = await supabase
|
const { data: row, error } = await supabase
|
||||||
.from("conversaciones_asignatura")
|
.from("conversaciones_asignatura")
|
||||||
.select(
|
.select(`*, asignaturas(*, estructuras_asignatura(definicion))`)
|
||||||
"id, openai_conversation_id, asignatura_id, estado, asignaturas(*)"
|
.eq("id", conversation_asig_id)
|
||||||
)
|
.single();
|
||||||
.eq("id", conversation_plan_id)
|
|
||||||
.single();
|
|
||||||
|
|
||||||
if (error || !row) {
|
if (error || !row) throw new HttpError(404, "not_found", "Conversación no encontrada");
|
||||||
throw new HttpError(
|
|
||||||
404,
|
|
||||||
"conversation_not_found",
|
|
||||||
"Conversación no encontrada",
|
|
||||||
error,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (row.estado === "ARCHIVADA") {
|
|
||||||
throw new HttpError(
|
|
||||||
409,
|
|
||||||
"already_archived",
|
|
||||||
"La conversación ya está archivada",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const plan = (row as any).planes_estudio;
|
const asignatura = row.asignaturas;
|
||||||
const definicion = plan?.estructuras_plan?.definicion;
|
const definicion = asignatura?.estructuras_asignatura?.definicion;
|
||||||
|
const wantsStructured = !!definicion && (body.campos?.length ?? 0) > 0;
|
||||||
|
|
||||||
// Si NO hay schema o no piden campos: solo agregamos mensaje y regresamos ok
|
let aiMessage = "";
|
||||||
const wantsStructured = !!definicion;
|
let isRefusal = false;
|
||||||
|
let recommendations: any[] = [];
|
||||||
|
let openAiRespId = "";
|
||||||
|
|
||||||
|
// --- FLUJO A: NO ESTRUCTURADO ---
|
||||||
if (!wantsStructured) {
|
if (!wantsStructured) {
|
||||||
await openai.responses.create({
|
const resp = await openai.responses.create({
|
||||||
conversation: row.openai_conversation_id,
|
conversation: row.openai_conversation_id,
|
||||||
model: CREATE_CHAT_CONVERSATION_NONSTRUCTURED_MODELO,
|
model: CREATE_CHAT_CONVERSATION_NONSTRUCTURED_MODELO,
|
||||||
input: [
|
input: [
|
||||||
{
|
{ role: "system", content: "Eres un experto en diseño curricular." },
|
||||||
role: "system",
|
|
||||||
content: `Este es el plan de estudios actual ${
|
|
||||||
JSON.stringify(plan)
|
|
||||||
}. Si te hacen una pregunta que no tiene nada que ver con el plan de estudio, responde con un refusal.`,
|
|
||||||
},
|
|
||||||
{ role: "user", content: body.content },
|
{ role: "user", content: body.content },
|
||||||
],
|
],
|
||||||
metadata: {
|
|
||||||
usuario: /* user.email ?? user.id ??*/ "unknown",
|
|
||||||
plan_estudio_id: row.plan_estudio_id,
|
|
||||||
},
|
|
||||||
text: {
|
text: {
|
||||||
format: {
|
format: {
|
||||||
type: "json_schema",
|
type: "json_schema",
|
||||||
name: "definicion",
|
name: "respuesta_basica",
|
||||||
|
strict: true,
|
||||||
schema: {
|
schema: {
|
||||||
// Si no hay schema, igual podemos pedir mejoras estructuradas en un campo libre, pero sin validación estricta
|
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
"ai-message": {
|
"ai-message": { type: "string" },
|
||||||
type: "string",
|
"is_refusal": { type: "boolean" },
|
||||||
description:
|
|
||||||
"Mensaje de la IA para el usuario final basado en la solicitud",
|
|
||||||
examples: [
|
|
||||||
"Excelente, actualmente tu plan de estudio tiene una redacción clara, pero podrías mejorar el perfil de ingreso para hacerlo más atractivo.",
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"is_refusal": {
|
|
||||||
type: "boolean",
|
|
||||||
description:
|
|
||||||
"Indica si la respuesta es un refusal (es decir, la pregunta no tiene que ver con el plan de estudio)",
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
|
required: ["ai-message", "is_refusal"],
|
||||||
|
additionalProperties: false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return withCors(jsonResponse({ ok: true }));
|
const resJson = JSON.parse(resp.output_text ?? "{}");
|
||||||
}
|
aiMessage = resJson["ai-message"] ?? "";
|
||||||
|
isRefusal = !!resJson["is_refusal"];
|
||||||
|
openAiRespId = resp.id;
|
||||||
|
|
||||||
// Pedimos respuesta estructurada con responses.create
|
} else {
|
||||||
const schema = pickSchemaFields(definicion, body.campos ?? []);
|
// --- FLUJO B: ESTRUCTURADO ---
|
||||||
const planForPrompt = safePlanForPrompt(plan);
|
const schemaBase = pickSchemaAsignaturaFields(definicion, body.campos ?? []);
|
||||||
|
const finalSchema = {
|
||||||
const model = CREATE_CHAT_CONVERSATION_STRUCTURED_MODELO;
|
type: "object",
|
||||||
const prompt = body.user_prompt ?? body.content;
|
properties: {
|
||||||
|
"ai-message": { type: "string" },
|
||||||
// append message of the user to conversacion_json (which guarantees a JSONB default to '[]')
|
"is_refusal": { type: "boolean" },
|
||||||
/**
|
...schemaBase.properties
|
||||||
* appended includes timestamp, user, prompt and fields (if any)
|
|
||||||
*/
|
|
||||||
|
|
||||||
type AppendedMessage = {
|
|
||||||
timestamp: string;
|
|
||||||
user: string;
|
|
||||||
prompt: string;
|
|
||||||
fields?: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
type AppendedResponse = {
|
|
||||||
timestamp: string;
|
|
||||||
user: "assistant";
|
|
||||||
refusal: boolean;
|
|
||||||
message: string;
|
|
||||||
recommendations?: {
|
|
||||||
texto_mejora: string;
|
|
||||||
campo_afectado: string;
|
|
||||||
aplicada: false;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
type AppendedItem = AppendedMessage | AppendedResponse;
|
|
||||||
|
|
||||||
let appended: AppendedItem = {
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
user: /* user.email ?? user.id ??*/ "unknown",
|
|
||||||
prompt,
|
|
||||||
fields: body.campos,
|
|
||||||
};
|
|
||||||
|
|
||||||
const { error: appendErr } = await supabase.rpc(
|
|
||||||
"append_conversacion_asignatura",
|
|
||||||
{
|
|
||||||
p_id: conversation_plan_id,
|
|
||||||
p_append: appended,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
if (appendErr) {
|
|
||||||
throw new HttpError(
|
|
||||||
500,
|
|
||||||
"append_conversation_failed",
|
|
||||||
"No se pudo agregar el mensaje a la conversación",
|
|
||||||
appendErr,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const resp = await openai.responses.create({
|
|
||||||
conversation: row.openai_conversation_id,
|
|
||||||
model,
|
|
||||||
text: { format: { type: "json_schema", name: "definicion", schema } },
|
|
||||||
metadata: {
|
|
||||||
usuario: /* user.email ?? user.id ??*/ "unknown",
|
|
||||||
plan_estudio_id: row.plan_estudio_id,
|
|
||||||
},
|
|
||||||
input: [
|
|
||||||
{
|
|
||||||
role: "system",
|
|
||||||
content:
|
|
||||||
`Eres un asistente que ayuda a mejorar este plan de estudio: ${
|
|
||||||
JSON.stringify(planForPrompt)
|
|
||||||
}. ` +
|
|
||||||
`Si te hacen una pregunta que no tiene nada que ver con el plan de estudio, responde con un refusal.`,
|
|
||||||
},
|
},
|
||||||
{ role: "user", content: prompt },
|
required: ["ai-message", "is_refusal", ...Object.keys(schemaBase.properties || {})],
|
||||||
],
|
additionalProperties: false
|
||||||
|
};
|
||||||
|
|
||||||
|
const resp = await openai.responses.create({
|
||||||
|
conversation: row.openai_conversation_id,
|
||||||
|
model: CREATE_CHAT_CONVERSATION_STRUCTURED_MODELO,
|
||||||
|
text: {
|
||||||
|
format: { type: "json_schema", name: "mejora_asignatura", strict: true, schema: finalSchema }
|
||||||
|
},
|
||||||
|
input: [
|
||||||
|
{ role: "system", content: `Asistente curricular. Datos: ${JSON.stringify(asignatura)}` },
|
||||||
|
{ role: "user", content: body.content },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const resJson = JSON.parse(resp.output_text ?? "{}");
|
||||||
|
aiMessage = resJson["ai-message"] ?? "";
|
||||||
|
isRefusal = !!resJson["is_refusal"];
|
||||||
|
openAiRespId = resp.id;
|
||||||
|
|
||||||
|
recommendations = Object.entries(resJson)
|
||||||
|
.filter(([k]) => k !== "ai-message" && k !== "is_refusal")
|
||||||
|
.map(([campo, texto]) => ({
|
||||||
|
campo_afectado: campo,
|
||||||
|
texto_mejora: texto,
|
||||||
|
aplicada: false,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Guardar Histórico y Mensaje (Común a ambos flujos)
|
||||||
|
await supabase.rpc("append_conversacion_asignatura", {
|
||||||
|
p_id: conversation_asig_id,
|
||||||
|
p_append: { timestamp: new Date().toISOString(), user: "user", prompt: body.content },
|
||||||
});
|
});
|
||||||
|
|
||||||
const respuestaJSON = JSON.parse(resp.output_text ?? "{}");
|
await supabase.from("asignatura_mensajes_ia").insert({
|
||||||
const refusal = respuestaJSON["is-refusal"] === true;
|
conversacion_asignatura_id: conversation_asig_id,
|
||||||
//remove the is-refusal field from respuestaJSON to avoid confusion
|
mensaje: body.content,
|
||||||
delete respuestaJSON["is-refusal"];
|
respuesta: aiMessage,
|
||||||
|
campos: body.campos ?? [],
|
||||||
// Now an item with the assistant response and the structured data (if any) should be
|
propuesta: { prompt: body.content, respuesta: aiMessage, recommendations },
|
||||||
appended = {
|
is_refusal: isRefusal,
|
||||||
timestamp: new Date().toISOString(),
|
estado: "COMPLETADO",
|
||||||
user: "assistant",
|
enviado_por: "00000000-0000-0000-0000-000000000000",
|
||||||
refusal,
|
});
|
||||||
// the ai-message field is the response
|
|
||||||
message: respuestaJSON?.["ai-message"] ?? "",
|
|
||||||
recommendations: resp.output_text
|
|
||||||
? Object.entries(respuestaJSON).filter(([k]) => k !== "ai-message")
|
|
||||||
.map(
|
|
||||||
([campo_afectado, texto_mejora]) => ({
|
|
||||||
campo_afectado,
|
|
||||||
texto_mejora,
|
|
||||||
aplicada: false,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
: undefined,
|
|
||||||
} as AppendedResponse;
|
|
||||||
|
|
||||||
const { error: appendRespErr } = await supabase.rpc("append_conversacion_asignatura", {
|
|
||||||
p_id: conversation_plan_id,
|
|
||||||
p_append: appended,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Construir propuesta estructurada
|
|
||||||
const propuesta = {
|
|
||||||
prompt,
|
|
||||||
respuesta: respuestaJSON?.["ai-message"] ?? "",
|
|
||||||
recommendations: resp.output_text
|
|
||||||
? Object.entries(respuestaJSON)
|
|
||||||
.filter(([k]) => k !== "ai-message")
|
|
||||||
.map(([campo_afectado, texto_mejora]) => ({
|
|
||||||
campo_afectado,
|
|
||||||
texto_mejora,
|
|
||||||
aplicada: false,
|
|
||||||
}))
|
|
||||||
: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
// Insertar en plan_mensajes_ia
|
|
||||||
const { error: insertErr } = await supabase
|
|
||||||
.from("asignatura_mensajes_ia")
|
|
||||||
.insert({
|
|
||||||
conversacion_asignatura_id: conversation_plan_id,
|
|
||||||
enviado_por: "00000000-0000-0000-0000-000000000000",
|
|
||||||
mensaje: prompt,
|
|
||||||
respuesta: respuestaJSON?.["ai-message"] ?? "",
|
|
||||||
campos: body.campos ?? [],
|
|
||||||
propuesta,
|
|
||||||
is_refusal: refusal,
|
|
||||||
estado: "COMPLETADO",
|
|
||||||
});
|
|
||||||
|
|
||||||
if (insertErr) {
|
|
||||||
throw new HttpError(
|
|
||||||
500,
|
|
||||||
"insert_plan_mensaje_failed",
|
|
||||||
"No se pudo guardar el mensaje en plan_mensajes_ia",
|
|
||||||
insertErr,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (appendRespErr) {
|
|
||||||
throw new HttpError(
|
|
||||||
500,
|
|
||||||
"append_response_failed",
|
|
||||||
"No se pudo agregar la respuesta a la conversación",
|
|
||||||
appendRespErr,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return withCors(jsonResponse({
|
return withCors(jsonResponse({
|
||||||
ok: true,
|
ok: true,
|
||||||
openai_response_id: resp.id,
|
openai_response_id: openAiRespId,
|
||||||
raw: resp.output_text ?? null,
|
ai_message: aiMessage,
|
||||||
|
recommendations
|
||||||
}));
|
}));
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return withCors(handleErr(err));
|
return withCors(handleErr(err));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,6 +46,37 @@ export function pickSchemaFields(
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function pickSchemaAsignaturaFields(
|
||||||
|
definicion: any,
|
||||||
|
campos: string[],
|
||||||
|
) {
|
||||||
|
// Si no hay definición válida, devolvemos un objeto vacío seguro
|
||||||
|
if (!definicion || definicion.type !== "object" || !definicion.properties) {
|
||||||
|
return { type: "object", properties: {}, required: [], additionalProperties: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clonamos para no mutar el original
|
||||||
|
const out = structuredClone(definicion);
|
||||||
|
|
||||||
|
// 1. Filtrar las propiedades: solo las que el usuario pidió en 'campos'
|
||||||
|
const entries = Object.entries(out.properties).filter(([k]) =>
|
||||||
|
campos.includes(k)
|
||||||
|
);
|
||||||
|
out.properties = Object.fromEntries(entries);
|
||||||
|
|
||||||
|
// 2. Filtrar los requeridos: solo si están en el nuevo set de propiedades
|
||||||
|
if (Array.isArray(out.required)) {
|
||||||
|
out.required = out.required.filter((k: string) => campos.includes(k));
|
||||||
|
} else {
|
||||||
|
out.required = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Limpieza de OpenAI: Forzar additionalProperties a false
|
||||||
|
out.additionalProperties = false;
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
export function safePlanForPrompt(plan: any) {
|
export function safePlanForPrompt(plan: any) {
|
||||||
const copy = structuredClone(plan);
|
const copy = structuredClone(plan);
|
||||||
if (copy?.estructuras_plan) delete copy.estructuras_plan;
|
if (copy?.estructuras_plan) delete copy.estructuras_plan;
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
// ./plan_mensajes_ia/index.ts
|
||||||
|
import type { OpenAI } from "openai";
|
||||||
|
|
||||||
|
import type { Json } from "../../_shared/database.types.ts";
|
||||||
|
import { ResponseMetadata } from "../../_shared/utils.ts";
|
||||||
|
import { supabase } from "../../openai-webhook-responses/supabase.ts";
|
||||||
|
|
||||||
|
|
||||||
|
function extractOutputText(response: OpenAI.Responses.Response): string {
|
||||||
|
const direct = (response as unknown as { output_text?: unknown }).output_text;
|
||||||
|
if (typeof direct === "string") return direct;
|
||||||
|
|
||||||
|
const output = (response as unknown as { output?: unknown }).output;
|
||||||
|
if (!Array.isArray(output)) return "";
|
||||||
|
|
||||||
|
// Fallback similar al usado en index.ts
|
||||||
|
try {
|
||||||
|
return output
|
||||||
|
.filter((item) => (item as { type?: unknown })?.type === "message")
|
||||||
|
.flatMap((item) => (item as { content?: unknown })?.content ?? [])
|
||||||
|
.filter((c) => (c as { type?: unknown })?.type === "output_text")
|
||||||
|
.map((c) => String((c as { text?: unknown })?.text ?? ""))
|
||||||
|
.join("");
|
||||||
|
} catch {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handlePlanMensajesResponse(
|
||||||
|
response: OpenAI.Responses.Response,
|
||||||
|
): Promise<void> {
|
||||||
|
const metadata = response.metadata as any;
|
||||||
|
const mensajeId = metadata?.mensaje_id;
|
||||||
|
console.log("ya entre aqui");
|
||||||
|
|
||||||
|
const isStructured = metadata?.is_structured === "true" || metadata?.is_structured === true;
|
||||||
|
if (!mensajeId) {
|
||||||
|
console.warn("No se recibió mensaje_id en la metadata del webhook");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const outputText = extractOutputText(response);
|
||||||
|
if (!outputText) {
|
||||||
|
throw new Error("La respuesta de OpenAI está vacía");
|
||||||
|
}
|
||||||
|
|
||||||
|
let respuestaJSON: any;
|
||||||
|
try {
|
||||||
|
respuestaJSON = JSON.parse(outputText);
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`Error parseando JSON de OpenAI: ${e.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const is_refusal = !!respuestaJSON.is_refusal || respuestaJSON["is-refusal"] === true;
|
||||||
|
|
||||||
|
let recommendations = [];
|
||||||
|
if (isStructured && !is_refusal) {
|
||||||
|
recommendations = Object.entries(respuestaJSON)
|
||||||
|
.filter(([k]) => k !== "ai-message" && k !== "is-refusal" && k !== "is_refusal")
|
||||||
|
.map(([campo, valor]) => ({
|
||||||
|
campo_afectado: campo,
|
||||||
|
texto_mejora: valor,
|
||||||
|
aplicada: false,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
const { error } = await supabase
|
||||||
|
.from("plan_mensajes_ia")
|
||||||
|
.update({
|
||||||
|
respuesta: respuestaJSON["ai-message"] || "",
|
||||||
|
propuesta: { recommendations },
|
||||||
|
is_refusal,
|
||||||
|
estado: "COMPLETADO",
|
||||||
|
})
|
||||||
|
.eq("id", mensajeId);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Error procesando handlePlanMensajesResponse:", { mensajeId, e });
|
||||||
|
// Opcional: Marcar el mensaje como fallido en la tabla si tienes ese estado
|
||||||
|
await supabase
|
||||||
|
.from("plan_mensajes_ia")
|
||||||
|
.update({ estado: "ERROR" })
|
||||||
|
.eq("id", mensajeId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,9 @@ import OpenAI from "openai";
|
|||||||
import { ResponseMetadata } from "../_shared/utils.ts";
|
import { ResponseMetadata } from "../_shared/utils.ts";
|
||||||
import { handlePlanesEstudioResponse } from "./planes_estudio/index.ts";
|
import { handlePlanesEstudioResponse } from "./planes_estudio/index.ts";
|
||||||
import { handleAsignaturasResponse } from "./asignaturas/index.ts";
|
import { handleAsignaturasResponse } from "./asignaturas/index.ts";
|
||||||
|
import { handlePlanMensajesResponse } from "../create-chat-conversation/plan/crear.ts";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
console.log("Starting OpenAI webhook responses function");
|
console.log("Starting OpenAI webhook responses function");
|
||||||
const client = new OpenAI({
|
const client = new OpenAI({
|
||||||
@@ -20,7 +23,8 @@ async function handleCompletedResponse(
|
|||||||
const response_id = event.data.id;
|
const response_id = event.data.id;
|
||||||
const response = await client.responses.retrieve(response_id);
|
const response = await client.responses.retrieve(response_id);
|
||||||
const metadata = response.metadata as ResponseMetadata | null;
|
const metadata = response.metadata as ResponseMetadata | null;
|
||||||
|
console.log(("entre"));
|
||||||
|
|
||||||
if (!metadata || !metadata.tabla) {
|
if (!metadata || !metadata.tabla) {
|
||||||
console.warn("No se recibió metadata o tabla en la respuesta");
|
console.warn("No se recibió metadata o tabla en la respuesta");
|
||||||
return;
|
return;
|
||||||
@@ -33,6 +37,9 @@ async function handleCompletedResponse(
|
|||||||
case "asignaturas":
|
case "asignaturas":
|
||||||
await handleAsignaturasResponse(response);
|
await handleAsignaturasResponse(response);
|
||||||
break;
|
break;
|
||||||
|
case "plan_mensajes_ia":
|
||||||
|
await handlePlanMensajesResponse(response);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
console.warn("Tabla no reconocida:", metadata.tabla);
|
console.warn("Tabla no reconocida:", metadata.tabla);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user