OpenAI Agents API 定时自动化

2026-11-19 15:38 更新

定时自动化可按 cron 计划启动智能体会话,也可在既有会话中安排后续任务。为智能体启用 automations 工具后,它可以在工作过程中安排跟进。每次触发都会生成一条调用记录(invocation),可以查看投递状态和接收任务的会话 ID。

按 cron 计划启动或继续会话

TypeScript

// 创建每天启动一次新会话的自动化计划
import OpenAI from "openai";

const client = new OpenAI();
const automation = await client.beta.agents.automations.create({
  type: "periodic",
  name: "每日会话",
  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: "总结当前情况和下一步行动。",
          },
        ],
      },
    ],
  },
});
console.log(automation);

Python

## 创建每天启动一次新会话的自动化计划
from openai import OpenAI

client = OpenAI()
automation = client.beta.agents.automations.create(
    type="periodic",
    name="每日会话",
    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": "总结当前情况和下一步行动。",
                    }
                ],
            }
        ],
    },
)
print(automation.to_json())

Go

// 创建每天启动一次新会话的自动化计划
import (
    "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:       "每日会话",
                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: "总结当前情况和下一步行动。",
                                        },
                                    },
                                },
                            },
                        },
                    },
                },
            },
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(automation.ID)

Java

// 创建每天启动一次新会话的自动化计划
import 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("每日会话")
                        .expression("0 10 * * *")
                        .timezone("America/New_York")
                        .target(
                            AutomationTargetParam.NewSession.builder()
                                .agentId("agt_123")
                                .environment(EnvironmentParam.OpenAIHosted.builder().build())
                                .addInput(
                                    AgentSessionInputMessageParam.builder()
                                        .addInputTextContent(
                                            "总结当前情况和下一步行动。")
                                        .build())
                                .build())
                        .build())
                .build());
System.out.println(automation);

Ruby

## 创建每天启动一次新会话的自动化计划
require "openai"

client = OpenAI::Client.new
automation = client.beta.agents.automations.create(
  create_automation_params: {
    type: "periodic",
    name: "每日会话",
    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: "总结当前情况和下一步行动。"
            }
          ]
        }
      ]
    }
  }
)
puts automation.id

cURL

## 创建每天启动一次新会话的自动化计划
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 '{
    "type": "periodic",
    "name": "每日会话",
    "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": "总结当前情况和下一步行动。"
            }
          ]
        }
      ]
    }
  }'

让智能体创建定时任务

TypeScript

// 为会话启用自动化和子智能体工具
import OpenAI from "openai";

const client = new OpenAI();
const session = await client.beta.agents.sessions.create({
  agent: {
    model: "gpt-6-astra",
    instructions:
      "用自动化安排用户请求的任务。将每次定时任务委派给子智能体,要求它简要回报。在主会话中保留目标、计划和有用的摘要。按用户要求调整或停止计划。",
    tools: [{ type: "automations" }],
    multi_agent: { enabled: true },
  },
  environment: { type: "openai_hosted" },
  input:
    "每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,并建议我接下来可以做的事。",
});
console.log(session.id);

Python

## 为会话启用自动化和子智能体工具
from openai import OpenAI

client = OpenAI()
session = client.beta.agents.sessions.create(
    agent={
        "model": "gpt-6-astra",
        "instructions": (
            "用自动化安排用户请求的任务。"
            "将每次定时任务委派给子智能体,要求它简要回报。"
            "在主会话中保留目标、计划和有用的摘要。"
            "按用户要求调整或停止计划。"
        ),
        "multi_agent": {"enabled": True},
        "tools": [{"type": "automations"}],
    },
    environment={"type": "openai_hosted"},
    input=(
        "每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,"
        "并建议我接下来可以做的事。"
    ),
)
print(session.id)

Go

// 为会话启用自动化和子智能体工具
import (
    "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("用自动化安排用户请求的任务。将每次定时任务委派给子智能体,要求它简要回报。在主会话中保留目标、计划和有用的摘要。按用户要求调整或停止计划。"),
            MultiAgent: openai.MultiAgentConfigParam{
                Enabled: true,
            },
            Tools: []openai.AgentToolParamUnion{
                {OfParamAutomations: &openai.AgentToolParamAutomations{}},
            },
        },
        Environment: openai.EnvironmentParamUnion{
            OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{},
        },
        Input: openai.BetaAgentSessionNewParamsInputUnion{
            OfString: openai.String("每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,并建议我接下来可以做的事。"),
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(session.ID)

Java

// 为会话启用自动化和子智能体工具
import 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(
                            "用自动化安排用户请求的任务。将每次定时任务委派给子智能体,要求它简要回报。在主会话中保留目标、计划和有用的摘要。按用户要求调整或停止计划。")
                        .multiAgent(MultiAgentConfigParam.builder().enabled(true).build())
                        .addToolAutomations()
                        .build())
                .environment(EnvironmentParam.OpenAIHosted.builder().build())
                .input(
                    "每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,并建议我接下来可以做的事。")
                .build());
System.out.println(session.id());

Ruby

## 为会话启用自动化和子智能体工具
require "openai"

client = OpenAI::Client.new
session = client.beta.agents.sessions.create(
  agent: {
    model: "gpt-6-astra",
    instructions: "用自动化安排用户请求的任务。将每次定时任务委派给子智能体,要求它简要回报。在主会话中保留目标、计划和有用的摘要。按用户要求调整或停止计划。",
    multi_agent: { enabled: true },
    tools: [{ type: "automations" }]
  },
  environment: { type: "openai_hosted" },
  input: "每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,并建议我接下来可以做的事。"
)
puts session.id

cURL

