---
isPublished: true
template: "page.peb"
title: "Call an iDialogue Agent from Apex with rooms.AIAgent"
displayName: "Apex AIAgent Reference"
description: "Use the rooms.AIAgent managed-package class to start or continue an interactive iDialogue chat from subscriber Apex."
category: "resources"
contentType: "reference"
audience: "developer"
tags: "salesforce,apex,ai-agent,chat,dialogue,developer"
section: "resources"
seoTitle: "Call an iDialogue Agent from Salesforce Apex"
seoDescription: "Developer reference for starting and continuing interactive iDialogue chat with the rooms.AIAgent Apex class."
---

# Call an iDialogue Agent from Apex with `rooms.AIAgent`

Use `rooms.AIAgent` when subscriber Apex must send an interactive Chat request to a configured iDialogue agent. This
page documents the supported public behavior without describing managed-package internals.

Use [Run Agent Action](/build/flows/run-agent.html) for Salesforce Flow, background execution, or file preparation;
`rooms.AIAgent` is synchronous and exposes no background request or polling handle.

## Before you start

Make sure that:

- the running user has Apex class access to `rooms.AIAgent`;
- the selected `rooms__AIModel__c` agent is configured for the intended record and Chat context;
- the running user and configured connections have the required access;
- the org has an active iDialogue connection and available usage capacity; and
- the Apex transaction permits an HTTP callout.

## Public interface

| Member | Purpose |
| --- | --- |
| `withModelId(Id agentId)` | Select the required `rooms__AIModel__c` agent. |
| `withRecordId(Id recordId)` | Supply optional Salesforce record context. Omit it for global context. |
| `runChat(String userPrompt)` | Start a new dialogue. The prompt must not be blank. |
| `runChat(String userPrompt, String dialogueId)` | Continue an existing dialogue. A blank dialogue ID starts a new dialogue. |
| `hasErrors()` | Return `true` when the run recorded one or more errors or warnings. |

The configuration and run methods return the same helper instance, so subscriber Apex can use fluent calls.
`hasErrors()` returns a Boolean.

## Start a chat

This example requests an Account brief and rejects any result that did not complete cleanly.

```apex
public with sharing class AccountBriefService {
    public class AgentRequestException extends Exception {}

    public static String createBrief(Id accountId, Id agentId) {
        rooms.AIAgent result = new rooms.AIAgent()
            .withModelId(agentId)
            .withRecordId(accountId)
            .runChat('Prepare a concise account brief from the available context.');

        if (!result.success || result.hasErrors()) {
            throw new AgentRequestException(
                'The agent request did not complete cleanly. Review iDialogue Events.'
            );
        }
        return result.message;
    }
}
```

Do not assume that `message` contains JSON. It is an untyped `String`; deserialize it only when the selected agent has
an explicit, tested response contract for that use case.

If this example throws, Salesforce work in the caller—including the new Dialogue—can roll back, while a completed
external request or agent-tool effect cannot. Choose the error contract deliberately; exceptions do not reverse remote effects.

## Read the result

| Property | Meaning |
| --- | --- |
| `success` | `true` when the chat response succeeded. |
| `message` | The completion on success or a diagnostic message on failure. |
| `dialogueId` | The identifier to use for the next turn. |
| `errors` | Errors or warnings recorded during this run. |
| `debugInfo` | Sensitive diagnostic content. Do not return it to a browser or write it to normal application logs. |

Check both `success` and `hasErrors()`. A completion can succeed before Salesforce fails to save its new dialogue
record. In that case, `success` can be `true` while `errors` contains a persistence warning.

Do not show raw `message`, `errors`, or `debugInfo` to an end user after a failure. Give the user a safe message and
direct an administrator to iDialogue Events.

## Continue a dialogue

Keep the returned dialogue ID with the application state that owns the conversation. Supply the same agent and record
context in a later request or transaction; another callout after the new Dialogue is saved can encounter uncommitted work.

```apex
rooms.AIAgent nextTurn = new rooms.AIAgent()
    .withModelId(agentId)
    .withRecordId(accountId)
    .runChat('List the three highest-priority follow-up actions.', priorDialogueId);

if (!nextTurn.success || nextTurn.hasErrors()) {
    // Return a safe application error and direct an admin to iDialogue Events.
    return;
}
String dialogueIdForLater = nextTurn.dialogueId;
```

Starting a chat attempts to save a `rooms__Dialogue__c` record after the callout. Continuing a supplied dialogue ID does
not create another for that turn. A long initial prompt is abbreviated in Salesforce, but the full prompt is sent.

## Record and file context

`withRecordId` supplies the current Salesforce record to the configured agent. The agent's Data Context Definition,
Chat prompts, skills, memory permissions, and connection identity determine what data and tools are available.

For an agent configured for `ContentDocument`, supply the Content Document ID. The helper can use its latest published
Content Version as Chat context. It does not prepare a new or unprocessed file. Use
[Run Agent Action](/build/flows/run-agent.html) when the workflow must send explicit Content Version and Content
Document IDs or process a file before the agent starts.

## Failures and side effects

The helper reports clear validation messages when the prompt or agent ID is missing. Agent loading, callout, service,
and dialogue-save failures are available through the result. The helper does not expose fields for monitoring a
long-running response; use the supported Background entry point and verify its documented business result instead.

The selected agent can use its configured tools to read or change Salesforce data, call connected services, create
artifacts, or consume credits. These effects are not one transaction with the subscriber Apex request. Review the
agent's permissions, tools, approval rules, usage limits, and failure behavior before production use.

For governance and data-handling guidance, read [AI & Agent Governance](/trust/ai-agent-governance.html).
