Tag: Batch Error

  • Chat Transcripts summaries using OpenAI

    Chat Transcripts summaries using OpenAI

    It is often necessary to reread the Chat Transcript with the customer to identify a problem and its solution, but the dialog can be very long and contain irrelevant information. AI comes to the rescue. It will easily provide you with the most important points of dialogue without unnecessary information.

    In this article we will use OpenAI, triggers, and Apex classes.

    Good to know
    Before we start, I recommend familiarizing yourself with the OpenAI limits by clicking the link.

    Main steps:

    1. Create an account on OpenAI.com and generate an ApiKey
    2. Set up Named Credentials
    3. Add external credential principal access to the profile
    4. Create a text field on the Chat Transcript object, where the compressed information of the dialogue with the customer will be stored
    5. Create the main logic using Apex Trigger and Apex Classes

    Generating ApiKey

    After creating an OpenAI account, we need to generate an ApiKey. Go to Personal and select View API keys. Click on the Create new secret key button and enter the name of your key. Copy and save the generated key somewhere, we will need it later.

    API keys are used for authenticating a calling program to another API – typically to confirm a project is authorized to connect.

    Set up Named Credentials

    A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. To simplify the setup of authenticated callouts, specify a named credential as the callout endpoint.

    Salesforce manages all authentication for callouts that specify a named credential as the callout endpoint. You can also skip remote site settings, which are otherwise required for callouts to external sites, for the site defined in the named credential.

    In the setup Quick find box find Named Credentials, choose External Credentials tab and click New button.

    Enter external credential Label, Name and Authentication Protocol and click Save.

    Click New button near the Principal section and enter:

    • Parameter Name: Token
    • Sequence Number: 1.

    Add Authentication Parameters and enter:

    • Parameter Name: Token
    • Value: your OpenAI generated ApiKey and click Save

    Click New button near the Custom Headers section and enter:
    Name: Authorization
    Value: {!$Credential.Your_Named_Credential_API_Name.Your_Principal_Name}
    Sequence Number: 1

    Click Save.

    dont miss out iconDon’t forget to check out: How to Send Any Salesforce Notifications to Slack Channels: A Complete Guide

    Go to the Named Credentials and click New. Enter Named credentials:
    Label: OpenAI API
    Name: OpenAI_API
    URL: https://api.openai.com
    Select your external credential from the picklist, uncheck Generate Authorization Header checkbox, check Allow Formulas in HTTP Header checkbox and click Save.

    Click New button near the Custom Headers section and enter:

    • Name: Content-Type
    • Value: application/json
    • Sequence Number: 1

    Click Save.

    Add external credential principal access to the profile

    Go to your profile and add external credential principal access.

    Chat Transcript Field Creation

    To store main information of a dialogue with a client, we can use a text field specially created for this on the Chat Transcript object.

    In the setup Object Manager find the Chat Transcript object, click Fields & Relationships tab and click New button. Select text Data Type, fulfill all necessary fields, choose layout for displaying the field and click Save.

    Main logic creation

    A chat transcript is a record of a chat between a customer and an agent. Salesforce automatically creates a transcript for each chat session.

    Requirements

    After the agent completes the chat, display the main idea of the dialogue in the Summary field (we created it earlier).

    Important
    When you’re using Omni-Channel routing, the chat transcript is created when the chat’s requested by a visitor. When a chat ends successfully by a customer or an agent, the chat transcript is updated with Body field as soon as the agent closes the chat window and any related tabs.

    Solution

    Let’s create an Apex Trigger for Chat Transcript object.

    Then let’s create a trigger handler class.

    Since we are using an after update trigger and plan to update the summary field with the Body field, we need to add a check for the Body field to avoid trigger recursion. The Body field should be changed and can’t be blank.

    dont miss out iconCheck out another amazing blog here by Vimera: How to make Error Handling in the Batches much Easier?

    In updateTranscriptSummary() we execute batch with a chunk of 100 records to avoid limits.

    Now let’s create an Apex Batch with the main logic.
    This article is prepared by our Salesforce developer Dmitry Mitkevich. To continue reading, please visit our website.
  • How to make Error Handling in the Batches much Easier?

    How to make Error Handling in the Batches much Easier?

    Have you ever faced such situation, when your batch handles loads of data, and suddenly one of chunks has failed, and to understand the cause of an error, you have to write customer error handlers to catch the error? And what if your org has dozens of various batches with different logic?

    Well, Salesforce has a solution for this.

    Any batch can implement the interface called Database.RaisesPlatformEvents which will wrap up your batch with a standard handler.

    First, you need to ensure that your batch is implementing Database.RaisesPlatformEvents interface.

    After that, if any unhandled error happens in your batch, the platform event called BatchApexErrorEvent will be created.

    This event according to documentation has next fields:

    • AsyncApexJobId – The AsyncApexJob record for the batch Apex job that fired this event.
    • DoesExceedJobScopeMaxLength – True if the JobScope field is truncated due to the message exceeding the character limit.
    • EventUuid – A universally unique identifier (UUID) that identifies a platform event message. This field is available in API version 52.0 and later.
    • ExceptionType – The Apex exception type name. Internal platform errors are represented as the System.UnexpectedException type.
    • JobScope – The Record IDs that are in scope if the event was fired from the execute() method of a batch job. If the batch job uses custom iterators instead of sObjects, JobScope is the toString() representation of the iterable objects. The maximum length is 40000 characters.
    • Message – The exception message text. The maximum length is 5000 characters.
    • Phase – The phase of the batch job when it encountered an error (start, execute, finish).
    • ReplayId – Represents an ID value that is populated by the system and refers to the position of the event in the event stream. Replay ID values aren’t guaranteed to be contiguous for consecutive events. A subscriber can store a replay ID value and use it on resubscription to retrieve missed events that are within the retention window.
    • RequestId – The unique ID of the batch job that fired the event. Event monitoring customers can use this information to correlate the error with logging information.
    • StackTrace – The Apex stacktrace of the exception, if available. The maximum length is 5000 characters.

    Once an event is created the next step is to catch and handle that event. There is a way to do it quite simple.

    dont miss out iconDon’t forget to check out: Data Manipulation and Error Handling in Salesforce

    Create the platform event triggered flow.

    Than choose BatchApexErrorEvent platform event to handle.

    Now $Record that is being passed to flow is BatchApexErrorEvent event that contains data about the batch error and the batch itself.

    Now in this flow you can create a custom object (that should be created before), to store all error data, or send email about the batch error, or even fix records that have failed to proceed.

    This event can be handled by a flow, apex trigger, processes and pub/sub API and streaming API.

    As you can see RaisesPlatformEvents interface can make error handling in the batches much easier. You will receive complete information about your batch error.

    dont miss out iconCheck out another amazing blog here by Vimera: Marketing Cloud Account Engagement (Pardot) Use Cases

    This article was originally published on the Vimera’s website.