Implementar function_call para traer el plan de estudios #8

Open
opened 2026-01-28 15:25:58 +00:00 by alexrg · 2 comments
Owner

Entrada

function proponer_mejora(plan_id, input, campose) {

const plan_id = '4660b774-a6e2-44f4-a340-747b41235c7c';

let input = [
  { role: "user", content: `ID del plan de estudio: ${plan_id}` },
  { role: "user", content: "Mejora el nombre del plan de estudio" },
];

const campos = ['nombre']

Código

const {error, data} = await supabase.from('planes_estudio').select('estructuras_plan (definicion), conversation_id').eq('id', plan_id).single();
if (error) {
  console.error("Error al obtener la definición del plan de estudio:", error);
}
const definicion = data?.estructuras_plan?.definicion;
definicion.properties = Object.fromEntries(campos.map(key => [key, definicion.properties[key]]));
definicion.required = definicion.required.filter((key: string) => campos.includes(key));

const conversation_id = data?.conversation_id;

// 1. Define a list of callable tools for the model
const tools = [
  {
    type: "function",
    name: "obtener_plan_estudio",
    description: "Obtener el plan de estudio por ID.",
    parameters: {
      type: "object",
      properties: {
        id: {
          type: "string",
          description: "El ID del plan de estudio.",
        },
      },
      required: ["id"],
    },
  },
];


// 2. Prompt the model with tools defined
let response = await client.responses.create({
  model: "gpt-5-nano",
  tools,
  input,
});

input.push(...response.output);

// Check if the model decided to call any tool
for (const item of response.output.filter(item => item.type === 'function_call') || []) {
  switch(item.name) {
    case "obtener_plan_estudio":
      // 3. Execute the function logic for obtener_plan_estudio
      const args = JSON.parse(item.arguments);
      const { data, error } = await supabase
        .from('planes_estudio')
        .select('datos')
        .eq('id', args.id)
        .single();

      if (error) {
        throw new Error(`Error al obtener el plan de estudio: ${error.message}`);
      }
      const planEstudio = data?.datos;
    // 4. Add the tool response to the input for the model
    input.push({
      type: "function_call_output",
      call_id: item.call_id,
      output: JSON.stringify(planEstudio)
    });
  }
}

response = await client.responses.create({
  model: "gpt-5-nano",
  instructions: "Propón mejoras solo con la información del plan de estudio obtenido por la herramienta.",
  tools,
  input,
  conversation: conversation_id,
  reasoning: {effort: "high"},

  text: {format: { type: "json_schema", name: "PlanEstudioMejorado", schema: definicion }},
});

console.log("Salida final:", response.output);
}
Entrada ```js function proponer_mejora(plan_id, input, campose) { const plan_id = '4660b774-a6e2-44f4-a340-747b41235c7c'; let input = [ { role: "user", content: `ID del plan de estudio: ${plan_id}` }, { role: "user", content: "Mejora el nombre del plan de estudio" }, ]; const campos = ['nombre'] ``` Código ```ts const {error, data} = await supabase.from('planes_estudio').select('estructuras_plan (definicion), conversation_id').eq('id', plan_id).single(); if (error) { console.error("Error al obtener la definición del plan de estudio:", error); } const definicion = data?.estructuras_plan?.definicion; definicion.properties = Object.fromEntries(campos.map(key => [key, definicion.properties[key]])); definicion.required = definicion.required.filter((key: string) => campos.includes(key)); const conversation_id = data?.conversation_id; // 1. Define a list of callable tools for the model const tools = [ { type: "function", name: "obtener_plan_estudio", description: "Obtener el plan de estudio por ID.", parameters: { type: "object", properties: { id: { type: "string", description: "El ID del plan de estudio.", }, }, required: ["id"], }, }, ]; // 2. Prompt the model with tools defined let response = await client.responses.create({ model: "gpt-5-nano", tools, input, }); input.push(...response.output); // Check if the model decided to call any tool for (const item of response.output.filter(item => item.type === 'function_call') || []) { switch(item.name) { case "obtener_plan_estudio": // 3. Execute the function logic for obtener_plan_estudio const args = JSON.parse(item.arguments); const { data, error } = await supabase .from('planes_estudio') .select('datos') .eq('id', args.id) .single(); if (error) { throw new Error(`Error al obtener el plan de estudio: ${error.message}`); } const planEstudio = data?.datos; // 4. Add the tool response to the input for the model input.push({ type: "function_call_output", call_id: item.call_id, output: JSON.stringify(planEstudio) }); } } response = await client.responses.create({ model: "gpt-5-nano", instructions: "Propón mejoras solo con la información del plan de estudio obtenido por la herramienta.", tools, input, conversation: conversation_id, reasoning: {effort: "high"}, text: {format: { type: "json_schema", name: "PlanEstudioMejorado", schema: definicion }}, }); console.log("Salida final:", response.output); } ```
Guillermo.Arrieta was assigned by alexrg 2026-01-28 15:25:59 +00:00
Author
Owner