## 为会话启用自动化和子智能体工具
curl 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": "用自动化安排用户请求的任务。将每次定时任务委派给子智能体,要求它简要回报。在主会话中保留目标、计划和有用的摘要。按用户要求调整或停止计划。",
      "tools": [{ "type": "automations" }],
      "multi_agent": { "enabled": true }
    },
    "environment": {
      "type": "openai_hosted"
    },
    "input": "每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,并建议我接下来可以做的事。"
  }'

查看自动化调用记录

TypeScript

// 列出自动化的调用记录
import OpenAI from "openai";

const client = new OpenAI();
for await (const invocation of client.beta.agents.automations.invocations.list(
  "auto_123"
)) {
  console.log(invocation.id, invocation.status, invocation.session_id);
}

Python

## 列出自动化的调用记录
from openai import OpenAI

client = OpenAI()
invocations = client.beta.agents.automations.invocations.list(automation_id="auto_123")
for invocation in invocations:
    print(invocation.id, invocation.status, invocation.session_id)

Go

// 列出自动化的调用记录
import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
)

ctx := context.Background()
client := openai.NewClient()
invocations := client.Beta.Agents.Automations.Invocations.ListAutoPaging(ctx, "auto_123",
    openai.BetaAgentAutomationInvocationListParams{})
for invocations.Next() {
    invocation := invocations.Current()
    fmt.Println(invocation.ID, invocation.Status, invocation.SessionID)
}
if err := invocations.Err(); err != nil {
    panic(err)
}

Java

// 列出自动化的调用记录
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.agents.automations.invocations.InvocationListParams;

OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var invocations =
    client
        .beta()
        .agents()
        .automations()
        .invocations()
        .list(InvocationListParams.builder().automationId("auto_123").build());
for (var invocation : invocations.autoPager()) {
  System.out.println(
      invocation.id() + " " + invocation.status() + " " + invocation.sessionId());
}

Ruby

## 列出自动化的调用记录
require "openai"

client = OpenAI::Client.new
invocations = client.beta.agents.automations.invocations.list("auto_123")
invocations.auto_paging_each do |invocation|
  puts "#{invocation.id} #{invocation.status} #{invocation.session_id}"
end

cURL

## 列出自动化的调用记录
curl https://api.openai.com/v1/agents/automations/auto_123/invocations \
  -H "OpenAI-Beta: agents=v1" \
  -H "Authorization: Bearer $OPENAI_API_KEY"

API 资源

资源 路径 用途
智能体 /v1/agents 定义任务指令与工具。
自动化 /v1/agents/automations 保存运行时间和目标会话。
自动化调用记录 /v1/agents/automations/{automation_id}/invocations 查看任务投递时间和接收任务的会话。
会话 /v1/agents/sessions 用会话历史和工具执行任务。
会话事件 /v1/agents/sessions/{session_id}/events 跟踪任务进度并收集结果。

使用场景

检查餐厅预约

TypeScript

// 在既有会话中安排定期检查餐厅预约
import OpenAI from "openai";

const client = new OpenAI();
const automation = await client.beta.agents.automations.create({
  type: "periodic",
  name: "检查餐厅预约",
  expression: "0 */2 * * *",
  timezone: "America/New_York",
  target: {
    type: "existing_session",
    session_id: "sess_123",
    instructions:
      "检查我们的晚餐计划是否有可预约的餐位。与先前查询结果比较,报告新增的可预约餐位。",
  },
});
console.log(automation);

Python

## 在既有会话中安排定期检查餐厅预约
from openai import OpenAI

client = OpenAI()
automation = client.beta.agents.automations.create(
    type="periodic",
    name="检查餐厅预约",
    expression="0 */2 * * *",
    timezone="America/New_York",
    target={
        "type": "existing_session",
        "session_id": "sess_123",
        "instructions": (
            "检查我们的晚餐计划是否有可预约的餐位。"
            "与先前查询结果比较,报告新增的可预约餐位。"
        ),
    },
)
print(automation.to_json())

Go

// 在既有会话中安排定期检查餐厅预约
import (
    "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:       "检查餐厅预约",
                Expression: "0 */2 * * *",
                Timezone:   "America/New_York",
                Target: openai.AutomationTargetParamUnion{
                    OfParamExistingSession: &openai.AutomationTargetParamExistingSession{
                        SessionID:    "sess_123",
                        Instructions: "检查我们的晚餐计划是否有可预约的餐位。与先前查询结果比较,报告新增的可预约餐位。",
                    },
                },
            },
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(automation.ID)

Java

// 在既有会话中安排定期检查餐厅预约
import 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;

OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var automation =
    client
        .beta()
        .agents()
        .automations()
        .create(
            AutomationCreateParams.builder()
                .automationScheduleParam(
                    AutomationScheduleParam.Periodic.builder()
                        .name("检查餐厅预约")
                        .expression("0 */2 * * *")
                        .timezone("America/New_York")
                        .target(
                            AutomationTargetParam.ExistingSession.builder()
                                .sessionId("sess_123")
                                .instructions(
                                    "检查我们的晚餐计划是否有可预约的餐位。与先前查询结果比较,报告新增的可预约餐位。")
                                .build())
                        .build())
                .build());
System.out.println(automation);

Ruby

## 在既有会话中安排定期检查餐厅预约
require "openai"

client = OpenAI::Client.new
automation = client.beta.agents.automations.create(
  create_automation_params: {
    type: "periodic",
    name: "检查餐厅预约",
    expression: "0 */2 * * *",
    timezone: "America/New_York",
    target: {
      type: "existing_session",
      session_id: "sess_123",
      instructions: "检查我们的晚餐计划是否有可预约的餐位。与先前查询结果比较,报告新增的可预约餐位。"
    }
  }
)
puts automation.id

cURL

## 在既有会话中安排定期检查餐厅预约
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 '{
    "type": "periodic",
    "name": "检查餐厅预约",
    "expression": "0 */2 * * *",
    "timezone": "America/New_York",
    "target": {
      "type": "existing_session",
      "session_id": "sess_123",
      "instructions": "检查我们的晚餐计划是否有可预约的餐位。与先前查询结果比较,报告新增的可预约餐位。"
    }
  }'

