Programa las tareas de un agente o deja que el agente programe sus próximas tareas.
Usa automatizaciones programadas para iniciar sesiones de agente según un horario cron. También puedes habilitar la herramienta automations para que tus agentes programen tareas mientras trabajan.
Automatiza sesiones con un horario cron
Usa una expresión cron y una zona horaria para iniciar sesiones nuevas o continuar una sesión existente.
Permite que los agentes creen automatizaciones
Agrega la herramienta automations para que un agente pueda programar tareas de seguimiento en su sesión actual.
Monitorea las invocaciones de una automatización
Cada invocación registra un intento de enviar una tarea a una sesión. Consulta el estado de la invocación y el ID de la sesión.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import OpenAI from"openai";constclient=newOpenAI();constsession=await client.beta.agents.sessions.create({ agent: { model: "gpt-6-astra", instructions:"Use automations to schedule tasks requested by the user. Delegate each scheduled task to a subagent and ask for a concise result. Keep the goal, schedule, and useful summaries in the main session. Adjust or stop schedules when the user asks.", tools: [{ type: "automations" }], multi_agent: { enabled: true }, }, environment: { type: "openai_hosted" }, input:"Every day at 10 AM in America/New_York, review the goals we discuss here and suggest the next actions I could take.",});console.log(session.id);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22from openai import OpenAIclient = OpenAI()session = client.beta.agents.sessions.create( agent={ "model": "gpt-6-astra", "instructions": ( "Use automations to schedule tasks requested by the user. " "Delegate each scheduled task to a subagent and ask for a concise result. " "Keep the goal, schedule, and useful summaries in the main session. " "Adjust or stop schedules when the user asks." ), "multi_agent": {"enabled": True}, "tools": [{"type": "automations"}], }, environment={"type": "openai_hosted"}, input=( "Every day at 10 AM in America/New_York, review the goals we discuss here " "and suggest the next actions I could take." ),)print(session.id)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32import ( "context" "fmt" "github.com/openai/openai-go/v3")ctx := context.Background()client := openai.NewClient()session, err := client.Beta.Agents.Sessions.New(ctx, openai.BetaAgentSessionNewParams{ Agent: openai.BetaAgentSessionNewParamsAgent{ Model: openai.String("gpt-6-astra"), Instructions: openai.String("Use automations to schedule tasks requested by the user. Delegate each scheduled task to a subagent and ask for a concise result. Keep the goal, schedule, and useful summaries in the main session. Adjust or stop schedules when the user asks."), MultiAgent: openai.MultiAgentConfigParam{ Enabled: true, }, Tools: []openai.AgentToolParamUnion{ {OfParamAutomations: &openai.AgentToolParamAutomations{}}, }, }, Environment: openai.EnvironmentParamUnion{ OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{}, }, Input: openai.BetaAgentSessionNewParamsInputUnion{ OfString: openai.String("Every day at 10 AM in America/New_York, review the goals we discuss here and suggest the next actions I could take."), }, })if err != nil { panic(err)}fmt.Println(session.ID)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27import com.openai.client.OpenAIClient;import com.openai.client.okhttp.OpenAIOkHttpClient;import com.openai.models.beta.agents.EnvironmentParam;import com.openai.models.beta.agents.MultiAgentConfigParam;import com.openai.models.beta.agents.sessions.SessionCreateParams;OpenAIClient client = OpenAIOkHttpClient.fromEnv();var session = client .beta() .agents() .sessions() .create( SessionCreateParams.builder() .agent( SessionCreateParams.Agent.builder() .model("gpt-6-astra") .instructions( "Use automations to schedule tasks requested by the user. Delegate each scheduled task to a subagent and ask for a concise result. Keep the goal, schedule, and useful summaries in the main session. Adjust or stop schedules when the user asks.") .multiAgent(MultiAgentConfigParam.builder().enabled(true).build()) .addToolAutomations() .build()) .environment(EnvironmentParam.OpenAIHosted.builder().build()) .input( "Every day at 10 AM in America/New_York, review the goals we discuss here and suggest the next actions I could take.") .build());System.out.println(session.id());
1
2
3
4
5
6
7
8
9
10
11
12
13
14require "openai"client = OpenAI::Client.newsession = client.beta.agents.sessions.create( agent: { model: "gpt-6-astra", instructions: "Use automations to schedule tasks requested by the user. Delegate each scheduled task to a subagent and ask for a concise result. Keep the goal, schedule, and useful summaries in the main session. Adjust or stop schedules when the user asks.", multi_agent: { enabled: true }, tools: [{ type: "automations" }] }, environment: { type: "openai_hosted" }, input: "Every day at 10 AM in America/New_York, review the goals we discuss here and suggest the next actions I could take.")puts session.id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16curl https://api.openai.com/v1/agents/sessions \ -H "OpenAI-Beta: agents=v1" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "agent": { "model": "gpt-6-astra", "instructions": "Use automations to schedule tasks requested by the user. Delegate each scheduled task to a subagent and ask for a concise result. Keep the goal, schedule, and useful summaries in the main session. Adjust or stop schedules when the user asks.", "tools": [{ "type": "automations" }], "multi_agent": { "enabled": true } }, "environment": { "type": "openai_hosted" }, "input": "Every day at 10 AM in America/New_York, review the goals we discuss here and suggest the next actions I could take." }'
Una automatización guarda la programación de las tareas de un agente. La API de agentes almacena esa programación y envía cada tarea a la sesión de destino:
Define la tarea. Elige cuándo debe ejecutarse y si cada ejecución inicia una sesión nueva o continúa una existente.
Envía la tarea. Cada ejecución crea una invocación que registra el intento de enviar la tarea a la sesión de destino. Si esa sesión está ocupada, la tarea queda en espera.
Consulta el resultado. El agente trabaja con las herramientas y el contexto de la sesión. Sigue los eventos de la sesión para monitorear el progreso y obtener los resultados. Que la sesión reciba la tarea no significa que el agente haya terminado el trabajo.
Tu aplicación puede crear, actualizar, pausar o eliminar programaciones mediante la API. Si habilitas la herramienta automations, el agente también puede programar su próxima comprobación en la sesión actual.
Elige la sesión y el horario
Elige el destino según si la tarea necesita el historial de la conversación:
Destino
Cuándo usarlo
Configuración requerida
new_session
Tareas independientes, como una revisión mensual de gastos.
Un agente, un entorno y mensajes iniciales en target.input.
existing_session
Tareas de seguimiento que requieren los resultados anteriores de la sesión.
Un ID de sesión y el texto del recordatorio en target.instructions.
Elige el horario independientemente del destino:
Tipo
Campos de programación
Ejemplo
periodic
expression y timezone
Todos los días a las 10 a. m. en America/New_York.
once
run_at
Una sola comprobación en un momento futuro indicado mediante una marca de tiempo Unix en segundos.
Ambos tipos de programación funcionan con cualquiera de los destinos. Al crear una automatización, esta se guarda con el estado active. La tarea no se ejecuta de inmediato. La primera ejecución de una automatización periódica se programa para la próxima hora que coincida con la expresión cron.
Programa sugerencias diarias
Antes de crear la automatización, crea un agente con las instrucciones y las herramientas necesarias para la tarea, incluido el acceso al calendario, las tareas y los mensajes del usuario. Consulta Reutiliza un agente en varias sesiones.
Los SDK incluyen el encabezado OpenAI-Beta: agents=v1. Inclúyelo cuando llames a la API con cURL.
En este ejemplo se crea una automatización que inicia una sesión nueva todos los días a las 10 a. m., hora de Nueva York:
Programa sugerencias diarias
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26import OpenAI from "openai";const client = new OpenAI();const automation = await client.beta.agents.automations.create({ type: "periodic", name: "Daily suggestions", expression: "0 10 * * *", timezone: "America/New_York", target: { type: "new_session", agent_id: "agt_123", environment: { type: "openai_hosted" }, input: [ { role: "user", content: [ { type: "input_text", text: "Review my calendar, tasks, and recent messages for today. Suggest the most useful actions I could take today, with a short reason for each.", }, ], }, ], },});console.log(automation);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30from openai import OpenAIclient = OpenAI()automation = client.beta.agents.automations.create(type="periodic",name="Daily suggestions",expression="0 10 * * *",timezone="America/New_York",target={"type": "new_session","agent_id": "agt_123","environment": {"type": "openai_hosted"},"input": [ {"role": "user","content": [ {"type": "input_text","text": ("Review my calendar, tasks, and recent messages for today. ""Suggest the most useful actions I could take today, ""with a short reason for each." ), } ], } ], },)print(automation.to_json())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42import ( "context" "fmt" "github.com/openai/openai-go/v3")ctx := context.Background()client := openai.NewClient()automation, err := client.Beta.Agents.Automations.New(ctx, openai.BetaAgentAutomationNewParams{ CreateAutomationParams: openai.AutomationScheduleParamUnion{ OfParamPeriodic: &openai.AutomationScheduleParamPeriodic{ Name: "Daily suggestions", Expression: "0 10 * * *", Timezone: "America/New_York", Target: openai.AutomationTargetParamUnion{ OfParamNewSession: &openai.AutomationTargetParamNewSession{ AgentID: openai.String("agt_123"), Environment: openai.EnvironmentParamUnion{ OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{}, }, Input: []openai.AgentSessionInputMessageParam{ { Content: []openai.InputContentParamUnion{ { OfParamInputText: &openai.InputContentParamInputText{ Text: "Review my calendar, tasks, and recent messages for today. Suggest the most useful actions I could take today, with a short reason for each.", }, }, }, }, }, }, }, }, }, })if err != nil { panic(err)}fmt.Println(automation.ID)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34import com.openai.client.OpenAIClient;import com.openai.client.okhttp.OpenAIOkHttpClient;import com.openai.models.beta.agents.AgentSessionInputMessageParam;import com.openai.models.beta.agents.EnvironmentParam;import com.openai.models.beta.agents.automations.AutomationCreateParams;import com.openai.models.beta.agents.automations.AutomationScheduleParam;import com.openai.models.beta.agents.automations.AutomationTargetParam;OpenAIClient client = OpenAIOkHttpClient.fromEnv();var automation = client .beta() .agents() .automations() .create( AutomationCreateParams.builder() .automationScheduleParam( AutomationScheduleParam.Periodic.builder() .name("Daily suggestions") .expression("0 10 * * *") .timezone("America/New_York") .target( AutomationTargetParam.NewSession.builder() .agentId("agt_123") .environment(EnvironmentParam.OpenAIHosted.builder().build()) .addInput( AgentSessionInputMessageParam.builder() .addInputTextContent( "Review my calendar, tasks, and recent messages for today. Suggest the most useful actions I could take today, with a short reason for each.") .build()) .build()) .build()) .build());System.out.println(automation);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28require "openai"client = OpenAI::Client.newautomation = client.beta.agents.automations.create( create_automation_params: { type: "periodic", name: "Daily suggestions", expression: "0 10 * * *", timezone: "America/New_York", target: { type: "new_session", agent_id: "agt_123", environment: { type: "openai_hosted" }, input: [ { role: "user", content: [ { type: "input_text", text: "Review my calendar, tasks, and recent messages for today. Suggest the most useful actions I could take today, with a short reason for each." } ] } ] } })puts automation.id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28curl https://api.openai.com/v1/agents/automations \ -H "OpenAI-Beta: agents=v1" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "periodic", "name": "Daily suggestions", "expression": "0 10 * * *", "timezone": "America/New_York", "target": { "type": "new_session", "agent_id": "agt_123", "environment": { "type": "openai_hosted" }, "input": [ { "role": "user", "content": [ { "type": "input_text", "text": "Review my calendar, tasks, and recent messages for today. Suggest the most useful actions I could take today, with a short reason for each." } ] } ] } }'
Guarda el id de la automatización que devuelve la API para consultar o administrar la programación más adelante. Cada invocación inicia una conversación nueva. La configuración del entorno del ejemplo anterior aprovisiona un sandbox alojado en OpenAI para esa sesión.
Puedes especificar la configuración del agente directamente en target.agent en lugar de usar un target.agent_id guardado. Especifica exactamente uno de estos campos. Coloca los mensajes iniciales en target.input, no en el nivel superior de la solicitud. Incluye al menos un mensaje con texto no vacío o con la URL de una imagen.
Revisa los gastos cada mes
Puedes seguir los mismos pasos para revisar los gastos mensuales. Dale al agente guardado acceso a los registros financieros del usuario y programa una sesión nueva para las 9 a. m. del primer día de cada mes:
Programa una revisión mensual de gastos
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26import OpenAI from "openai";const client = new OpenAI();const automation = await client.beta.agents.automations.create({ type: "periodic", name: "Monthly spending review", expression: "0 9 1 * *", timezone: "America/New_York", target: { type: "new_session", agent_id: "agt_123", environment: { type: "openai_hosted" }, input: [ { role: "user", content: [ { type: "input_text", text: "Review my spending for the previous month. Flag unused subscriptions, price increases, and other potential savings for me to review.", }, ], }, ], },});console.log(automation);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30from openai import OpenAIclient = OpenAI()automation = client.beta.agents.automations.create(type="periodic",name="Monthly spending review",expression="0 9 1 * *",timezone="America/New_York",target={"type": "new_session","agent_id": "agt_123","environment": {"type": "openai_hosted"},"input": [ {"role": "user","content": [ {"type": "input_text","text": ("Review my spending for the previous month. Flag unused ""subscriptions, price increases, and other potential ""savings for me to review." ), } ], } ], },)print(automation.to_json())
Usa una expresión cron de cinco campos y especifica la zona horaria por su nombre:
Expresión
Horario
0 10 * * *
Todos los días a las 10 a. m.
0 */2 * * *
Cada dos horas
0 9 1 * *
El primer día de cada mes a las 9 a. m.
0 9 * * MON-FRI
De lunes a viernes a las 9 a. m.
La zona horaria determina cómo se interpreta la expresión. Usa UTC para un horario en UTC o una zona horaria de IANA como America/New_York para un horario local. No incluyas run_at en una automatización periódica.
Un horario cron se rige por la hora de la zona horaria seleccionada. Por ejemplo, 0 */3 * * * programa ejecuciones a la medianoche, a las 3 a. m., a las 6 a. m. y así sucesivamente cada tres horas. El intervalo no se cuenta desde la creación de la automatización.
La programación indica la hora prevista. La API de agentes agrega un pequeño retraso aleatorio a las ejecuciones recurrentes para distribuir la carga. La espera puede prolongarse si la sesión de destino está ocupada.
Continúa una sesión existente
Usa una sesión existente cuando el agente necesite resultados anteriores, mensajes o trabajo guardado. Por ejemplo, una sesión dedicada a planear una cena puede conservar las preferencias de restaurantes y los resultados de consultas anteriores de disponibilidad.
Así puedes consultar la disponibilidad de mesas cada dos horas en esa sesión:
Consulta la disponibilidad de mesas en restaurantes
Cada invocación entrega las instrucciones guardadas como una notificación de la automatización a la misma sesión, con la configuración actual del agente y el estado guardado de la sesión. La notificación es independiente de los mensajes nuevos del usuario.
Si la sesión está ocupada, la entrega queda en espera hasta que esté disponible. Una ejecución programada no interrumpe el turno activo ni proporciona un resultado de herramienta o una aprobación pendientes. Tu aplicación debe seguir gestionando las acciones requeridas.
Programa una sola comprobación
Para una sola tarea de seguimiento, usa type: "once" con run_at. El valor debe ser una marca de tiempo Unix entera en segundos que corresponda a un momento futuro. No incluyas expression ni timezone.
Programa una comprobación para el 1 de enero de 2027 a las 9 a. m. UTC:
Programa una sola ejecución del agente
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15import OpenAI from "openai";const client = new OpenAI();const automation = await client.beta.agents.automations.create({ type: "once", name: "Check restaurant reply", run_at: 1798794000, target: { type: "existing_session", session_id: "sess_123", instructions: "Check whether the restaurant replied about our booking. Summarize any changes to the dinner plans.", },});console.log(automation);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17from openai import OpenAIclient = OpenAI()automation = client.beta.agents.automations.create(type="once",name="Check restaurant reply",run_at=1798794000,target={"type": "existing_session","session_id": "sess_123","instructions": ("Check whether the restaurant replied about our booking. ""Summarize any changes to the dinner plans." ), },)print(automation.to_json())
Una vez completada una programación de ejecución única, no quedan más ejecuciones programadas. Aún puedes invocar la automatización manualmente o crear otra para programar una nueva tarea de seguimiento.
Permite que el agente programe tareas de seguimiento
Agrega automations a las herramientas del agente para que pueda programar las tareas que solicite el usuario. En este ejemplo también se habilitan los subagentes para que el agente principal pueda delegar cada tarea programada y conservar un resumen breve del resultado:
Permite que los agentes programen tareas
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import OpenAI from "openai";const client = new OpenAI();const session = await client.beta.agents.sessions.create({ agent: { model: "gpt-6-astra", instructions: "Use automations to schedule tasks requested by the user. Delegate each scheduled task to a subagent and ask for a concise result. Keep the goal, schedule, and useful summaries in the main session. Adjust or stop schedules when the user asks.", tools: [{ type: "automations" }], multi_agent: { enabled: true }, }, environment: { type: "openai_hosted" }, input: "Every day at 10 AM in America/New_York, review the goals we discuss here and suggest the next actions I could take.",});console.log(session.id);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22from openai import OpenAIclient = OpenAI()session = client.beta.agents.sessions.create(agent={"model": "gpt-6-astra","instructions": ("Use automations to schedule tasks requested by the user. ""Delegate each scheduled task to a subagent and ask for a concise result. ""Keep the goal, schedule, and useful summaries in the main session. ""Adjust or stop schedules when the user asks." ),"multi_agent": {"enabled": True},"tools": [{"type": "automations"}], },environment={"type": "openai_hosted"},input=("Every day at 10 AM in America/New_York, review the goals we discuss here ""and suggest the next actions I could take." ),)print(session.id)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32import ( "context" "fmt" "github.com/openai/openai-go/v3")ctx := context.Background()client := openai.NewClient()session, err := client.Beta.Agents.Sessions.New(ctx, openai.BetaAgentSessionNewParams{ Agent: openai.BetaAgentSessionNewParamsAgent{ Model: openai.String("gpt-6-astra"), Instructions: openai.String("Use automations to schedule tasks requested by the user. Delegate each scheduled task to a subagent and ask for a concise result. Keep the goal, schedule, and useful summaries in the main session. Adjust or stop schedules when the user asks."), MultiAgent: openai.MultiAgentConfigParam{ Enabled: true, }, Tools: []openai.AgentToolParamUnion{ {OfParamAutomations: &openai.AgentToolParamAutomations{}}, }, }, Environment: openai.EnvironmentParamUnion{ OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{}, }, Input: openai.BetaAgentSessionNewParamsInputUnion{ OfString: openai.String("Every day at 10 AM in America/New_York, review the goals we discuss here and suggest the next actions I could take."), }, })if err != nil { panic(err)}fmt.Println(session.ID)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27import com.openai.client.OpenAIClient;import com.openai.client.okhttp.OpenAIOkHttpClient;import com.openai.models.beta.agents.EnvironmentParam;import com.openai.models.beta.agents.MultiAgentConfigParam;import com.openai.models.beta.agents.sessions.SessionCreateParams;OpenAIClient client = OpenAIOkHttpClient.fromEnv();var session = client .beta() .agents() .sessions() .create( SessionCreateParams.builder() .agent( SessionCreateParams.Agent.builder() .model("gpt-6-astra") .instructions( "Use automations to schedule tasks requested by the user. Delegate each scheduled task to a subagent and ask for a concise result. Keep the goal, schedule, and useful summaries in the main session. Adjust or stop schedules when the user asks.") .multiAgent(MultiAgentConfigParam.builder().enabled(true).build()) .addToolAutomations() .build()) .environment(EnvironmentParam.OpenAIHosted.builder().build()) .input( "Every day at 10 AM in America/New_York, review the goals we discuss here and suggest the next actions I could take.") .build());System.out.println(session.id());
1
2
3
4
5
6
7
8
9
10
11
12
13
14require "openai"client = OpenAI::Client.newsession = client.beta.agents.sessions.create( agent: { model: "gpt-6-astra", instructions: "Use automations to schedule tasks requested by the user. Delegate each scheduled task to a subagent and ask for a concise result. Keep the goal, schedule, and useful summaries in the main session. Adjust or stop schedules when the user asks.", multi_agent: { enabled: true }, tools: [{ type: "automations" }] }, environment: { type: "openai_hosted" }, input: "Every day at 10 AM in America/New_York, review the goals we discuss here and suggest the next actions I could take.")puts session.id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16curl https://api.openai.com/v1/agents/sessions \ -H "OpenAI-Beta: agents=v1" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "agent": { "model": "gpt-6-astra", "instructions": "Use automations to schedule tasks requested by the user. Delegate each scheduled task to a subagent and ask for a concise result. Keep the goal, schedule, and useful summaries in the main session. Adjust or stop schedules when the user asks.", "tools": [{ "type": "automations" }], "multi_agent": { "enabled": true } }, "environment": { "type": "openai_hosted" }, "input": "Every day at 10 AM in America/New_York, review the goals we discuss here and suggest the next actions I could take." }'
Así, el agente puede crear, listar, obtener, actualizar, pausar, reanudar y eliminar sus propias automatizaciones. La API de agentes establece la sesión actual como destino. El agente puede programar ejecuciones únicas o periódicas, pero no puede usar estas herramientas para iniciar una sesión nueva ni administrar las automatizaciones de otra sesión.
Las herramientas solo pueden acceder a las automatizaciones que el agente haya creado en la sesión actual. Tu aplicación puede administrarlas mediante la API junto con las que haya creado la propia aplicación. La API de agentes registra quién creó la automatización en created_by. No envíes ese campo en una solicitud de creación.
La herramienta no está habilitada de forma predeterminada. Tu aplicación puede programar tareas sin habilitarla. Quitar la herramienta de la configuración de un agente no elimina las programaciones guardadas. Puedes pausarlas o eliminarlas mediante la API cuando lo necesites.
Mantén las tareas repetitivas fuera del contexto principal
Para objetivos que requieren trabajo continuo, habilita la orquestación de varios agentes con agent.multi_agent.enabled: true. Pídele al agente principal que conserve el objetivo y la programación, que delegue cada tarea a un subagente y que guarde un resumen breve del resultado. Así, los resultados detallados que generan las herramientas en cada comprobación quedan fuera de la ventana de contexto de la sesión principal.
Por ejemplo, incluye lo siguiente en las instrucciones del agente principal:
Delega cada tarea programada a un subagente. Indícale el objetivo y los resultados anteriores pertinentes, y pídele un resultado conciso. Revísalo, conserva un resumen de lo que sea útil y decide si mantienes, cambias o detienes la programación.
La herramienta automations administra las programaciones. Conserva las demás herramientas y el acceso a los datos que el agente necesita para realizar las tareas programadas.
Programa tareas de seguimiento de la incorporación desde tu aplicación
Tu aplicación también puede crear programaciones en respuesta a sus propios eventos. Por ejemplo, cuando un usuario se registre, inicia una sesión de incorporación y programa la primera tarea de seguimiento para 48 horas después:
Programa una tarea de seguimiento de la incorporación
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15import OpenAI from "openai";const client = new OpenAI();const automation = await client.beta.agents.automations.create({ type: "once", name: "Onboarding follow-up", run_at: Math.floor(Date.now() / 1000) + 48 * 60 * 60, target: { type: "existing_session", session_id: "sess_123", instructions: "Review onboarding progress and send the next onboarding message if the user has not completed onboarding.", },});console.log(automation);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import timefrom openai import OpenAIclient = OpenAI()automation = client.beta.agents.automations.create(type="once",name="Onboarding follow-up",run_at=int(time.time()) +48*60*60,target={"type": "existing_session","session_id": "sess_123","instructions": ("Review onboarding progress and send the next onboarding message ""if the user has not completed onboarding." ), },)print(automation.to_json())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29import com.openai.client.OpenAIClient;import com.openai.client.okhttp.OpenAIOkHttpClient;import com.openai.models.beta.agents.automations.AutomationCreateParams;import com.openai.models.beta.agents.automations.AutomationScheduleParam;import com.openai.models.beta.agents.automations.AutomationTargetParam;import java.time.Duration;import java.time.Instant;OpenAIClient client = OpenAIOkHttpClient.fromEnv();var automation = client .beta() .agents() .automations() .create( AutomationCreateParams.builder() .automationScheduleParam( AutomationScheduleParam.Once.builder() .name("Onboarding follow-up") .runAt(Instant.now().plus(Duration.ofHours(48)).getEpochSecond()) .target( AutomationTargetParam.ExistingSession.builder() .sessionId("sess_123") .instructions( "Review onboarding progress and send the next onboarding message if the user has not completed onboarding.") .build()) .build()) .build());System.out.println(automation);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16require "openai"client = OpenAI::Client.newautomation = client.beta.agents.automations.create( create_automation_params: { type: "once", name: "Onboarding follow-up", run_at: Time.now.to_i + 48 * 60 * 60, target: { type: "existing_session", session_id: "sess_123", instructions: "Review onboarding progress and send the next onboarding message if the user has not completed onboarding." } })puts automation.id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18RUN_AT=$(($(date +%s) + 48 * 60 * 60))curl https://api.openai.com/v1/agents/automations \ -H "OpenAI-Beta: agents=v1" \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d @- <<EOF{ "type": "once", "name": "Onboarding follow-up", "run_at": $RUN_AT, "target": { "type": "existing_session", "session_id": "sess_123", "instructions": "Review onboarding progress and send the next onboarding message if the user has not completed onboarding." } }EOF
Cada vez que se complete una tarea de seguimiento, tu aplicación puede programar otra para 48 horas después. Detén el seguimiento cuando se complete la incorporación o el usuario decida dejar de recibirlo, y elimina cualquier tarea de seguimiento pendiente. Para este intervalo, usa programaciones de ejecución única. Una expresión cron basada en el día del mes no mantiene un intervalo de 48 horas al pasar de un mes a otro.
El agente de incorporación necesita acceso a la información sobre el progreso de la incorporación y a las herramientas de mensajería de la aplicación. Al crear la automatización, se programa la tarea. El mensaje no se envía de inmediato.
Prueba una ejecución y verifica la entrega
Para probar de inmediato una automatización guardada, envía POST /v1/agents/automations/auto_123/invocations sin cuerpo de solicitud. Una invocación manual no cambia la programación guardada ni consume la ejecución programada de una automatización de ejecución única. También funciona cuando la programación está en pausa.
Guarda el ID de invocación que devuelve la API. Consulta esa invocación con GET /v1/agents/automations/auto_123/invocations/ainv_123 u obtén el historial de entregas con GET /v1/agents/automations/auto_123/invocations.
Para ver las ejecuciones anteriores, consulta la lista de invocaciones de la automatización:
El historial contiene las invocaciones ya creadas, pero no incluye todas las ejecuciones futuras. Revisa estos campos:
Campo
Qué revisar
status
Empieza con el valor queued y cambia a completed cuando la entrega se realiza correctamente.
session_id
Identifica la sesión que debes seguir después de la entrega. Puede ser null mientras no haya una sesión disponible.
source.type
manual para una invocación manual o automation para una ejecución programada.
scheduled_at
La hora prevista de la ejecución programada o null para una invocación manual.
Que se complete la entrega no significa que el agente haya terminado la tarea. Si la sesión es nueva, significa que aceptó los datos de entrada iniciales. Si es una sesión existente, significa que aceptó la notificación y la solicitud de iniciar la tarea.
La automatización programa la tarea. Tu aplicación muestra los resultados de la sesión y envía las notificaciones al usuario.
Cambia o detén una programación
Obtén una automatización con GET /v1/agents/automations/auto_123. Consulta la lista de automatizaciones de tu proyecto con GET /v1/agents/automations. Agrega session_id=sess_123 para encontrar las que tengan como destino esa sesión existente.
Actualiza la expresión cron para cambiar la hora de una comprobación recurrente a las 11 a. m.:
Los campos que omitas conservan sus valores. Si envías target, se reemplaza todo el destino, así que incluye todos sus campos obligatorios y conserva su tipo. Actualiza el texto del recordatorio en target.instructions o los mensajes iniciales en target.input. Si un agente creó la automatización, esta debe conservar como destino la sesión en la que se creó.
Haz los cambios antes de la próxima hora programada. Las actualizaciones se aplican a las invocaciones futuras. Una invocación que ya está en cola conserva el destino y los datos de entrada que se guardaron al crearla.
Usa las siguientes operaciones sin cuerpo de solicitud:
Objetivo
Operación
Efecto
Pausar las tareas programadas.
POST /v1/agents/automations/auto_123/pause
Deja en espera las entregas programadas pendientes. La invocación manual sigue disponible.
Reanudar las tareas programadas.
POST /v1/agents/automations/auto_123/resume
Reactiva la programación guardada.
Eliminar la programación.
DELETE /v1/agents/automations/auto_123
Impide futuras invocaciones programadas y manuales.
Pausar o eliminar una automatización no detiene las tareas que una sesión ya haya aceptado ni elimina la sesión. Una entrega que ya está en curso aún puede llegar a su sesión. Para detener la tarea en curso, cancela el turno activo.
Si pasa la hora programada de una automatización de ejecución única mientras está en pausa, establece un nuevo valor futuro para run_at antes de reanudarla. Una automatización de ejecución única que ya se completó no se puede pausar ni reanudar. Crea otra automatización para programar una nueva tarea de seguimiento.