Skip to main content

准备好创建 Apex 操作

学习目标

完成本单元后,您将能够:

  • 使贵组织准备好构建操作。
  • 验证 Apex 是否已为操作做好准备。
备注

备注

用中文(简体)学习?在中文(简体)Trailhead Playground 中开始挑战,用括号中提供的译文完成挑战。仅复制并粘贴英文值,因为挑战验证基于英文数据。如果在中文(简体)组织中没有成功通过挑战,我们建议您 (1) 将区域设置切换为美国,(2) 按此处说明将语言切换为英文,(3) 再次单击“检查挑战”按钮。

查看 Trailhead 本地化语言徽章详细了解如何利用 Trailhead 译文。

Note

全新 Agentforce 生成器已全面可用!

Agentforce 已升级!2026 年 2 月起,全新的智能体构建体验已全面可用。此徽章使用的不是新生成器,而是旧生成器,但将会更新。现在如需使用新生成器,请完成浏览新 Agentforce 生成器学习路径或详细阅读 Agentforce 文档

预报:未来几天天气晴朗

任何有过度假经历的人都知道,密切关注天气对于有效落实旅行计划至关重要。在 Coral Cloud 度假村,客人期望的是阳光明媚、温暖宜人……直到天气突变。为了确保无论天气如何,客人都能尽享假期,Coral Cloud 团队希望为其 AI 智能体添加收集天气信息的功能。为此,他们需要创建操作,使用外部 API 从 Apex 类中提取天气数据。

注册包含 Agentforce 的 Developer Edition 组织

要完成本模块,您需要一个包含 Agentforce 和示例数据的专用 Developer Edition 组织。单击链接,注册免费、可自定义且包含 Agentforce 的 Developer Edition 组织,并将其连接到 Trailhead,即可完成本模块中的挑战。请注意,此组织是为配合此徽章中的挑战而设计的,可能不适用于其他徽章。请务必检查确认您使用的是我们推荐的 Trailhead Playground 或专用的 Developer Edition 组织。

  1. 免费注册包含 Agentforce 的 Developer Edition 组织
  2. 填写表格:
    1. 在 Email(电子邮件)处输入有效的电子邮件地址。
    2. 在 Username(用户名)处输入一个看起来像电子邮件地址且唯一的用户名,但不必是一个有效的电子邮件帐户(例如,yourname@example.com)。
  3. 表格填好以后,单击 Sign me up(我要注册)。出现一条确认消息。
  4. 收到激活电子邮件后(这可能需要几分钟),打开它并点击 Verify Account(验证帐户)。
  5. 设置密码和挑战问题,完成注册。提示:将用户名、密码和登录 URL 保存在安全的地方(如密码管理器),以便日后访问。
  6. 您已登录 Developer Edition。

现在将新的 Developer Edition 组织连接到 Trailhead。

  1. 确保您已登录 Trailhead 帐户。
  2. 在页面底部的 Challenge(挑战)部分,单击组织名称,然后单击 Connect Org(连接组织)
  3. 在登录屏幕上,输入刚刚设置的 Developer Edition 的用户名和密码。
  4. 在 Allow Access?(是否允许访问?)屏幕上,单击 Allow(允许)
  5. 在 Want to connect this org for hands-on challenges?(想要连接此组织进行实践挑战?)屏幕上,单击 Yes!(是!) Save it(保存)。您将被重定向到挑战页面,并准备使用新的 Developer Edition 来获得此徽章。

帮助组织做好智能体准备

在开始自定义智能体之前,请启用所有必需的组织功能。

  1. 单击 Setup(设置),然后选择 Setup(设置)
  2. 在 Setup(设置)的 Quick Find(快速查找)框中,搜索并选择 Einstein Setup(Einstein 设置)
  3. 验证 Einstein 是否已 On(开启)。如果已经 On(开启),请先 Off(关闭),再重新 On(开启)

    启用 Einstein 切换开关。
  1. 刷新浏览器重新加载 Setup(设置)。
  2. 在 Setup(设置)的 Quick Find(快速查找)中,输入并搜索 Salesforce Go
  3. 在 Search features...(搜索功能...)文本框中,输入并选择 Agentforce (Default)(Agentforce(默认))

    已选择 Agentforce(默认)。
  1. 单击 Get Started(开始)
  2. 单击 Turn On(打开)
  3. 单击 Confirm(确认)