每月回顾支出

TypeScript

// 每月运行一次支出回顾
import OpenAI from "openai";

const client = new OpenAI();
const automation = await client.beta.agents.automations.create({
  type: "periodic",
  name: "每月支出回顾",
  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: "回顾我上个月的支出,指出未使用的订阅、涨价项目和其他可能节省费用的机会,供我核对。",
          },
        ],
      },
    ],
  },
});
console.log(automation);

Python

## 每月运行一次支出回顾
from openai import OpenAI

client = OpenAI()
automation = client.beta.agents.automations.create(
    type="periodic",
    name="每月支出回顾",
    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": (
                            "回顾我上个月的支出,指出未使用的"
                            "订阅、涨价项目和其他可能节省"
                            "费用的机会,供我核对。"
                        ),
                    }
                ],
            }
        ],
    },
)
print(automation.to_json())

Go

// 每月运行一次支出回顾
import (
    "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:       "每月支出回顾",
                Expression: "0 9 1 * *",
                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: "回顾我上个月的支出,指出未使用的订阅、涨价项目和其他可能节省费用的机会,供我核对。",
                                        },
                                    },
                                },
                            },
                        },
                    },
                },
            },
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(automation.ID)

Java

// 每月运行一次支出回顾
import 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("每月支出回顾")
                        .expression("0 9 1 * *")
                        .timezone("America/New_York")
                        .target(
                            AutomationTargetParam.NewSession.builder()
                                .agentId("agt_123")
                                .environment(EnvironmentParam.OpenAIHosted.builder().build())
                                .addInput(
                                    AgentSessionInputMessageParam.builder()
                                        .addInputTextContent(
                                            "回顾我上个月的支出,指出未使用的订阅、涨价项目和其他可能节省费用的机会,供我核对。")
                                        .build())
                                .build())
                        .build())
                .build());
System.out.println(automation);

Ruby

## 每月运行一次支出回顾
require "openai"

client = OpenAI::Client.new
automation = client.beta.agents.automations.create(
  create_automation_params: {
    type: "periodic",
    name: "每月支出回顾",
    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: "回顾我上个月的支出,指出未使用的订阅、涨价项目和其他可能节省费用的机会,供我核对。"
            }
          ]
        }
      ]
    }
  }
)
puts automation.id

cURL

## 每月运行一次支出回顾
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 '{
    "type": "periodic",
    "name": "每月支出回顾",
    "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": "回顾我上个月的支出,指出未使用的订阅、涨价项目和其他可能节省费用的机会,供我核对。"
            }
          ]
        }
      ]
    }
  }'

给出每日行动建议

TypeScript

// 定时在新会话中生成每日建议
import OpenAI from "openai";

const client = new OpenAI();
const automation = await client.beta.agents.automations.create({
  type: "periodic",
  name: "每日行动建议",
  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: "查看我的日历、任务和近期消息,了解今天的安排。建议今天最值得做的事,每项附上简短理由。",
          },
        ],
      },
    ],
  },
});
console.log(automation);

Python

## 定时在新会话中生成每日建议
from openai import OpenAI

client = OpenAI()
automation = client.beta.agents.automations.create(
    type="periodic",
    name="每日行动建议",
    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": (
                            "查看我的日历、任务和近期消息,了解今天的安排。"
                            "建议今天最值得做的事,"
                            "每项附上简短理由。"
                        ),
                    }
                ],
            }
        ],
    },
)
print(automation.to_json())

Go

// 定时在新会话中生成每日建议
import (
    "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:       "每日行动建议",
                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: "查看我的日历、任务和近期消息,了解今天的安排。建议今天最值得做的事,每项附上简短理由。",
                                        },
                                    },
                                },
                            },
                        },
                    },
                },
            },
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(automation.ID)

Java

// 定时在新会话中生成每日建议
import 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("每日行动建议")
                        .expression("0 10 * * *")
                        .timezone("America/New_York")
                        .target(
                            AutomationTargetParam.NewSession.builder()
                                .agentId("agt_123")
                                .environment(EnvironmentParam.OpenAIHosted.builder().build())
                                .addInput(
                                    AgentSessionInputMessageParam.builder()
                                        .addInputTextContent(
                                            "查看我的日历、任务和近期消息,了解今天的安排。建议今天最值得做的事,每项附上简短理由。")
                                        .build())
                                .build())
                        .build())
                .build());
System.out.println(automation);

Ruby

## 定时在新会话中生成每日建议
require "openai"

client = OpenAI::Client.new
automation = client.beta.agents.automations.create(
  create_automation_params: {
    type: "periodic",
    name: "每日行动建议",
    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: "查看我的日历、任务和近期消息,了解今天的安排。建议今天最值得做的事,每项附上简短理由。"
            }
          ]
        }
      ]
    }
  }
)
puts automation.id

cURL

## 定时在新会话中生成每日建议
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 '{
    "type": "periodic",
    "name": "每日行动建议",
    "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": "查看我的日历、任务和近期消息,了解今天的安排。建议今天最值得做的事,每项附上简短理由。"
            }
          ]
        }
      ]
    }
  }'

工作原理

  1. 定义任务。 选择运行时间,并指定每次运行是创建新会话还是继续既有会话。
  2. 投递任务。 每次运行都会产生一条调用记录,记录向目标会话发送任务的尝试。若目标会话忙碌,任务会等待。
  3. 跟踪结果。 智能体在会话的上下文中使用工具执行工作。通过会话事件跟踪进度和结果。会话接收任务后仍需执行,不能用投递完成判断工作是否完成。

应用可以通过 API 创建、更新、暂停或删除计划。启用 automations 工具后,智能体也可在当前会话安排下一次检查。

选择目标会话和计划类型

