Skip to main content

Triggers

The ballerina/ai module provides a Listener and ChatService type for building AI-powered chat service endpoints. The ai:Listener wraps an HTTP listener and the ai:ChatService defines the contract for handling chat requests. This enables you to expose your AI agent as a standard HTTP service.

Three components work together:

ComponentRole
ai:ListenerHTTP listener wrapper that accepts chat service attachments and listens for incoming requests.
ai:ChatServiceService type contract that defines the post chat resource function for handling chat messages.
ai:ChatReqMessageThe incoming chat request payload containing sessionId and message fields.
ai:ChatRespMessageThe outgoing chat response payload containing the message field.

For action-based operations, see the Action Reference.


Listener

The ai:Listener establishes the connection and manages event subscriptions.

Configuration

The listener supports the following connection strategies:

Config TypeDescription
Listener initializationThe listener accepts either an integer port number or an existing http:Listener instance.

Listener initialization fields:

FieldTypeDefaultDescription
listenOnint|http:Listener8090The port number to listen on, or an existing HTTP listener to reuse.

Initializing the listener

Using a port number:

import ballerina/ai;

listener ai:Listener aiListener = new (9090);

Using an existing HTTP listener:

import ballerina/ai;
import ballerina/http;

listener http:Listener httpListener = new (9090);
listener ai:Listener aiListener = new (httpListener);

Service

An ai:ChatService is a Ballerina service that implements the chat endpoint contract. It must define a resource function post chat that accepts a ChatReqMessage payload and returns a ChatRespMessage or error.

Callback signatures

FunctionSignatureDescription
post chatresource function post chat(@http:Payload ai:ChatReqMessage request) returns ai:ChatRespMessage|errorInvoked when a chat client sends a message to the service.
note

The ai:ChatService type extends http:Service, so all standard HTTP service features apply.

Full usage example

import ballerina/ai;
import ballerina/http;

// Assume `personalAiAssistantAgent` is an ai:Agent defined elsewhere
service on new ai:Listener(9090) {
resource function post chat(@http:Payload ai:ChatReqMessage request) returns ai:ChatRespMessage|error {
string response = check personalAiAssistantAgent.run(request.message, request.sessionId);
return {message: response};
}
}
note

The ai:Listener defaults to port 8090 if no port or listener is provided. For production deployments, configure the port explicitly.


Supporting types

ChatReqMessage

FieldTypeDescription
sessionIdstringA unique identifier for the chat session.
messagestringThe content of the chat message sent by the user.

ChatRespMessage

FieldTypeDescription
messagestringThe response message generated by the chat service.