**Source URL:** https://general.veevavault.dev/ai-agents/agent-actions/how-to-execute.md

# How to Execute Agent Actions

<Aside type="note">The functionality described on this page is only available to customers who have licensed Veeva AI.</Aside>
Developers can programmatically execute actions through Vault API or Vault Java SDK. Actions that are also available
for users to execute in the Vault UI through Veeva AI Chat have `supportChat` set to `true`.

## Vault API {#vault-api}

<Steps>
1. Query for all available actions with [Retrieve All Agent Actions](/ai-agents/api/retrieve-agent-actions/). From the response, find the action you want to execute. For example, `spelling_grammar__v`. You will also need the `agentName` associated with this action, for example, `quick_check__v`. You can also programatically retrieve the next step, the execute call, from the `url` parameter.

2. Request to execute the action with [Execute Agent Action](/ai-agents/api/execute-agent-action/). The previous call to [Retrieve All Agent Actions](/ai-agents/api/retrieve-agent-actions/) also includes this endpoint in the `url` parameter.

3. Once running, monitor the status of the in-progress action with [Retrieve Agent Action Execution Status](/ai-agents/api/retrieve-agent-action-execution-status/).

4. Once the action is complete, retrieve the completed action output with [Retrieve Agent Action Execution Status](/ai-agents/api/retrieve-agent-action-execution-status/).

</Steps>

## Vault Java SDK {#vault-java-sdk}

To execute an agent action with Vault Java SDK:

<Steps>
1. Define an *Agent Action Result Handler*, which is an asynchronous result handler class, `AgentActionResultHandler`. This class defines how to process the output returned by the action. The following is an example implementation of an `AgentActionResultHandler`:

```
@AgentActionResultHandlerInfo
public class MyActionHandler implements AgentActionResultHandler {
    @Override
    public void onSuccess(AgentActionSuccess result) {
        LogService logService = ServiceLocator.locate(LogService.class);
        logService.info("Action completed successfully: {}", result.getActionName());
        // Retrieve output from result to process it further
        for (int i = 0; i < result.getOutputSize(); i++) {
            AgentActionOutputType outputType = result.getOutputType(i);
            if (AgentActionOutputType.TEXT.equals(outputType)) {
                String outputMsg = result.getOutput(i, AgentActionOutputType.TEXT);
                logService.info("Action output [{}]: {}", i, outputMsg);
                  }
              }
          }

    @Override
    public void onError(AgentActionError error) {
    LogService logService = ServiceLocator.locate(LogService.class);
        logService.error("Action failed: {} - {}", error.getType(), error.getMessage());
              // Log the error or attempt retry
          }
      }

```

2. Build the agent instance request and start a new instance. Use `AiService` to build the agent instance request, and `AgentService` to start the new instance:

```
 AgentService agentService = ServiceLocator.locate(AgentService.class);
      AiService aiService = ServiceLocator.locate(AiService.class);
      LogService logService = ServiceLocator.locate(LogService.class);

      // Create a scope source for a specific object and record
      AiScopeSource objectScopeSource = aiService.newAiObjectScopeSourceBuilder()
          .withObjectName("my_object__c")
          .withRecordId("V35000000001001")
          .build();

      StartAgentInstanceRequest startAgentInstanceRequest = agentService.newStartAgentInstanceRequestBuilder()
          // Specify the Agent name to create an instance of
          .withAgentConfigurationName("my_agent__c")
          // Provide the scope source to the agent
          .withScopeSource(objectScopeSource)
          .build();

      agentService.batchStartAgentInstances(VaultCollections.asList(startAgentInstanceRequest))
          .onSuccesses(successes -> {
              StartAgentSuccess successResult = successes.get(0);
              logService.info("Agent Instance created with ID: {}", successResult.getAgentInstanceId());
          })
          .onErrors(errors -> {
              BatchOperationError errorResult = errors.get(0);
              logService.error("Failed to create Agent Instance due to error:  {}", errorResult.getError().getMessage());
          })
          .execute();

```

3. Build the action parameters and run the action.  Use `AgentActionInputItem` to build the action input, for example, the prompt a user would enter in Veeva AI chat. Then, build the action parameters with `AgentActionParameters`, which includes the required data to execute the action. For example, the input we just built with `AgentActionInputItem` and the `AgentActionResultHandler`. Finally, we run the action with `runAgentAction`:

```
    AgentService agentService = ServiceLocator.locate(AgentService.class);
    LogService logService = ServiceLocator.locate(LogService.class);

    AgentActionInputItem userInputItem = agentService.newAgentActionInputItemBuilder()
        .addText("Summarize the last 5 documents in the 'Compliance' folder.")
        .build();
    AgentActionInput userInput = agentService.newAgentActionUserInputBuilder()
        .appendInputItem(userInputItem)
        .build();

    AgentActionParameters parameters = agentService.newAgentActionParametersBuilder()
        // Specify the Agent Instance ID and the specific Action name to run
        .withAgentInstanceId("VXF00000000P001")
        .withActionName("summarize_documents__c")
        // Provide the input prompt/messages
        .appendInput(userInput)
        // Set the class that will handle the result when the action completes
        .withResultHandler(MyActionHandler.class)
        .build();
    // Running the action is asynchronous, the result handler will be invoked later.
    AgentActionRunResult runResult = agentService.runAgentAction(parameters);
    logService.info("Agent Action started with ID: {}", runResult.getActionInstanceId());

```

4. After executing all required actions, shut down the agent instance:

```
AgentService agentService = ServiceLocator.locate(AgentService.class);
LogService logService = ServiceLocator.locate(LogService.class);

StopAgentInstanceRequest stopAgentInstanceRequest = agentService.newStopAgentInstanceRequestBuilder()
    .withAgentInstanceId("VXF00000000P001")
    .build();

agentService.batchStopAgentInstances(VaultCollections.asList(stopAgentInstanceRequest))
    .onSuccesses(successes -> {
        StopAgentSuccess successResult = successes.get(0);
        logService.info("Agent Instance stopped with ID: {}", successResult.getAgentInstanceId());
        })
    .onErrors(errors -> {
        BatchOperationError errorResult = errors.get(0);
        logService.error("Failed to stop Agent Instance due to error: {}", errorResult.getError().getMessage());
        })
    .execute();

```

</Steps>

### Best Practices {#best-practices}

* Use one agent instance to run multiple actions in the same unit of work, rather than starting a new instance for every action.

* Shut down your agent instances as soon as you’ve finished running all of your agent actions. Instances will run for a maximum of 30 days before shutting down.



---

**Previous:** [Agent Actions](/ai-agents/agent-actions)  
**Next:** [Agent Context](/ai-agents/agent-context)