目标 使用场景 必需配置
new_session 每次独立执行的任务,例如每月回顾一次支出。 智能体、执行环境和 target.input 中的初始消息。
existing_session 依赖先前会话发现或上下文的跟进。 会话 ID 和 target.instructions 中的提醒指令。
类型 时间字段 示例
periodic expression 和 timezone 每天纽约时间上午 10 点。
once run_at 在未来某个时间运行一次,使用以秒为单位的 Unix 时间戳。

两种计划都适用于任一会话目标。创建后自动化以 active 状态存储。创建请求本身只保存计划,周期计划的第一次运行时间是下一个符合 cron 表达式的时刻。

安排每日行动建议

先创建具备任务所需指令和工具的智能体,并为其提供已获授权的日历、任务和消息访问。参见跨会话复用智能体。

SDK 会包含 OpenAI-Beta: agents=v1 请求头。直接用 cURL 发请求时请添加该请求头。下例每天纽约时间上午 10 点新建会话。

TypeScript

// 按纽约时间每天上午 10 点启动新会话
import OpenAI from "openai";

const client = new OpenAI();
const automation = await client.beta.agents.automations.create({
  type: "periodic",
  name: "每日行动建议",
  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: "查看我的日历、任务和近期消息,了解今天的安排。建议今天最值得做的事,每项附上简短理由。",
          },
        ],
      },
    ],
  },
});
console.log(automation);

Python

## 按纽约时间每天上午 10 点启动新会话
from openai import OpenAI

client = OpenAI()
automation = client.beta.agents.automations.create(
    type="periodic",
    name="每日行动建议",
    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": (
                            "查看我的日历、任务和近期消息,了解今天的安排。"
                            "建议今天最值得做的事,"
                            "每项附上简短理由。"
                        ),
                    }
                ],
            }
        ],
    },
)
print(automation.to_json())

Go

// 按纽约时间每天上午 10 点启动新会话
import (
    "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:       "每日行动建议",
                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: "查看我的日历、任务和近期消息,了解今天的安排。建议今天最值得做的事,每项附上简短理由。",
                                        },
                                    },
                                },
                            },
                        },
                    },
                },
            },
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(automation.ID)

Java

// 按纽约时间每天上午 10 点启动新会话
import 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("每日行动建议")
                        .expression("0 10 * * *")
                        .timezone("America/New_York")
                        .target(
                            AutomationTargetParam.NewSession.builder()
                                .agentId("agt_123")
                                .environment(EnvironmentParam.OpenAIHosted.builder().build())
                                .addInput(
                                    AgentSessionInputMessageParam.builder()
                                        .addInputTextContent(
                                            "查看我的日历、任务和近期消息,了解今天的安排。建议今天最值得做的事,每项附上简短理由。")
                                        .build())
                                .build())
                        .build())
                .build());
System.out.println(automation);

Ruby

## 按纽约时间每天上午 10 点启动新会话
require "openai"

client = OpenAI::Client.new
automation = client.beta.agents.automations.create(
  create_automation_params: {
    type: "periodic",
    name: "每日行动建议",
    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: "查看我的日历、任务和近期消息,了解今天的安排。建议今天最值得做的事,每项附上简短理由。"
            }
          ]
        }
      ]
    }
  }
)
puts automation.id

cURL

## 按纽约时间每天上午 10 点启动新会话
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 '{
    "type": "periodic",
    "name": "每日行动建议",
    "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": "查看我的日历、任务和近期消息,了解今天的安排。建议今天最值得做的事,每项附上简短理由。"
            }
          ]
        }
      ]
    }
  }'

保存返回的自动化 id 供之后查询或管理。每次运行都开启新对话。上例为会话创建一个 OpenAI 托管沙箱。

也可以在 target.agent 中内联配置智能体。请在 target.agent 与已有智能体的 target.agent_id 中填写一项。初始消息放在 target.input 内,至少包含一条带非空文本或图像 URL 的消息。

每月回顾支出

向已有智能体提供获授权的财务记录访问后,可按同样方式安排每月 1 日上午 9 点创建会话。

TypeScript

// 在每月 1 日上午 9 点安排支出回顾
import OpenAI from "openai";

const client = new OpenAI();
const automation = await client.beta.agents.automations.create({
  type: "periodic",
  name: "每月支出回顾",
  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: "回顾我上个月的支出,指出未使用的订阅、涨价项目和其他可能节省费用的机会,供我核对。",
          },
        ],
      },
    ],
  },
});
console.log(automation);

Python

## 在每月 1 日上午 9 点安排支出回顾
from openai import OpenAI

client = OpenAI()
automation = client.beta.agents.automations.create(
    type="periodic",
    name="每月支出回顾",
    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": (
                            "回顾我上个月的支出,指出未使用的"
                            "订阅、涨价项目和其他可能节省"
                            "费用的机会,供我核对。"
                        ),
                    }
                ],
            }
        ],
    },
)
print(automation.to_json())

Go

// 在每月 1 日上午 9 点安排支出回顾
import (
    "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:       "每月支出回顾",
                Expression: "0 9 1 * *",
                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: "回顾我上个月的支出,指出未使用的订阅、涨价项目和其他可能节省费用的机会,供我核对。",
                                        },
                                    },
                                },
                            },
                        },
                    },
                },
            },
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(automation.ID)

Java

// 在每月 1 日上午 9 点安排支出回顾
import 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("每月支出回顾")
                        .expression("0 9 1 * *")
                        .timezone("America/New_York")
                        .target(
                            AutomationTargetParam.NewSession.builder()
                                .agentId("agt_123")
                                .environment(EnvironmentParam.OpenAIHosted.builder().build())
                                .addInput(
                                    AgentSessionInputMessageParam.builder()
                                        .addInputTextContent(
                                            "回顾我上个月的支出,指出未使用的订阅、涨价项目和其他可能节省费用的机会,供我核对。")
                                        .build())
                                .build())
                        .build())
                .build());
