Refactor dependency management and improve error handling in Supabase functions

This commit is contained in:
2026-01-13 15:35:43 -06:00
parent 5ab3c6ca5a
commit 4fc445db61
5 changed files with 257 additions and 116 deletions
+20 -11
View File
@@ -1,7 +1,7 @@
// supabase/functions/ai-structured/index.ts
import OpenAI from "jsr:@openai/openai";
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import OpenAI from'jsr:@openai/openai';
import 'jsr:@supabase/functions-js/edge-runtime.d.ts'
import { createClient } from 'npm:@supabase/supabase-js@2'
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
@@ -142,14 +142,12 @@ Deno.serve(async (req) => {
// Conveniencia top-level
if (payload.input !== undefined && responseCfg.input === undefined) responseCfg.input = payload.input;
if (payload.model && !responseCfg.model) responseCfg.model = payload.model;
if (payload.temperature !== undefined && responseCfg.temperature === undefined) responseCfg.temperature = payload.temperature;
if (payload.conversationId && responseCfg.conversation === undefined) responseCfg.conversation = payload.conversationId;
if (payload.previousResponseId && responseCfg.previous_response_id === undefined) responseCfg.previous_response_id = payload.previousResponseId;
if (payload.reasoning && responseCfg.reasoning === undefined) responseCfg.reasoning = payload.reasoning;
// Defaults
responseCfg.model = responseCfg.model ?? "gpt-5";
responseCfg.temperature = responseCfg.temperature ?? 0.2;
// Regla API: no mezclar conversation + previous_response_id
if (responseCfg.conversation && responseCfg.previous_response_id) {
@@ -271,10 +269,17 @@ Deno.serve(async (req) => {
if (!OPENAI_API_KEY) return json({ ok: false, error: "Missing OPENAI_API_KEY" }, 500);
const openai = new OpenAI({ apiKey: OPENAI_API_KEY });
const resp = await openai.responses.create(responseCfg);
let resp = null;
try {
resp = await openai.responses.create(responseCfg);
} catch (error) {
return json({ ok: false, error: "OpenAI API error", details: (error as Error)?.message ?? String(error) }, 500);
}
const outputText = extractOutputText(resp);
let output: unknown = null;
let outputParseError: string | null = null;
try {
@@ -283,14 +288,18 @@ Deno.serve(async (req) => {
outputParseError = (e as Error)?.message ?? String(e);
}
const conv =
resp?.conversation?.id ??
(typeof resp?.conversation === "string"
? resp.conversation
: responseCfg.conversation ?? null)
return json({
ok: outputParseError ? false : true,
responseId: resp.id,
conversationId:
(resp as any)?.conversation?.id ??
(typeof (resp as any)?.conversation === "string" ? (resp as any).conversation : responseCfg.conversation ?? null),
conversationId: conv,
model: resp.model ?? responseCfg.model,
temperature: resp.temperature ?? responseCfg.temperature,
usage: resp.usage ?? null,
outputText,