Skip to content

Invoking AI Agents ​

An AI Agent can be invoked interactively through an AI Agent Widget or headlessly from Cloud Flow. Choose the invocation surface according to who initiates the work, whether a conversation interface is needed, and how the result will be used.

Choose an Invocation Surface ​

RequirementRecommended Approach
A person chats with the Agent on a PageAI Agent Widget
A Page or external caller sends an HTTP requestCloud Flow Web Hook that invokes the Agent
Server-side processing invokes the Agent without an HTTP endpointBackground Task
A Function delegates a bounded task to a specialist AgentInvoke another Agent from the Function implementation
A workflow needs only a model response, without Agent knowledge or functionsUse the simple-prompt Server API

The Agent must be configured, initialized, enabled, and available to the current runtime before it can be invoked.

Access Rules by Invocation Surface ​

The access check depends on how the Agent is invoked.

Invocation SurfaceAccess Control
AI Agent WidgetThe Agent's Access (Security) settings control which client users and groups may access it.
Web HookThe Web Hook's Access (Security) settings control who may invoke the endpoint. After that check passes, the Web Hook's trusted Cloud Flow can invoke the Agent regardless of the Agent's client access settings.
Background TaskThe task already runs in the trusted server environment and can invoke the Agent regardless of the Agent's client access settings.
AI Agent Function or moduleThe server-side Agent module can invoke another Agent regardless of the target Agent's client access settings.

Bypassing the Agent's client access settings does not authorize every operation performed during the run. Web Hooks must validate their requested operation. Built-in table tools enforce their applicable table access rules; Custom Functions must authorize direct Database and other protected operations themselves. Connection functions receive the Agent user's access context, but enforcement depends on the function exposed by the Connection service.

Interactive Widget Conversations ​

The AI Agent Widget provides a Page-based conversation experience. It can expose conversation controls such as new chats, available chats, and the Prompt Library.

The Widget controls presentation, including title, logo, prompt guide, disclaimer, and Default or Floating appearance. The selected Agent controls instructions, Knowledge Sources, functions, and behavior.

Widget conversations use persistent Agent chat behavior for the applicable user. Earlier messages can influence later turns. Use a new chat when testing a changed Agent configuration.

See AI Agent Widget.

Full Agent Runs vs. Simple Model Prompts ​

Cloud Flow supports two conceptually different operations:

OperationUses Agent InstructionsUses Knowledge Sources and FunctionsUses Agent Threads
Full Agent runYesYesUses a temporary service thread for a headless run
Simple model promptNoNoNo

Use a full Agent run when the target Agent's configured behavior is part of the requirement. Use a simple model prompt only when the workflow deliberately needs the provider/model without the Agent's configuration.

Naming an Agent in a simple-prompt call selects its configured provider/model. It does not turn the request into a full Agent run.

Invoke an Agent with Cloud Flow Blocks ​

The AI Prompt Output block invokes a configured Agent and returns a Deferred Task / Promise. Supply:

  • The AI Agent identifier.
  • The natural-language prompt.
  • An optional JSON Schema.
  • An optional JSON Schema Name.

Wait for the Deferred Task to complete, then use:

  • AI Prompt Output Status to determine whether the run succeeded.
  • AI Prompt Output Text to retrieve the text response.
  • AI Prompt Output Data to retrieve parsed structured output when a schema was supplied.

A conceptual workflow is:

text
Create Deferred Task
  AI Prompt Output using Agent: ClassificationAgent
  Prompt: classify the supplied request
  JSON Schema: classification result schema

Wait for Deferred Task Completion

If AI Prompt Output Status is true
  Read AI Prompt Output Data
  Continue trusted workflow
Otherwise
  Handle failure

Check status before using text or structured data. A model response that does not match the expected schema should be treated as a failed or incomplete structured result.

For exact block inputs and outputs, see the AI Agents Cloud Flow reference.

Invoke an Agent with the Server API ​

$io.system.runAgentPrompt performs a full headless Agent run from a Web Hook, Background Task, or AI Agent module.