Ejemplo de OPENAI

// 1. Define a list of callable tools for the model
const tools = [
  {
    type: "function",
    name: "get_horoscope",
    description: "Get today's horoscope for an astrological sign.",
    parameters: {
      type: "object",
      properties: {
        sign: {
          type: "string",
          description: "An astrological sign like Taurus or Aquarius",
        },
      },
      required: ["sign"],
    },
  },
];

function getHoroscope(sign: string) {
  return sign + " Next Tuesday you will befriend a baby otter.";
}

// Create a running input list we will add to over time
let input = [
  { role: "user", content: "What is my horoscope? I am an Aquarius." },
];

// 2. Prompt the model with tools defined
let response = await client.responses.create({
  model: "gpt-5-nano",
  tools,
  input,
});

input.push(...response.output);

// Check if the model decided to call any tool
response.output?.forEach((item) => {
  if (item.type === "function_call" && item.name === "get_horoscope") {
    // 3. Execute the function logic for get_horoscope
    const args = JSON.parse(item.arguments);
    const horoscope = getHoroscope(args.sign);
    
    // 4. Add the tool response to the input for the model
    input.push({
      type: "function_call_output",
      call_id: item.call_id,
      output: JSON.stringify({ horoscope })
    });
  }
});

console.log(input);


response = await client.responses.create({
  model: "gpt-5-nano",
  instructions: "Respond only with a horoscope generated by a tool.",
  tools,
  input,
});

// 5. The model should be able to give a response!
console.log("Final output:");
console.log(response.output);

# Ejemplo de OPENAI ```ts // 1. Define a list of callable tools for the model const tools = [ { type: "function", name: "get_horoscope", description: "Get today's horoscope for an astrological sign.", parameters: { type: "object", properties: { sign: { type: "string", description: "An astrological sign like Taurus or Aquarius", }, }, required: ["sign"], }, }, ]; function getHoroscope(sign: string) { return sign + " Next Tuesday you will befriend a baby otter."; } // Create a running input list we will add to over time let input = [ { role: "user", content: "What is my horoscope? I am an Aquarius." }, ]; // 2. Prompt the model with tools defined let response = await client.responses.create({ model: "gpt-5-nano", tools, input, }); input.push(...response.output); // Check if the model decided to call any tool response.output?.forEach((item) => { if (item.type === "function_call" && item.name === "get_horoscope") { // 3. Execute the function logic for get_horoscope const args = JSON.parse(item.arguments); const horoscope = getHoroscope(args.sign); // 4. Add the tool response to the input for the model input.push({ type: "function_call_output", call_id: item.call_id, output: JSON.stringify({ horoscope }) }); } }); console.log(input); response = await client.responses.create({ model: "gpt-5-nano", instructions: "Respond only with a horoscope generated by a tool.", tools, input, }); // 5. The model should be able to give a response! console.log("Final output:"); console.log(response.output); ```
Author
Owner

Ejemplo en bruto

const plan_id = '4660b774-a6e2-44f4-a340-747b41235c7c';

let input = [
  { role: "user", content: `ID del asignatura: ${plan_id}` },
  { role: "user", content: "Mejora el nombre del asignatura" },
];

const campos = ['nombre']

// 1. Define a list of callable tools for the model
const tools = [
  {
    type: "function",
    name: "obtener_plan_estudio",
    description: "Obtener el plan de estudio por ID.",
    parameters: {
      type: "object",
      properties: {
        id: {
          type: "string",
          description: "El ID del plan de estudio.",
        },
      },
      required: ["id"],
    },
  },
  {
    type: "function",
    name: "obtener_asignatura",
    description: "Obtener la asignatura por ID.",
    parameters: {
      type: "object",
      properties: {
        id: {
          type: "string",
          description: "El ID del asignatura.",
        },
      },
      required: ["id"],
    },
  },
];


// 2. Prompt the model with tools defined
let response = await client.responses.create({
  model: "gpt-5-nano",
  tools,
  input,
});