System.out.println(automation);

Ruby

## 在每月 1 日上午 9 点安排支出回顾
require "openai"

client = OpenAI::Client.new
automation = client.beta.agents.automations.create(
  create_automation_params: {
    type: "periodic",
    name: "每月支出回顾",
    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: "回顾我上个月的支出,指出未使用的订阅、涨价项目和其他可能节省费用的机会,供我核对。"
            }
          ]
        }
      ]
    }
  }
)
puts automation.id

cURL

## 在每月 1 日上午 9 点安排支出回顾
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 '{
    "type": "periodic",
    "name": "每月支出回顾",
    "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": "回顾我上个月的支出,指出未使用的订阅、涨价项目和其他可能节省费用的机会,供我核对。"
            }
          ]
        }
      ]
    }
  }'

设置重复时间

使用五字段 cron 表达式和命名时区。

表达式 计划
0 10 * * * 每天上午 10 点。
0 */2 * * * 每两小时一次。
0 9 1 * * 每月 1 日上午 9 点。
0 9 * * MON-FRI 周一至周五上午 9 点。

时区决定如何解释 cron 表达式。UTC 计划使用 UTC,当地时间计划使用 America/New_York 等 IANA 时区。周期计划省略 run_at。

例如,0 */3 * * * 按所选时区的时钟时间在午夜、上午 3 点、6 点等时刻执行,计时与创建时刻无关。Agents API 会给周期运行加入少量随机延迟以分散负载。目标会话繁忙时,任务可能等待更久。

继续既有会话

当任务依赖会话之前的消息、发现或保留的工作时,选择既有会话。例如,计划晚餐的会话可以复用餐厅偏好及先前的查询结果。下例每两小时检查一次可预约情况。

TypeScript

// 每两小时在既有会话中复查餐厅预约
import OpenAI from "openai";

const client = new OpenAI();
const automation = await client.beta.agents.automations.create({
  type: "periodic",
  name: "检查餐厅预约",
  expression: "0 */2 * * *",
  timezone: "America/New_York",
  target: {
    type: "existing_session",
    session_id: "sess_123",
    instructions:
      "检查我们的晚餐计划是否有可预约的餐位。与先前查询结果比较,报告新增的可预约餐位。",
  },
});
console.log(automation);

Python

## 每两小时在既有会话中复查餐厅预约
from openai import OpenAI

client = OpenAI()
automation = client.beta.agents.automations.create(
    type="periodic",
    name="检查餐厅预约",
    expression="0 */2 * * *",
    timezone="America/New_York",
    target={
        "type": "existing_session",
        "session_id": "sess_123",
        "instructions": (
            "检查我们的晚餐计划是否有可预约的餐位。"
            "与先前查询结果比较,报告新增的可预约餐位。"
        ),
    },
)
print(automation.to_json())

Go

// 每两小时在既有会话中复查餐厅预约
import (
    "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:       "检查餐厅预约",
                Expression: "0 */2 * * *",
                Timezone:   "America/New_York",
                Target: openai.AutomationTargetParamUnion{
                    OfParamExistingSession: &openai.AutomationTargetParamExistingSession{
                        SessionID:    "sess_123",
                        Instructions: "检查我们的晚餐计划是否有可预约的餐位。与先前查询结果比较,报告新增的可预约餐位。",
                    },
                },
            },
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(automation.ID)

Java

// 每两小时在既有会话中复查餐厅预约
import 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;

OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var automation =
    client
        .beta()
        .agents()
        .automations()
        .create(
            AutomationCreateParams.builder()
                .automationScheduleParam(
                    AutomationScheduleParam.Periodic.builder()
                        .name("检查餐厅预约")
                        .expression("0 */2 * * *")
                        .timezone("America/New_York")
                        .target(
                            AutomationTargetParam.ExistingSession.builder()
                                .sessionId("sess_123")
                                .instructions(
                                    "检查我们的晚餐计划是否有可预约的餐位。与先前查询结果比较,报告新增的可预约餐位。")
                                .build())
                        .build())
                .build());
System.out.println(automation);

Ruby

## 每两小时在既有会话中复查餐厅预约
require "openai"

client = OpenAI::Client.new
automation = client.beta.agents.automations.create(
  create_automation_params: {
    type: "periodic",
    name: "检查餐厅预约",
    expression: "0 */2 * * *",
    timezone: "America/New_York",
    target: {
      type: "existing_session",
      session_id: "sess_123",
      instructions: "检查我们的晚餐计划是否有可预约的餐位。与先前查询结果比较,报告新增的可预约餐位。"
    }
  }
)
puts automation.id

cURL

## 每两小时在既有会话中复查餐厅预约
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 '{
    "type": "periodic",
    "name": "检查餐厅预约",
    "expression": "0 */2 * * *",
    "timezone": "America/New_York",
    "target": {
      "type": "existing_session",
      "session_id": "sess_123",
      "instructions": "检查我们的晚餐计划是否有可预约的餐位。与先前查询结果比较,报告新增的可预约餐位。"
    }
  }'

每次调用把保存的指令作为自动化通知发送到同一会话,使用当时的智能体配置与已保存状态。自动化通知与新用户消息是不同的输入。

会话忙碌时,通知等待会话可用。定时运行不会打断当前轮次,也不能补齐缺失的工具结果或批准。应用仍需处理需要跟进的操作。

安排一次检查

设置 type: "once",并将 run_at 设为未来某一时刻的整数 Unix 时间戳,单位为秒。省略 expression 和 timezone。该例的时间为 UTC 2027 年 1 月 1 日上午 9 点。运行示例时应根据实际时间选择未来时刻。

TypeScript

// 用未来的 Unix 秒时间戳安排一次跟进
import OpenAI from "openai";