It accepts:

  • The current Cloud Flow hook context.
  • The target Agent identifier.
  • A prompt.
  • An optional JSON Schema.
  • An optional progress callback.
  • Options including a schema name and request context.

The Promise resolves with an object containing:

PropertyMeaning
statusWhether the run completed successfully.
outputTextThe text produced by the Agent.
outputRawThe raw output objects produced by the run.
outputDataParsed JSON output when a valid schema was supplied and satisfied.
errError information when the run failed.

The optional callback can receive progress states and output chunks while the operation runs. Supported run statuses include queued, running, cancelled, complete, and error.

Use the exact signature and output contract from the Server $io.system API.

Temporary Service Threads ​

A headless full Agent invocation creates a temporary service thread for the run and removes it after processing. It does not add the headless exchange to a user's normal Widget conversation history.

This makes headless runs suitable for backend processing, but it also means one invocation should not assume that a later invocation remembers the earlier service run. Persist required workflow state in the Project Database or another appropriate durable system.

If a multi-step backend workflow requires context across calls, construct each prompt from trusted stored state or coordinate the sequence within the same bounded Cloud Flow operation.

Structured Output ​

Supply a JSON Schema when later Cloud Flow logic needs predictable fields rather than free-form prose.

Structured output is useful for:

  • Classification.
  • Extracting fields from text.
  • Selecting one of several workflow routes.
  • Producing a bounded list of actions for trusted validation.
  • Returning a typed result from a specialist Agent.

The supported schema subset includes string, number, integer, boolean, array, object, enum, and anyOf. Provide a valid schema name through the invocation options.

Schema validation improves result handling; it does not make model output trusted. Validate values, identifiers, ranges, and permissions before using them in Database or external-service operations.

Request Context ​

runAgentPrompt can pass an application-defined reqContext through the run. Function Knowledge Source implementations and Agent Database callbacks receive it when the model calls them.

Use request context for relevant workflow data such as:

  • A correlation identifier.
  • The name of the initiating workflow.
  • A bounded delegation depth.
  • A validated application-specific reference.

Request context is not authentication information. When the Agent calls a Function or initiates a database operation with a registered callback, the runtime supplies the identity and authentication information for the user invoking the Agent separately. The Function or callback can use that information to decide whether and how to perform the operation.

Do not place a claimed username, administrator flag, or role in reqContext and then treat it as authoritative. Use the separately supplied Agent authentication information and trusted Project data.

When an Agent Function invokes another Agent, request context is forwarded only if the implementation includes it in the nested call. Construct the nested context deliberately and omit irrelevant or sensitive fields.

Invoke an Agent from a Web Hook ​

A Web Hook can accept a request, validate it, invoke an Agent, and return a controlled response.

A typical flow is:

text
Web Hook receives request
  Validate caller and request data
  Build a bounded prompt
  Build non-authentication request context if needed
  Invoke configured AI Agent
  Wait for completion
  Validate output
  Return a controlled response

Do not forward an entire untrusted request blindly into a prompt or request context. Select the required values and apply size, type, and content checks.

The Web Hook must enforce its own access and response rules. Agent output can contain sensitive or unexpected content; return only the fields intended for the caller.

For Web Hook request handling, see Web Hooks and Access and Security.

Invoke an Agent from a Background Task ​

A Background Task can use an Agent as one step in backend processing. Examples include:

  • Classifying pending records.
  • Summarizing new content.
  • Generating a proposed plan for trusted code to validate.
  • Extracting structured fields before a Database update.
  • Coordinating a bounded sequence of specialized Agents.

A Background Task has no separate schedule setting. If it should repeat, implement the timing and rearming behavior in the task's own logic.

See Background Tasks.

Build a Bounded Agentic Loop ​

An agentic loop combines model output with application-controlled iteration. The Background Task should remain the loop controller.

text
Background Task
  Load durable workflow state
  Check stop and eligibility conditions
  Build prompt and request context
  Invoke Agent
  Validate structured result
  Perform only permitted action
  Store outcome and next state
  Stop or rearm timer