利用已有功能构建智能体操作

好了!差不多可以开始为您的智能体构建自定义操作了。使用 Salesforce 构建 AI 智能体的优势之一在于,您可以利用组织中已构建的功能。在本个案中,您希望将 Coral Cloud 度假村的天气信息添加到 AI 智能体中。Coral Cloud 已经提供了一个 WeatherService Apex 类,用于从外部 API 获取 Coral Cloud 度假村所在位置的天气信息。我们来看看它如何应用于操作。

public with sharing class WeatherService {
    /**
     * Gets the weather at Coral Cloud Resorts for the provided date
     */
    public static Weather getResortWeather(Datetime dateToCheck) {
        Integer currentYear = Date.today().year();
        Integer yearDelta = currentYear - dateToCheck.year();
        dateToCheck = dateToCheck.addYears(yearDelta);
        String isoDate = dateToCheck.format('yyyy-MM-dd');
        String dateString = dateToCheck.format('MMMM d');
        // Prepare API request
        HttpRequest req = new HttpRequest();
        req.setEndpoint(
            'callout:Weather_Endpoint/weather?lat=37.789782764570425&lon=-122.39723702244089&date=' +
            isoDate
        );
        req.setMethod('GET');
        // Make callout
        Http http = new Http();
        HttpResponse res = http.send(req);
        if (res.getStatusCode() != 200) {
            throw new CalloutException('Bad response: ' + res);
        }
        // The response contains a list of temperatures for different times of the day
        // We parse the response and find the min and max temperatures
        String body = res.getBody();
        WeatherApiResponse weatherResponse = (WeatherApiResponse) JSON.deserialize(
            body,
            WeatherAPIResponse.class
        );
        List<Decimal> temperatures = new List<Decimal>();
        for (TemperatureWrapper item : weatherResponse.weather) {
            if (item.temperature != null) {
                temperatures.add(item.temperature);
            }
        }
        temperatures.sort();
        // Prepare temperatures and description
        Decimal minTempC = temperatures[0];
        Decimal maxTempC = temperatures[temperatures.size() - 1];
        Decimal minTempF = toFahrenheit(minTempC);
        Decimal maxTempF = toFahrenheit(maxTempC);
        String description =
            'On ' +
            dateString +
            ', temperature should be between ' +
            minTempC +
            '°C (' +
            minTempF +
            '°F) and ' +
            maxTempC +
            '°C (' +
            maxTempF +
            '°F) at Coral Cloud Resorts.';
        // Return weather info
        Weather weather = new Weather();
        weather.minTemperatureC = minTempC;
        weather.minTemperatureF = minTempF;
        weather.maxTemperatureC = maxTempC;
        weather.maxTemperatureF = maxTempF;
        weather.description = description;
        return weather;
    }
    private static Decimal toFahrenheit(Decimal celsius) {
        return (celsius * 9 / 5 + 32).setScale(1);
    }
    private class WeatherApiResponse {
        public List<TemperatureWrapper> weather;
    }
    private class TemperatureWrapper {
        public Decimal temperature;
    }
    public class Weather {
        public Decimal minTemperatureC;
        public Decimal minTemperatureF;
        public Decimal maxTemperatureC;
        public Decimal maxTemperatureF;
        public String description;
    }
}

这是一个简单的 Apex 类,它会向天气服务发送 HTTP 请求,获取所输入日期的天气信息。不过,Agentforce Builder(Agentforce 生成器)无法使用此 Apex 类。您可以将该类更新为可调用方法,但最佳实践是创建新的 Apex 类,并将其设置为 InvocableMethod,调用原始的 WeatherService。InvocableMethod 注解允许您从声明式工具(例如 Flows(流))、通过 REST 连接的外部应用程序以及 Agentforce 调用自定义 Apex 代码。

好消息是,Coral Cloud 团队构建了一个 Apex 类,该类已经开始调用 WeatherService。让我们来看一看这个类,以及它是如何实施 WeatherService 的。