const client = new OpenAI();
const automation = await client.beta.agents.automations.create({
  type: "once",
  name: "检查餐厅回复",
  run_at: 1798794000,
  target: {
    type: "existing_session",
    session_id: "sess_123",
    instructions:
      "检查餐厅是否回复了我们的预约。总结晚餐安排的变化。",
  },
});
console.log(automation);

Python

## 用未来的 Unix 秒时间戳安排一次跟进
from openai import OpenAI

client = OpenAI()
automation = client.beta.agents.automations.create(
    type="once",
    name="检查餐厅回复",
    run_at=1798794000,
    target={
        "type": "existing_session",
        "session_id": "sess_123",
        "instructions": (
            "检查餐厅是否回复了我们的预约。"
            "总结晚餐安排的变化。"
        ),
    },
)
print(automation.to_json())

Go

// 用未来的 Unix 秒时间戳安排一次跟进
import (
    "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{
            OfParamOnce: &openai.AutomationScheduleParamOnce{
                Name:  "检查餐厅回复",
                RunAt: 1798794000,
                Target: openai.AutomationTargetParamUnion{
                    OfParamExistingSession: &openai.AutomationTargetParamExistingSession{
                        SessionID:    "sess_123",
                        Instructions: "检查餐厅是否回复了我们的预约。总结晚餐安排的变化。",
                    },
                },
            },
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(automation.ID)

Java

// 用未来的 Unix 秒时间戳安排一次跟进
import 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;

OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var automation =
    client
        .beta()
        .agents()
        .automations()
        .create(
            AutomationCreateParams.builder()
                .automationScheduleParam(
                    AutomationScheduleParam.Once.builder()
                        .name("检查餐厅回复")
                        .runAt(1798794000L)
                        .target(
                            AutomationTargetParam.ExistingSession.builder()
                                .sessionId("sess_123")
                                .instructions(
                                    "检查餐厅是否回复了我们的预约。总结晚餐安排的变化。")
                                .build())
                        .build())
                .build());
System.out.println(automation);

Ruby

## 用未来的 Unix 秒时间戳安排一次跟进
require "openai"

client = OpenAI::Client.new
automation = client.beta.agents.automations.create(
  create_automation_params: {
    type: "once",
    name: "检查餐厅回复",
    run_at: 1798794000,
    target: {
      type: "existing_session",
      session_id: "sess_123",
      instructions: "检查餐厅是否回复了我们的预约。总结晚餐安排的变化。"
    }
  }
)
puts automation.id

cURL

## 用未来的 Unix 秒时间戳安排一次跟进
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 '{
    "type": "once",
    "name": "检查餐厅回复",
    "run_at": 1798794000,
    "target": {
      "type": "existing_session",
      "session_id": "sess_123",
      "instructions": "检查餐厅是否回复了我们的预约。总结晚餐安排的变化。"
    }
  }'

一次性计划执行后没有后续的定时运行。仍可手动触发,或为下一次跟进创建新的自动化。

让智能体安排后续任务

把 automations 加入工具列表,智能体即可为用户请求的工作安排后续任务。下例同时启用子智能体,以便主智能体委派每次定时工作并保留简短结果。

TypeScript

// 让主智能体安排任务并交由子智能体处理
import OpenAI from "openai";

const client = new OpenAI();
const session = await client.beta.agents.sessions.create({
  agent: {
    model: "gpt-6-astra",
    instructions:
      "用自动化安排用户请求的任务。将每次定时任务委派给子智能体,要求它简要回报。在主会话中保留目标、计划和有用的摘要。按用户要求调整或停止计划。",
    tools: [{ type: "automations" }],
    multi_agent: { enabled: true },
  },
  environment: { type: "openai_hosted" },
  input:
    "每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,并建议我接下来可以做的事。",
});
console.log(session.id);

Python

## 让主智能体安排任务并交由子智能体处理
from openai import OpenAI

client = OpenAI()
session = client.beta.agents.sessions.create(
    agent={
        "model": "gpt-6-astra",
        "instructions": (
            "用自动化安排用户请求的任务。"
            "将每次定时任务委派给子智能体,要求它简要回报。"
            "在主会话中保留目标、计划和有用的摘要。"
            "按用户要求调整或停止计划。"
        ),
        "multi_agent": {"enabled": True},
        "tools": [{"type": "automations"}],
    },
    environment={"type": "openai_hosted"},
    input=(
        "每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,"
        "并建议我接下来可以做的事。"
    ),
)
print(session.id)

Go

// 让主智能体安排任务并交由子智能体处理
import (
    "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("用自动化安排用户请求的任务。将每次定时任务委派给子智能体,要求它简要回报。在主会话中保留目标、计划和有用的摘要。按用户要求调整或停止计划。"),
            MultiAgent: openai.MultiAgentConfigParam{
                Enabled: true,
            },
            Tools: []openai.AgentToolParamUnion{
                {OfParamAutomations: &openai.AgentToolParamAutomations{}},
            },
        },
        Environment: openai.EnvironmentParamUnion{
            OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{},
        },
        Input: openai.BetaAgentSessionNewParamsInputUnion{
            OfString: openai.String("每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,并建议我接下来可以做的事。"),
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(session.ID)

Java

// 让主智能体安排任务并交由子智能体处理
import 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(
                            "用自动化安排用户请求的任务。将每次定时任务委派给子智能体,要求它简要回报。在主会话中保留目标、计划和有用的摘要。按用户要求调整或停止计划。")
                        .multiAgent(MultiAgentConfigParam.builder().enabled(true).build())
                        .addToolAutomations()
                        .build())
                .environment(EnvironmentParam.OpenAIHosted.builder().build())
                .input(
                    "每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,并建议我接下来可以做的事。")
                .build());
System.out.println(session.id());

Ruby

## 让主智能体安排任务并交由子智能体处理
require "openai"