Design the loop with:

  • A clear goal and stop condition.
  • A maximum iteration or delegation depth.
  • Durable state for work that must survive a restart.
  • Validation before every Database or external action.
  • Idempotency or duplicate prevention.
  • Timeout, retry, and backoff behavior.
  • Provider usage and cost limits appropriate to the Project.
  • Logs that diagnose failures without exposing secrets.

Do not let a model response rearm an unlimited loop without trusted checks. Runtime timers and variables are not durable scheduling records.

Agent-to-Agent Delegation ​

A Function Knowledge Source implementation can call another Agent. This is useful when each Agent has a narrow specialty.

For example:

text
Support Agent
  Function: classifyEscalation
    Invoke Policy Classification Agent
    Request structured classification
    Validate result
    Return permitted summary to Support Agent

The called Agent can use its own instructions, Knowledge Sources, and functions. This also means it can call another Agent, so dependencies must be bounded.

Avoid these patterns:

  • An Agent directly invoking itself without a depth guard.
  • Agent A calling Agent B while Agent B can call Agent A without a stop rule.
  • Retrying every nested failure immediately and indefinitely.
  • Passing unrestricted output from one Agent directly into a consequential tool.

Prefer structured results, explicit responsibilities, and an application-controlled maximum depth.

Use a Simple Model Prompt ​

$io.system.runAgentSimplePrompt sends a prompt to the underlying model associated with an Agent. It does not use that Agent's instructions, Knowledge Sources, Function tools, or threads.

Use it for a small model task whose entire context is supplied in the call, such as a focused rewrite or transformation that does not need Agent behavior.

It returns a Promise resolving to status, output text, and error information. Its options are passed to the underlying model provider and can therefore be provider-specific.

Do not use the simple-prompt method when users expect the target Agent's configured knowledge or tools. Use runAgentPrompt instead.

Security and Reliability ​

For every headless invocation:

  • Validate the initiating request or stored work item.
  • Apply the caller-facing access control at the entry point, such as Web Hook Access (Security).
  • Enforce operation-specific authorization even though trusted Cloud Flow can invoke the Agent directly.
  • Treat prompt content and model output as untrusted.
  • Keep reqContext separate from authentication.
  • Validate structured output before acting on it.
  • Avoid sending secrets or unnecessary personal data to the provider.
  • Handle cancellation, timeout, failure, and missing output.
  • Protect external actions against duplication.
  • Bound nested calls and loops.

When the Agent calls a Function or table tool, that operation must still enforce its own authorization rules.

Testing Invocation Workflows ​

TestWhat to Verify
Widget chatConversation controls, persistent history, Agent behavior, and user access.
Headless full runInstructions, Knowledge Sources, Functions, and temporary service execution.
Simple promptResult does not depend on Agent knowledge or prior chat.
Structured resultRequired fields parse and pass application validation.
Request contextExpected context reaches Functions/callbacks and is not used as identity.
Web Hook callerRequest validation, response filtering, and access rules.
Background loopStop conditions, restarts, duplicate prevention, and provider failure.
Nested AgentMaximum depth, cycle prevention, timeout, and error propagation.
Published runtimePublished configuration and dependencies match the tested workflow.

Review Agent Run Logs and Cloud Flow logs together when a workflow spans several modules.

Troubleshooting ​

IssueWhat to Check
Agent not found or not initializedTarget identifier, provider Connection, Agent enabled state, and runtime.
Full run ignores expected knowledgeTarget Agent selection, active Knowledge Sources, description, and prompt.
Simple prompt ignores Agent instructionsThis is expected; use a full Agent run.
Structured data is nullSchema validity, schema name, model output, and run status.
Function lacks request contextoptions.reqContext on the initiating call and explicit forwarding in nested calls.
Web Hook exposes too much outputResponse construction and validation after the Agent completes.
Loop repeats workDurable state, idempotency checks, timer behavior, and restart handling.
Nested workflow does not terminateSelf-call, circular dependency, missing depth limit, and retry policy.

For Function composition, see Function Knowledge Sources. For test and usage tools, see Managing and Testing AI Agents.