public with sharing class CheckWeather {
    @InvocableMethod(
        label='Check Weather'
        description='Check weather at Coral Cloud Resorts at a specific date'
    )
    public static List<WeatherResponse> getWeather(
        List<WeatherRequest> requests
    ) {
        // Retrieve the date for which we want to check the weather
        Datetime dateToCheck = (Datetime) requests[0].dateToCheck;
        WeatherService.Weather weather = WeatherService.getResortWeather(
            dateToCheck
        );
        // Create the response for Copilot
        WeatherResponse response = new WeatherResponse();
        response.minTemperature = weather.minTemperatureC;
        response.maxTemperature = weather.maxTemperatureC;
        response.temperatureDescription =
            'Temperatures will be between ' +
            weather.minTemperatureC +
            '°C (' +
            weather.minTemperatureF +
            '°F) and ' +
            weather.maxTemperatureC +
            '°C (' +
            weather.maxTemperatureF +
            '°F) at Coral Cloud.';
        return new List<WeatherResponse>{ response };
    }
    public class WeatherRequest {
        @InvocableVariable(
            required=true
            description='Date for which we want to check the temperature. The variable needs to be an Apex Date type with format yyyy-MM-dd.'
        )
        public Date dateToCheck;
    }
    public class WeatherResponse {
        @InvocableVariable(
            description='Minimum temperature in Celsius at Coral Cloud Resorts location for the provided date'
        )
        public Decimal minTemperature;
        @InvocableVariable(
            description='Maximum temperature in Celsius at Coral Cloud Resorts location for the provided date'
        )
        public Decimal maxTemperature;
        @InvocableVariable(
            description='Description of temperatures at Coral Cloud Resorts location for the provided date'
        )
        public String temperatureDescription;
    }
}

首先要注意的是 getWeather 方法的 @InvocableMethod 注解。传入的两个参数用于 Create an Agent Action(创建智能体操作)过程。label(标签)参数显示为 Agent Action Label(智能体操作标签)。description(描述)参数显示为 Agent Action Instructions(智能体操作指令)。描述对于 AI 智能体及智能体理解方法的方式至关重要。

此外,还有两个公共类,即 WeatherRequestWeatherResponse,分别具有用于标识 Create an Agent Action Input and Outputs(创建智能体操作输入和输出)的 @InvocableVariable 注解。

对于 WeatherRequestdateToCheck@InvocableVariable 注解中,其 required(必要)参数被设置为 true。这将强制使 Create an Agent Action Require Input(创建智能体操作需要输入)配置默认处于勾选状态。description(描述)参数将显示为 Input Instructions(输入指令)。此外,将 dateToCheck 的变量类型设置为 Date(日期)时,会同时设置 Input Data Type(输入数据类型)。

对于 WeatherResponse,存在三个带有 @InvocableVariable 注解、minTemperaturemaxTemperaturetemperatureDescription 的变量。每个变量都有一组 description(描述)参数,这些参数会在 Create an Agent Action Outputs Instructions(创建智能体操作输出指令)中显示。此外,变量类型 Decimal(小数)、Decimal(小数)和 String(字符串)均以 Output Rendering(输出渲染)形式显示。String(字符串)变量类型将被设置为 Text for Output Rendering(输出渲染文本)。

设置权限

与任何 Apex 功能一样,您需要对 Apex 文件拥有正确的访问权限。此步骤已在您用于此徽章的自定义开发组织中完成。权限已设置完毕,通过权限集使 AI 智能体能够访问包含 Invocable(可调用)方法的 Apex 类。如果不是这样,即使您创建了操作并将其添加到智能体中,智能体在制定计划时也无法将其纳入考虑范围。缺乏适当的权限是导致 Apex 操作在 Agentforce 中无法按预期运行的主要原因之一。

现在您应该更清楚地了解了将 Apex 用于操作所需的条件。这有点难以理解,但当您在下一单元构建操作时,就会更清楚了。

资源

在 Salesforce 帮助中分享 Trailhead 反馈

我们很想听听您使用 Trailhead 的经验——您现在可以随时从 Salesforce 帮助网站访问新的反馈表单。

了解更多 继续分享反馈