client = OpenAI::Client.new
session = client.beta.agents.sessions.create(
  agent: {
    model: "gpt-6-astra",
    instructions: "用自动化安排用户请求的任务。将每次定时任务委派给子智能体,要求它简要回报。在主会话中保留目标、计划和有用的摘要。按用户要求调整或停止计划。",
    multi_agent: { enabled: true },
    tools: [{ type: "automations" }]
  },
  environment: { type: "openai_hosted" },
  input: "每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,并建议我接下来可以做的事。"
)
puts session.id

cURL

## 让主智能体安排任务并交由子智能体处理
curl 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": "用自动化安排用户请求的任务。将每次定时任务委派给子智能体,要求它简要回报。在主会话中保留目标、计划和有用的摘要。按用户要求调整或停止计划。",
      "tools": [{ "type": "automations" }],
      "multi_agent": { "enabled": true }
    },
    "environment": {
      "type": "openai_hosted"
    },
    "input": "每天在 America/New_York 时区上午 10 点回顾本会话中讨论的目标,并建议我接下来可以做的事。"
  }'

工具可创建、列出、获取、更新、暂停、恢复和删除当前智能体在本会话中创建的自动化。Agents API 会将当前会话设为目标。工具可安排一次性和周期任务,其权限限于本会话,不能用于启动新会话或管理其他会话的自动化。

应用可通过 API 管理智能体创建的自动化,也可管理应用自己创建的自动化。创建者由 Agents API 写入 created_by,创建请求应省略该字段。

automations 工具默认未启用,应用可直接经 API 创建计划。移除该工具后,已保存的计划仍然存在,需要时请通过 API 暂停或删除。

减少重复任务在主会话中的上下文占用

对于持续进行的任务,可启用多智能体编排,设置 agent.multi_agent.enabled: true。主智能体保留目标、计划和简要结果,将每次工作的细节委派给子智能体。

将每次定时任务委派给子智能体,提供目标和相关的既有发现,并要求简要回报。审阅回报并保存必要摘要,再决定继续、调整或停止计划。

automations 工具负责管理计划。请保留定时任务所需的其他工具和数据访问。

由应用定时跟进新用户的引导流程

应用可以响应自身事件创建计划。例如,用户注册后创建引导会话,并将第一次跟进安排在 48 小时之后。

TypeScript

// 从当前时间起计算 48 小时后的跟进时间
import OpenAI from "openai";

const client = new OpenAI();
const automation = await client.beta.agents.automations.create({
  type: "once",
  name: "新用户引导跟进",
  run_at: Math.floor(Date.now() / 1000) + 48 * 60 * 60,
  target: {
    type: "existing_session",
    session_id: "sess_123",
    instructions:
      "检查新用户引导进度。如果用户尚未完成引导,请发送下一条引导消息。",
  },
});
console.log(automation);

Python

## 从当前时间起计算 48 小时后的跟进时间
import time

from openai import OpenAI

client = OpenAI()
automation = client.beta.agents.automations.create(
    type="once",
    name="新用户引导跟进",
    run_at=int(time.time()) + 48 * 60 * 60,
    target={
        "type": "existing_session",
        "session_id": "sess_123",
        "instructions": (
            "检查新用户引导进度。"
            "如果用户尚未完成引导,请发送下一条引导消息。"
        ),
    },
)
print(automation.to_json())

Go

// 从当前时间起计算 48 小时后的跟进时间
import (
    "context"
    "fmt"
    "time"

    "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{
            OfParamOnce: &openai.AutomationScheduleParamOnce{
                Name:  "新用户引导跟进",
                RunAt: time.Now().Add(48 * time.Hour).Unix(),
                Target: openai.AutomationTargetParamUnion{
                    OfParamExistingSession: &openai.AutomationTargetParamExistingSession{
                        SessionID:    "sess_123",
                        Instructions: "检查新用户引导进度。如果用户尚未完成引导,请发送下一条引导消息。",
                    },
                },
            },
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(automation.ID)

Java

// 从当前时间起计算 48 小时后的跟进时间
import 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("新用户引导跟进")
                        .runAt(Instant.now().plus(Duration.ofHours(48)).getEpochSecond())
                        .target(
                            AutomationTargetParam.ExistingSession.builder()
                                .sessionId("sess_123")
                                .instructions(
                                    "检查新用户引导进度。如果用户尚未完成引导,请发送下一条引导消息。")
                                .build())
                        .build())
                .build());
System.out.println(automation);

Ruby

## 从当前时间起计算 48 小时后的跟进时间
require "openai"

client = OpenAI::Client.new
automation = client.beta.agents.automations.create(
  create_automation_params: {
    type: "once",
    name: "新用户引导跟进",
    run_at: Time.now.to_i + 48 * 60 * 60,
    target: {
      type: "existing_session",
      session_id: "sess_123",
      instructions: "检查新用户引导进度。如果用户尚未完成引导,请发送下一条引导消息。"
    }
  }
)
puts automation.id

cURL

## 从当前时间起计算 48 小时后的跟进时间
RUN_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": "新用户引导跟进",
    "run_at": $RUN_AT,
    "target": {
      "type": "existing_session",
      "session_id": "sess_123",
      "instructions": "检查新用户引导进度。如果用户尚未完成引导,请发送下一条引导消息。"
    }
  }
EOF

每次跟进结束后,应用可再安排一次 48 小时后的跟进。用户完成引导或选择退出时停止安排,并删除待执行的后续任务。用一次性计划实现 48 小时间隔,因为 cron 的月内日期字段不会跨月持续按 48 小时重复。

智能体需要访问引导进度和应用的消息工具。创建自动化只会保存任务计划,消息在执行过程中由应用发送。

试运行并检查投递

立即测试已保存的自动化时,可向 POST /v1/agents/automations/auto_123/invocations 发送无请求体的请求。手动触发不会改变已有计划,也不会消耗一次性计划的定时运行机会。计划暂停期间仍可手动触发。