input.push(...response.output);
let conversation_id = null, definicion = null;
// Check if the model decided to call any tool
for (const item of response.output.filter(item => item.type === 'function_call') || []) {
  switch(item.name) {
    case "obtener_plan_estudio":
    const {error, data} = await supabase.from('planes_estudio').select('estructuras_plan (definicion), conversation_id').eq('id', plan_id).single();
    if (error) {
    console.error("Error al obtener la definición del plan de estudio:", error);
    }
    definicion = data?.estructuras_plan?.definicion;
    conversation_id = data?.conversation_id;

          // 3. Execute the function logic for obtener_plan_estudio
          const args = JSON.parse(item.arguments);
          const { data, error } = await supabase
            .from('planes_estudio')
            .select('datos')
            .eq('id', args.id)
            .single();

          if (error) {
            throw new Error(`Error al obtener el plan de estudio: ${error.message}`);
          }
          const planEstudio = data?.datos;
        // 4. Add the tool response to the input for the model
        input.push({
          type: "function_call_output",
          call_id: item.call_id,
          output: JSON.stringify(planEstudio)
        });
      }
    case "obtener_plan_estudio":
    const {error, data} = await supabase.from('planes_estudio').select('estructuras_asignatura (definicion), conversation_id').eq('id', plan_id).single();
    if (error) {
    console.error("Error al obtener la definición del plan de estudio:", error);
    }
    definicion = data?.estructuras_asignatura?.definicion;
    conversation_id = data?.conversation_id;

          // 3. Execute the function logic for obtener_plan_estudio
          const args = JSON.parse(item.arguments);
          const { data, error } = await supabase
            .from('planes_estudio')
            .select('datos')
            .eq('id', args.id)
            .single();

          if (error) {
            throw new Error(`Error al obtener el plan de estudio: ${error.message}`);
          }
          const planEstudio = data?.datos;
        // 4. Add the tool response to the input for the model
        input.push({
          type: "function_call_output",
          call_id: item.call_id,
          output: JSON.stringify(planEstudio)
        });
      }
}
definicion.properties = Object.fromEntries(campos.map(key => [key, definicion.properties[key]]));
definicion.required = definicion.required.filter((key: string) => campos.includes(key));

response = await client.responses.create({
  model: "gpt-5-nano",
  instructions: "Propón mejoras solo con la información del plan de estudio obtenido por la herramienta.",
  tools,
  input,
  conversation: conversation_id,
  reasoning: {effort: "high"},

  text: {format: { type: "json_schema", name: "PlanEstudioMejorado", schema: definicion }},
});

console.log("Salida final:", response.output);
# Ejemplo en bruto ```js const plan_id = '4660b774-a6e2-44f4-a340-747b41235c7c'; let input = [ { role: "user", content: `ID del asignatura: ${plan_id}` }, { role: "user", content: "Mejora el nombre del asignatura" }, ]; const campos = ['nombre'] // 1. Define a list of callable tools for the model const tools = [ { type: "function", name: "obtener_plan_estudio", description: "Obtener el plan de estudio por ID.", parameters: { type: "object", properties: { id: { type: "string", description: "El ID del plan de estudio.", }, }, required: ["id"], }, }, { type: "function", name: "obtener_asignatura", description: "Obtener la asignatura por ID.", parameters: { type: "object", properties: { id: { type: "string", description: "El ID del asignatura.", }, }, required: ["id"], }, }, ]; // 2. Prompt the model with tools defined let response = await client.responses.create({ model: "gpt-5-nano", tools, input, }); input.push(...response.output); let conversation_id = null, definicion = null; // Check if the model decided to call any tool for (const item of response.output.filter(item => item.type === 'function_call') || []) { switch(item.name) { case "obtener_plan_estudio": const {error, data} = await supabase.from('planes_estudio').select('estructuras_plan (definicion), conversation_id').eq('id', plan_id).single(); if (error) { console.error("Error al obtener la definición del plan de estudio:", error); } definicion = data?.estructuras_plan?.definicion; conversation_id = data?.conversation_id; // 3. Execute the function logic for obtener_plan_estudio const args = JSON.parse(item.arguments); const { data, error } = await supabase .from('planes_estudio') .select('datos') .eq('id', args.id) .single(); if (error) { throw new Error(`Error al obtener el plan de estudio: ${error.message}`); } const planEstudio = data?.datos; // 4. Add the tool response to the input for the model input.push({ type: "function_call_output", call_id: item.call_id, output: JSON.stringify(planEstudio) }); } case "obtener_plan_estudio": const {error, data} = await supabase.from('planes_estudio').select('estructuras_asignatura (definicion), conversation_id').eq('id', plan_id).single(); if (error) { console.error("Error al obtener la definición del plan de estudio:", error); } definicion = data?.estructuras_asignatura?.definicion; conversation_id = data?.conversation_id; // 3. Execute the function logic for obtener_plan_estudio const args = JSON.parse(item.arguments); const { data, error } = await supabase .from('planes_estudio') .select('datos') .eq('id', args.id) .single(); if (error) { throw new Error(`Error al obtener el plan de estudio: ${error.message}`); } const planEstudio = data?.datos; // 4. Add the tool response to the input for the model input.push({ type: "function_call_output", call_id: item.call_id, output: JSON.stringify(planEstudio) }); } } definicion.properties = Object.fromEntries(campos.map(key => [key, definicion.properties[key]])); definicion.required = definicion.required.filter((key: string) => campos.includes(key)); response = await client.responses.create({ model: "gpt-5-nano", instructions: "Propón mejoras solo con la información del plan de estudio obtenido por la herramienta.", tools, input, conversation: conversation_id, reasoning: {effort: "high"}, text: {format: { type: "json_schema", name: "PlanEstudioMejorado", schema: definicion }}, }); console.log("Salida final:", response.output); ```
Sign in to join this conversation.