保存返回的调用记录 ID。用 GET /v1/agents/automations/auto_123/invocations/ainv_123 获取该记录,或用下例列出投递历史。

TypeScript

// 列出调用记录并跟踪任务投递
import OpenAI from "openai";

const client = new OpenAI();
for await (const invocation of client.beta.agents.automations.invocations.list(
  "auto_123"
)) {
  console.log(invocation.id, invocation.status, invocation.session_id);
}

Python

## 列出调用记录并跟踪任务投递
from openai import OpenAI

client = OpenAI()
invocations = client.beta.agents.automations.invocations.list(automation_id="auto_123")
for invocation in invocations:
    print(invocation.id, invocation.status, invocation.session_id)

Go

// 列出调用记录并跟踪任务投递
import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
)

ctx := context.Background()
client := openai.NewClient()
invocations := client.Beta.Agents.Automations.Invocations.ListAutoPaging(ctx, "auto_123",
    openai.BetaAgentAutomationInvocationListParams{})
for invocations.Next() {
    invocation := invocations.Current()
    fmt.Println(invocation.ID, invocation.Status, invocation.SessionID)
}
if err := invocations.Err(); err != nil {
    panic(err)
}

Java

// 列出调用记录并跟踪任务投递
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.agents.automations.invocations.InvocationListParams;

OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var invocations =
    client
        .beta()
        .agents()
        .automations()
        .invocations()
        .list(InvocationListParams.builder().automationId("auto_123").build());
for (var invocation : invocations.autoPager()) {
  System.out.println(
      invocation.id() + " " + invocation.status() + " " + invocation.sessionId());
}

Ruby

## 列出调用记录并跟踪任务投递
require "openai"

client = OpenAI::Client.new
invocations = client.beta.agents.automations.invocations.list("auto_123")
invocations.auto_paging_each do |invocation|
  puts "#{invocation.id} #{invocation.status} #{invocation.session_id}"
end

cURL

## 列出调用记录并跟踪任务投递
curl https://api.openai.com/v1/agents/automations/auto_123/invocations \
  -H "OpenAI-Beta: agents=v1" \
  -H "Authorization: Bearer $OPENAI_API_KEY"

历史列表只包含已生成的调用记录。

字段 检查内容
status 初始为 queued,投递成功后变为 completed。
session_id 投递后要跟踪的会话 ID,会话还未就绪时可以是 null。
source.type 手动触发为 manual,定时运行时为 automation。
scheduled_at 计划执行时间,手动触发时为 null。

投递完成后,智能体可能仍在执行。 对新会话,投递完成表示接收了初始输入。对既有会话,这意味着会话已接收通知和开始工作的请求。

根据调用记录中的 session_id 跟踪会话事件,查看具体轮次的结果。自动化负责调度,应用负责显示会话输出和发送用户通知。

更改或停止计划

用 GET /v1/agents/automations/auto_123 获取计划,或用 GET /v1/agents/automations 列出项目的自动化。附加 session_id=sess_123 可筛选目标为该会话的自动化。下例修改 cron 表达式,将周期检查调整到上午 11 点。

TypeScript

// 把定期检查改为上午 11 点
import OpenAI from "openai";

const client = new OpenAI();
const automation = await client.beta.agents.automations.update("auto_123", {
  expression: "0 11 * * *",
});
console.log(automation);

Python

## 把定期检查改为上午 11 点
from openai import OpenAI

client = OpenAI()
automation = client.beta.agents.automations.update(
    automation_id="auto_123",
    expression="0 11 * * *",
)
print(automation.to_json())

Go

// 把定期检查改为上午 11 点
import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
)

ctx := context.Background()
client := openai.NewClient()
automation, err := client.Beta.Agents.Automations.Update(ctx, "auto_123",
    openai.BetaAgentAutomationUpdateParams{
        Expression: openai.String("0 11 * * *"),
    })
if err != nil {
    panic(err)
}
fmt.Println(automation.ID)

Java

// 把定期检查改为上午 11 点
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.agents.automations.AutomationUpdateParams;

OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var automation =
    client
        .beta()
        .agents()
        .automations()
        .update(
            AutomationUpdateParams.builder()
                .automationId("auto_123")
                .expression("0 11 * * *")
                .build());
System.out.println(automation);

Ruby

## 把定期检查改为上午 11 点
require "openai"

client = OpenAI::Client.new
automation = client.beta.agents.automations.update(
  "auto_123",
  expression: "0 11 * * *"
)
puts automation.id

cURL

## 把定期检查改为上午 11 点
curl https://api.openai.com/v1/agents/automations/auto_123 \
  -H "OpenAI-Beta: agents=v1" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "expression": "0 11 * * *"
  }'

省略的字段保留原值。如果传入 target,它会整体替换原目标,须包含所有必填字段并保留目标类型。可通过 target.instructions 修改提醒,或在 target.input 中更新初始消息。由智能体创建的自动化须继续使用创建它的会话作为目标。

在下一计划时刻前提交更改。更新适用于未来生成的调用记录。已排队的调用仍使用创建当时的目标和输入。

以下操作均无请求体。

目标 操作 效果
暂停 POST /v1/agents/automations/auto_123/pause 暂停尚待投递的定时任务,仍可手动触发。
恢复 POST /v1/agents/automations/auto_123/resume 让保存的计划重新生效。
删除 DELETE /v1/agents/automations/auto_123 停止未来的定时与手动调用。

暂停或删除自动化不会停止会话已接收的任务,也不会删除会话。正在投递的任务仍可能到达会话。若要停止正在执行的工作,请取消当前轮次。

若一次性自动化在暂停期间错过计划时间,恢复前请设置一个新的未来 run_at。已完成的一次性自动化不能暂停或恢复。要再定时跟进一次,请创建另一条自动化。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号