Module ai
API
Declarations
Definitions
ballerina/ai Ballerina library
Overview
This module offers APIs for developing AI applications and agents powered by Large Language Models (LLMs).
AI agents use LLMs to process natural language inputs, generate responses, and make decisions based on given instructions. These agents can be designed for various tasks, such as answering questions, automating workflows, or interacting with external systems.
Quickstart
To use the ai
module in your Ballerina application, update the .bal
file as follows:
Step 1: Import the module
Import the ai
module.
import ballerina/ai;
Step 2: Define the System Prompt
A system prompt guides the AI's behavior, tone, and response style, defining its role and interaction with users.
ai:SystemPrompt systemPrompt = { role: "Math Tutor", instructions: string `You are a helpful math tutor. Explain concepts clearly with examples and provide step-by-step solutions.` };
Step 3: Define the Model Provider
Ballerina currently supports multiple model providers, which you can explore here on Ballerina Central.
In addition to these prebuilt implementations, you also have the flexibility to implement your own custom provider.
Here's how to initialize the prebuilt OpenAI model provider:
import ballerinax/ai.model.provider.openai; final ai:ModelProvider openAiModel = check new openai:Provider("openAiApiKey", modelType = openai:GPT_4O);
Step 4: Define the tools
An agent tool extends the AI's abilities beyond text-based responses, enabling interaction with external systems or dynamic tasks. Define tools as shown below:
# Returns the sum of two numbers # + a - first number # + b - second number # + return - sum of the numbers @ai:AgentTool isolated function sum(int a, int b) returns int => a + b; @ai:AgentTool isolated function mult(int a, int b) returns int => a * b;
Constraints for defining tools:
- The function must be marked
isolated
. - Parameters should be a subtype of
anydata
. - The tool should return a subtype of
anydata|http:Response|stream<anydata, error>|error
. - Tool documentation enhances LLM performance but is optional.
Step 5: Define the Memory
The ai
module manages memory for individual user sessions using the Memory
. By default, agents are configured with a memory that has a predefined capacity. To create a stateless agent, set the memory
to ()
when defining the agent. Additionally, you can customize the memory capacity or provide your own memory implementation. Here's how to initialize the default memory with a new capacity:
final ai:Memory memory = new ai:MessageWindowChatMemory(20);
Step 6: Define the Agent
Create a Ballerina AI agent using the configurations created earlier:
final ai:Agent mathTutorAgent = check new ( systemPrompt = systemPrompt, model = openAiModel, tools = [sum, mult], // Pass array of function pointers annotated with @ai:AgentTool memory = memory );
Step 7: Invoke the Agent
Finally, invoke the agent by calling the run
method:
mathTutorAgent.run("What is 8 + 9 multiplied by 10", sessionId = "student-one");
If using the agent with a single session, you can omit the sessionId
parameter.
Examples
The ai
module provides practical examples illustrating usage in various scenarios. Explore these examples, covering the following use cases:
- Personal AI Assistant - Demonstrates how to implement a personal AI assistant using Ballerina AI module along with Google Calendar and Gmail integrations
Functions
augmentUserQuery
function augmentUserQuery(QueryMatch[]|Document[] context, string query) returns ChatUserMessage
Augments the user's query with relevant context.
Parameters
- context QueryMatch[]|Document[] - Array of matched chunks or documents to include as context
- query string - The user's original question
Return Type
- ChatUserMessage - The augmented query with injected context
chunkDocumentRecursively
function chunkDocumentRecursively(Document document, int maxChunkSize, int maxOverlapSize, RecursiveChunkStrategy strategy) returns Chunk[]|Error
Provides functionality to recursively chunk a text document using a configurable strategy.
The chunking process begins with the specified strategy and recursively falls back to
finer-grained strategies if the content exceeds the configured maxChunkSize
. Overlapping content
between chunks can be controlled using maxOverlapSize
.
Parameters
- document Document - The input document to be chunked
- maxChunkSize int (default 200) - Maximum number of characters allowed per chunk
- maxOverlapSize int (default 40) - Maximum number of characters to reuse from the end of the previous chunk when creating the next one. This overlap is made of complete sentences taken in reverse from the previous chunk, without exceeding this limit. It helps maintain context between chunks during splitting.
- strategy RecursiveChunkStrategy (default PARAGRAPH) - The recursive chunking strategy to use. Defaults to
PARAGRAPH
executeTool
function executeTool(FunctionTool tool, map<json> llmToolInput) returns ToolExecutionResult
Executes an AgentTool.
Parameters
- tool FunctionTool - Function pointer to the AgentTool
- llmToolInput map<json> - Tool input generated by the LLM
Return Type
- ToolExecutionResult - Result of the tool execution
extractToolsFromOpenApiJsonSpec
function extractToolsFromOpenApiJsonSpec(map<json> openApiSpec, *AdditionInfoFlags additionInfoFlags) returns HttpApiSpecification & readonly|Error
Extracts the Http tools from the given OpenAPI specification as a JSON
Parameters
- openApiSpec map<json> - A valid OpenAPI specification in JSON format
- additionInfoFlags *AdditionInfoFlags - Flags to extract additional information from the OpenAPI specification
Return Type
- HttpApiSpecification & readonly|Error - A record with the list of extracted tools and the service URL (if available)
extractToolsFromOpenApiSpecFile
function extractToolsFromOpenApiSpecFile(string filePath, *AdditionInfoFlags additionInfoFlags) returns HttpApiSpecification & readonly|Error
Extracts the Http tools from the given OpenAPI specification file.
Parameters
- filePath string - Path to the OpenAPI specification file (should be JSON or YAML)
- additionInfoFlags *AdditionInfoFlags - Flags to extract additional information from the OpenAPI specification
Return Type
- HttpApiSpecification & readonly|Error - A record with the list of extracted tools and the service URL (if available)
getDefaultEmbeddingProvider
function getDefaultEmbeddingProvider() returns Wso2EmbeddingProvider|Error
Creates a default embedding provider based on the provided wso2ProviderConfig
.
Return Type
- Wso2EmbeddingProvider|Error - A
Wso2EmbeddingProvider
instance if the configuration is valid; otherwise, anai:Error
.
getDefaultModelProvider
function getDefaultModelProvider() returns Wso2ModelProvider|Error
Creates a default model provider based on the provided wso2ProviderConfig
.
Return Type
- Wso2ModelProvider|Error - A
Wso2ModelProvider
instance if the configuration is valid; otherwise, anai:Error
.
getToolConfigs
function getToolConfigs(FunctionTool[] tools) returns ToolConfig[]
Generates a array of ToolConfig
from the given list of function pointers.
Parameters
- tools FunctionTool[] - Array of function pointers annotated with
@ai:AgentTool
annotation
Return Type
- ToolConfig[] - Array of
ai:ToolConfig
instances
getTools
Get the tools registered with the agent.
Parameters
- agent Agent - Agent instance
Return Type
- Tool[] - Array of tools registered with the agent
parseOpenApiSpec
function parseOpenApiSpec(map<json> openApiSpec) returns OpenApiSpec|UnsupportedOpenApiVersion|OpenApiParsingError
Parses the given OpenAPI specification as a JSON to a OpenApiSpec object.
Parameters
- openApiSpec map<json> - A valid OpenAPI specification in JSON format
Return Type
- OpenApiSpec|UnsupportedOpenApiVersion|OpenApiParsingError - A OpenApiSpec object
Classes
ai: Agent
Represents an agent.
Constructor
Initialize an Agent.
init (*AgentConfiguration config)
- config *AgentConfiguration - Configuration used to initialize an agent
run
Executes the agent for a given user query.
ai: HttpServiceToolKit
Defines a HTTP tool kit. This is a special type of tool kit that can be used to invoke HTTP resources. Require to initialize the toolkit with the service url and http tools that are belongs to a single API.
Constructor
Initializes the toolkit with the given service url and http tools.
init (string serviceUrl, HttpTool[] httpTools, ClientConfiguration clientConfig, map<string|string[]> headers)
getTools
function getTools() returns ToolConfig[]
Useful to retrieve the Tools extracted from the HttpTools.
Return Type
- ToolConfig[] - An array of Tools corresponding to the HttpTools
ai: InMemoryVectorStore
An in-memory vector store implementation that provides simple storage for vector entries.
Constructor
Initializes a new in-memory vector store.
init (int topK, SimilarityMetric similarityMetric)
- topK int 3 - The maximum number of top similar vectors to return in query results
- similarityMetric SimilarityMetric COSINE - The metric used for vector similarity
add
function add(VectorEntry[] entries) returns Error?
Adds vector entries to the in-memory store. Only supports dense vectors in this implementation. If a vector entry with the same ID already exists, it will be replaced.
Parameters
- entries VectorEntry[] - Array of vector entries to store. If an entry does not contain an id, a unique id will be generated by default.
Return Type
- Error? -
nil
on success; an Error if non-dense vectors are provided
query
function query(VectorStoreQuery query) returns VectorMatch[]|Error
Queries the vector store for vectors similar to the given query.
Parameters
- query VectorStoreQuery - The query containing the embedding vector and optional filters
Return Type
- VectorMatch[]|Error - An array of vector matches sorted by similarity score (limited to topK),
or an
ai:Error
if the query fails
delete
Deletes a vector entry from the in-memory store. Removes the entry that matches the given reference ID.
Parameters
- id string - The reference ID of the vector entry to delete
Return Type
- Error? -
ai:Error
if the reference ID is not found, otherwisenil
ai: McpToolKit
Represents a toolkit for interacting with an MCP server, invoking tools via the MCP protocol.
callTool
function callTool(CallToolParams params) returns CallToolResult|error
Parameters
- params CallToolParams -
getTools
function getTools() returns ToolConfig[]
ai: MessageWindowChatMemory
Provides an in-memory chat message window with a limit on stored messages.
Constructor
Initializes a new memory window with a default or given size.
init (int size)
- size int 10 - The maximum capacity for stored messages
get
function get(string sessionId) returns ChatMessage[]|MemoryError
Retrieves a copy of all stored messages, with an optional system prompt.
Parameters
- sessionId string - The ID associated with the memory
Return Type
- ChatMessage[]|MemoryError - A copy of the messages, or an
ai:Error
update
function update(string sessionId, ChatMessage message) returns MemoryError?
Adds a message to the window.
Parameters
- sessionId string - The ID associated with the memory
- message ChatMessage - The
ChatMessage
to store or use as system prompt
Return Type
- MemoryError? - nil on success, or an
ai:Error
if the operation fails
delete
function delete(string sessionId) returns MemoryError?
Removes all messages from the memory.
Parameters
- sessionId string - The ID associated with the memory
Return Type
- MemoryError? - nil on success, or an
ai:Error
if the operation fails
ai: ToolStore
Constructor
Register tools to the agent. These tools will be by the LLM to perform tasks.
init ((BaseToolKit|ToolConfig|FunctionTool)... tools)
- tools (BaseToolKit|ToolConfig|FunctionTool)... - A list of tools that are available to the LLM
execute
function execute(LlmToolResponse action) returns ToolOutput|LlmInvalidGenerationError|ToolExecutionError
execute the tool decided by the LLM.
Parameters
- action LlmToolResponse - Action object that contains the tool name and inputs
Return Type
- ToolOutput|LlmInvalidGenerationError|ToolExecutionError - ActionResult containing the results of the tool execution or an error if tool execution fails
Fields
ai: VectorKnowledgeBase
Represents a vector knowledge base for managing chunk indexing and retrieval operations.
The VectorKnowledgeBase
handles converting chunks to embeddings,
storing them in a vector store, and enabling retrieval through a Retriever
.
Constructor
Initializes a new VectorKnowledgeBase
instance.
init (VectorStore vectorStore, EmbeddingProvider embeddingModel)
- vectorStore VectorStore - The vector store for embedding persistence
- embeddingModel EmbeddingProvider - The embedding provider for generating vector representations
ingest
Indexes a collection of chunks. Converts each chunk to an embedding and stores it in the vector store, making the chunk searchable through the retriever.
Parameters
- chunks Chunk[] - The array of chunk to index
Return Type
- Error? - An
ai:Error
if indexing fails; otherwise,nil
retrieve
function retrieve(string query, MetadataFilters? filters) returns QueryMatch[]|Error
Retrieves relevant chunk for the given query.
Parameters
- query string - The text query to search for
- filters MetadataFilters? (default ()) - Optional metadata filters to apply during retrieval
Return Type
- QueryMatch[]|Error - An array of matching chunks with similarity scores, or an
ai:Error
if retrieval fails
ai: VectorRetriever
Represents a retriever that finds relevant chunks based on query similarity.
The Retriever
combines query embedding generation and vector search
to return matching chunks along with their similarity scores.
Constructor
Initializes a new Retriever
instance.
init (VectorStore vectorStore, EmbeddingProvider embeddingModel)
- vectorStore VectorStore - The vector store to search in
- embeddingModel EmbeddingProvider - The embedding provider to use for generating query embeddings
retrieve
function retrieve(string query, MetadataFilters? filters) returns QueryMatch[]|Error
Retrieves relevant chunks for the given query.
Parameters
- query string - The text query to search for
- filters MetadataFilters? (default ()) - Optional metadata filters to apply during retrieval
Return Type
- QueryMatch[]|Error - An array of matching chunks with similarity scores, or an
ai:Error
if retrieval fails
Clients
ai: ChatClient
A client class for interacting with a chat service.
Constructor
Initializes the ChatClient
with the provided service URL and configuration.
init (string serviceUrl, *ChatClientConfiguration clientConfig)
- serviceUrl string - The base URL of the chat service.
- clientConfig *ChatClientConfiguration - Configuration options for the chat client.
post chat
function post chat(ChatReqMessage request) returns ChatRespMessage|error
Handles incoming chat messages by sending a request to the chat service.
Parameters
- request ChatReqMessage - The chat request message to be sent.
Return Type
- ChatRespMessage|error - A
ChatRespMessage
containing the response from the chat service, or anerror
if the request fails.
ai: Wso2EmbeddingProvider
WSO2 embedding provider implementation that provides embedding capabilities using WSO2's AI service.
Constructor
Initializes a new Wso2EmbeddingProvider
instance.
init (string serviceUrl, string accessToken, *ConnectionConfig connectionConfig)
- serviceUrl string - The base URL of WSO2 intelligence API endpoint
- accessToken string - The access token for authenticating API requests
- connectionConfig *ConnectionConfig - Additional HTTP connection configuration
embed
Converts chunk to embedding.
Parameters
- chunk Chunk - The data to embed
Return Type
batchEmbed
Converts a batch of chunks into embeddings.
Parameters
- chunks Chunk[] - The array of chunks to be converted into embeddings
ai: Wso2ModelProvider
WSO2 model provider implementation that provides chat completion capabilities using WSO2's AI services.
Constructor
Initializes a new WSO2ModelProvider
instance.
init (string serviceUrl, string accessToken, decimal temperature, *ConnectionConfig connectionConfig)
- serviceUrl string - The base URL of WSO2 intelligence API endpoint
- accessToken string - The access token for authenticating API requests
- temperature decimal DEFAULT_TEMPERATURE - The temperature for controlling randomness in the model's output
- connectionConfig *ConnectionConfig - Additional HTTP connection configuration
chat
function chat(ChatMessage[]|ChatUserMessage messages, ChatCompletionFunctions[] tools, string? stop) returns ChatAssistantMessage|Error
Sends a chat request to the model with the given messages and tools.
Parameters
- messages ChatMessage[]|ChatUserMessage - List of chat messages or a user message
- tools ChatCompletionFunctions[] - Tool definitions to be used for the tool call
- stop string? (default ()) - Stop sequence to stop the completion
Return Type
- ChatAssistantMessage|Error - Function to be called, chat response or an error in-case of failures
generate
Sends a chat request to the model and generates a value that belongs to the type corresponding to the type descriptor argument.
Parameters
- prompt Prompt - The prompt to use in the chat messages
- td typedesc<anydata> (default <>) - Type descriptor specifying the expected return type format
Return Type
- td|Error - Generates a value that belongs to the type, or an error if generation fails
Service types
ai: ChatService
Defines a chat service interface that handles incoming chat messages.
post chat
function post chat(ChatReqMessage request) returns ChatRespMessage|error
Parameters
- request ChatReqMessage -
Enums
ai: AgentType
Represents the different types of agents supported by the module.
Members
ai: EncodingStyle
Members
ai: HeaderStyle
Members
ai: HttpMethod
Supported HTTP methods.
Members
ai: InputType
Supported input types by the Tool schemas.
Members
ai: MetadataFilterCondition
Represents logical conditions for combining multiple metadata filtering during vector search operations.
Members
ai: MetadataFilterOperator
Represents the set of supported operators used for metadata filtering during vector search operations.
Members
ai: ParameterLocation
Members
ai: RecursiveChunkStrategy
Represents the available strategies for recursively chunking a document.
Each strategy attempts to include as much content as possible using a specific unit (such as paragraph or sentence).
If the content exceeds the defined maxChunkSize
in RecursiveChunker
, the strategy recursively falls back
to a finer-grained unit until the content fits within the limit.
Members
ai: ROLE
Roles for the chat messages.
Members
ai: SimilarityMetric
Represents the similarity metrics used for comparing vectors. Defines how the similarity between vectors is calculated during search operations.
Members
ai: VectorStoreQueryMode
Represents query modes to be used with vector store. Defines different search strategies for retrieving relevant chunks based on the type of embeddings and search algorithms to be used.
Members
Listeners
ai: Listener
A server listener for handling chat service requests.
attach
function attach(ChatService chatService, string[]|string? name) returns error?
detach
function detach(ChatService chatService) returns error?
Parameters
- chatService ChatService -
'start
function 'start() returns error?
gracefulStop
function gracefulStop() returns error?
immediateStop
function immediateStop() returns error?
Annotations
ai: AgentTool
Represents the annotation of a function tool.
ai: JsonSchema
Configurables
ai: wso2ProviderConfig
Configurable for WSO2 provider.
Records
ai: AdditionInfoFlags
Defines additional information to be extracted from the OpenAPI specification.
Fields
- extractDescription boolean(default false) - Flag to extract description of parameters and schema attributes from the OpenAPI specification
- extractDefault boolean(default false) - Flag to extract default values of parameters and schema attributes from the OpenAPI specification
ai: AgentConfiguration
Provides a set of configurations for the agent.
Fields
- systemPrompt SystemPrompt - The system prompt assigned to the agent
- model ModelProvider - The model used by the agent
- tools (BaseToolKit|ToolConfig|FunctionTool)[](default []) - The tools available for the agent
- maxIter INFER_TOOL_COUNT|int(default INFER_TOOL_COUNT) - The maximum number of iterations the agent performs to complete the task. By default, it is set to the number of tools + 1.
- verbose boolean(default false) - Specifies whether verbose logging is enabled
ai: AllOfInputSchema
Defines an allOf
input field in the schema. Follows OpenAPI 3.x specification.
Fields
- Fields Included from *BaseInputSchema
- allOf JsonSubSchema[] - List of possible input types
ai: AllOfSchema
All of schema object.
Fields
- Fields Included from *BaseSchema
- allOf Schema[] - List of schemas that should match
ai: AnyOfInputSchema
Defines an anyOf
input field in the schema. Follows OpenAPI 3.x specification.
Fields
- Fields Included from *BaseInputSchema
- anyOf JsonSubSchema[] - List of possible input types
ai: AnyOfSchema
Any of schema object.
Fields
- Fields Included from *BaseSchema
- anyOf Schema[] - List of schemas that should match
- discriminator? Discriminator - Discriminator
ai: ArrayInputSchema
Defines an array input field in the schema.
Fields
- Fields Included from *BaseInputTypeSchema
- 'type ARRAY(default ARRAY) - Input data type. Should be
ARRAY
.
- items JsonSubSchema - Schema of the array items
- default? json[] - Default value for the array
ai: ArraySchema
Array schema object.
Fields
- Fields Included from *BaseTypeSchema
- 'type ARRAY(default ARRAY) - Type of the array schema
- uniqueItems? boolean - Whether the array items are unique
- items Schema - Schema of the array items
- minItems? int - Minimum number of items in the array
- maxItems? int - Maximum number of items in the array
- properties? never - Not allowed properties
ai: AudioDocument
Represents an audio document.
Fields
- Fields Included from *Document
- 'typereadonly "audio" (default "audio") - Fixed type identifier for audio documents
- content Url|byte[] - Audio content, either a URL or binary data
ai: BaseInputSchema
Defines a base input type schema.
Fields
- description? string - Description of the input
- default? json - Default value of the input
- nullable? boolean - Indicates whether the value can be null.
ai: BaseInputTypeSchema
Defines a base input schema with type field.
Fields
- Fields Included from *BaseInputSchema
- 'type InputType - Input data type
ai: BasePrimitiveTypeSchema
Base primitive type schema object.
Fields
- Fields Included from *BaseTypeSchema
- properties? never - Can not have properties in a primitive type schema
- items? never - Can not have items in a primitive type schema
ai: BaseSchema
Base schema object.
Fields
- description? string - Description of the schema
- default? json - Default value of the schema
- nullable? boolean - Whether the value is nullable
- 'xml? XmlSchema - Xml schema
- \$ref? never - Not allowed $ref property
ai: BaseTypeSchema
Base type schema object.
Fields
- Fields Included from *BaseSchema
- 'type string - Type of the schema
- anyOf? never - Not allowed anyOf
- oneOf? never - Not allowed oneOf
- allOf? never - Not allowed allOf
- not? never - Not allowed not
ai: BooleanSchema
Boolean schema object.
Fields
- Fields Included from *BasePrimitiveTypeSchema
- 'type BOOLEAN - Type of the boolean schema
ai: ChatAssistantMessage
Assistant chat message record.
Fields
- role ASSISTANT - Role of the message
- content string?(default ()) - The contents of the assistant message
Required unless
tool_calls
orfunction_call
is specified
- name? string - An optional name for the participant Provides the model information to differentiate between participants of the same role
- toolCalls FunctionCall[]?(default ()) - The function calls generated by the model, such as function calls
ai: ChatClientConfiguration
Represents the configuration for a chat client.
ai: ChatCompletionFunctions
Function definitions for function calling API.
Fields
- name string - Name of the function
- description string - Description of the function
- parameters? map<json> - Parameters of the function
ai: ChatFunctionMessage
Function message record.
Fields
- role FUNCTION - Role of the message
- content string?(default ()) - Content of the message
- name string - Name of the function when the message is a function call
- id? string - Identifier for the tool call
ai: ChatReqMessage
Represents a request message for the chat service.
Fields
- sessionId string - A unique identifier for the chat session.
- message string - The content of the chat message sent by the user.
ai: ChatRespMessage
Represents a response message from the chat service.
Fields
- message string - The response message generated by the chat service.
ai: ChatSystemMessage
System chat message record.
Fields
- role SYSTEM - Role of the message
- name? string - An optional name for the participant Provides the model information to differentiate between participants of the same role
ai: ChatUserMessage
User chat message record.
Fields
- role USER - Role of the message
- name? string - An optional name for the participant Provides the model information to differentiate between participants of the same role
ai: Chunk
Represents a chunk of a document.
Fields
- Fields Included from *Document
ai: Components
Map of component objects.
Fields
- requestBodies? map<RequestBody|Reference> - A map of reusable request body objects
ai: ConnectionConfig
Configurations for controlling the behaviours when communicating with a remote HTTP endpoint.
Fields
- httpVersion HttpVersion(default http:HTTP_2_0) - The HTTP version understood by the client
- http1Settings ClientHttp1Settings(default {}) - Configurations related to HTTP/1.x protocol
- http2Settings ClientHttp2Settings(default {}) - Configurations related to HTTP/2 protocol
- timeout decimal(default 60) - The maximum time to wait (in seconds) for a response before closing the connection
- forwarded string(default "disable") - The choice of setting
forwarded
/x-forwarded
header
- poolConfig? PoolConfiguration - Configurations associated with request pooling
- cache CacheConfig(default {}) - HTTP caching related configurations
- compression Compression(default http:COMPRESSION_AUTO) - Specifies the way of handling compression (
accept-encoding
) header
- circuitBreaker? CircuitBreakerConfig - Configurations associated with the behaviour of the Circuit Breaker
- retryConfig? RetryConfig - Configurations associated with retrying
- responseLimits ResponseLimitConfigs(default {}) - Configurations associated with inbound response size limits
- secureSocket? ClientSecureSocket - SSL/TLS-related options
- proxy? ProxyConfig - Proxy server related options
- validation boolean(default true) - Enables the inbound payload validation functionality which provided by the constraint package. Enabled by default
ai: ConstantValueSchema
Defines a constant value field in the schema.
Fields
- 'const json - The constant value.
ai: Discriminator
Discriminator object.
Fields
- propertyName string - Name of the property that specifies the type
ai: Document
Represents the common structure for all document types
Fields
- 'type string - The type of the document or chunk
- metadata? Metadata - Associated metadata
- content anydata - The actual content
ai: Encoding
Describes a encoding definition applied to a schema property.
Fields
- style? string - Describes how a specific property value will be serialized depending on its type
- explode? boolean - When this is true, property values of type array or object generate separate parameters for each value of the array, or key-value-pair of the map
- contentType? string - The Content-Type for encoding a specific property
ai: ExecutionError
Fields
- llmResponse json - Response generated by the LLM
- 'error LlmInvalidGenerationError|ToolExecutionError|MemoryError - Error caused during the execution
- observation string - Observation on the caused error as additional instruction to the LLM
ai: ExecutionProgress
Execution progress record
Fields
- query string - Question to the agent
- history ExecutionStep[](default []) - Execution history up to the current action
ai: ExecutionResult
Execution step information
Fields
- tool LlmToolResponse - Tool decided by the LLM during the reasoning
- observation anydata|error - Observations produced by the tool during the execution
ai: ExecutionStep
Execution step information
Fields
- llmResponse json - Response generated by the LLM
- observation anydata|error - Observations produced by the tool during the execution
ai: FileDocument
Represents a generic file document.
Fields
- Fields Included from *Document
- 'typereadonly "file" (default "file") - Fixed type identifier for file documents
ai: FileId
Represents an ID referring to a file.
Fields
- fileId string - Unique identifier for the file
ai: FunctionCall
Function call record
Fields
- name string - Name of the function
- arguments map<json>?(default {}) - Arguments of the function
- id? string - Identifier for the tool call
ai: Header
Describes HTTP headers.
Fields
- required? boolean - Whether this header parameter is mandatory
- description? string - A brief description of the header parameter
- allowEmptyValue? string - Whether empty value is allowed
- style? HeaderStyle - Describes how a specific property value will be serialized depending on its type
- explode? boolean - When this is true, property values of type array or object generate separate parameters for each value of the array, or key-value-pair of the map
- schema? Schema - Schema of the header parameter
- \$ref? never - Not allowed $ref
ai: HttpApiSpecification
Provides extracted tools and service URL from the OpenAPI specification.
Fields
- serviceUrl? string - Extracted service URL from the OpenAPI specification if there is any
- tools HttpTool[] - Extracted Http tools from the OpenAPI specification
ai: HttpOutput
Defines an HTTP output record for requests.
Fields
- code int - HTTP status code of the response
- path string - HTTP path url with encoded paramteres
- body? json|xml - Response payload
ai: HttpTool
Defines an HTTP tool. This is a special type of tool that can be used to invoke HTTP resources.
Fields
- name string - Name of the Http resource tool
- description string - Description of the Http resource tool used by the LLM
- method HttpMethod - Http method type (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)
- path string - Path of the Http resource
- parameters? map<ParameterSchema> - path and query parameters definitions of the Http resource
- requestBody? RequestBodySchema - Request body definition of the Http resource
ai: HybridVector
Represents a hybrid embedding containing both dense and sparse vector representations.
Fields
- dense Vector - Dense vector representation of the embedding
- sparse SparseVector - Sparse vector representation of the embedding
ai: ImageDocument
Represents an image document.
Fields
- Fields Included from *Document
- 'typereadonly "image" (default "image") - Fixed type identifier for image documents
- content Url|byte[] - Image content, either a URL or binary data
ai: IntegerSchema
Integer schema object.
Fields
- Fields Included from *BasePrimitiveTypeSchema
- 'type INTEGER - Type of the integer schema
- format? string - Format of the value
- minimum? int - Minimum value of the integer value
- maximum? int - Maximum value of the integer value
- exclusiveMinimum? boolean - Whether the minimum value is exclusive
- exclusiveMaximum? boolean - Whether the maximum value is exclusive
- multipleOf? int - Multiplier of the integer value
ai: InternalValueSchema
Defines a internal value field in the schema
Fields
- Fields Included from *ConstantValueSchema
- const json
ai: LlmToolResponse
Tool selected by LLM to be performed by the agent
Fields
- name string - Name of the tool to selected
- arguments map<json>?(default {}) - Input to the tool
- id? string - Identifier for the tool call
ai: MediaType
Defines media type of a parameter, response body or header.
Fields
- schema Schema(default {}) - Schema of the content
ai: Metadata
Represents additional metadata associated with documents or nodes.
Fields
- mimeType? string - MIME type specification for the file
- fileName? string - File name for the document
- fileSize? decimal - File size in bytes
- createdAt? Utc - Creation timestamp of the file
- modifiedAt? Utc - Modification timestamp of the file
- json... - Rest field
ai: MetadataFilter
Represents a metadata filter for vector search operations. Defines conditions to filter vectors based on their associated metadata values.
Fields
- key string - The name of the metadata field to filter
- operator MetadataFilterOperator(default EQUAL) - The comparison operator to use. Defaults to
EQUAL
- value json - The value to compare the metadata field against
ai: MetadataFilters
Represents a container for combining multiple metadata filters using logical operators. Enables complex filtering by applying multiple conditions with AND/OR logic during vector search.
Fields
- filters (MetadataFilters|MetadataFilter)[] - An array of
MetadataFilter
or nestedMetadataFilters
to apply
- condition MetadataFilterCondition(default AND) - The logical operator (
AND
orOR
) used to combine the filters. Defaults toAND
ai: NotInputSchema
Defines a not
input field in the schema. Follows OpenAPI 3.x specification.
Fields
- Fields Included from *BaseInputSchema
- not JsonSubSchema - Schema that is not accepted as an input
ai: NotSchema
Not schema object.
Fields
- Fields Included from *BaseSchema
- not Schema - Schema that should not match
ai: NumberSchema
Number schema object.
Fields
- Fields Included from *BasePrimitiveTypeSchema
- format? string - Format of the value
- exclusiveMinimum? boolean - Whether the minimum value is exclusive
- exclusiveMaximum? boolean - Whether the maximum value is exclusive
ai: ObjectInputSchema
Defines an object input field in the schema.
Fields
- Fields Included from *BaseInputTypeSchema
- 'type OBJECT(default OBJECT) - Input data type. Should be
OBJECT
.
- required? string[] - List of required properties
- properties? map<JsonSubSchema> - Schema of the object properties
ai: ObjectSchemaType1
Defines an bbject schema with type is specified and properties are optional.
Fields
- Fields Included from *BaseTypeSchema
- 'type OBJECT - Type of the object schema
- minProperties? int - Minimum number of properties in the object
- maxProperties? int - Maximum number of properties in the object
- discriminator? Discriminator - Discriminator
- items? never - Not allowed items. Distinction between array and object
ai: ObjectSchemaType2
Defines an object schema with the properties defined and type is unspecified.
Fields
- Fields Included from *ObjectSchemaType1
- type "object"
- minProperties int
- maxProperties int
- required boolean|string[]
- properties map<Schema>
- additionalProperties boolean|IntegerSchema|NumberSchema|StringSchema|BooleanSchema|ArraySchema|ObjectSchemaType1|ObjectSchemaType2|OneOfSchema|AllOfSchema|AnyOfSchema|NotSchema|Reference
- discriminator Discriminator
- items never
- anyOf never
- oneOf never
- allOf never
- not never
- description string
- default json
- nullable boolean
- xml XmlSchema
- \$ref never
- anydata...
- 'type? never - To match when type is not specified, but properties are specified
ai: OneOfInputSchema
Defines an oneOf
input field in the schema. Follows OpenAPI 3.x specification.
Fields
- oneOf JsonSubSchema[] - List of possible input types
- nullable? boolean - Indicates whether the value can be null.
- description? string - Description of the input
ai: OneOfSchema
One of schema object.
Fields
- Fields Included from *BaseSchema
- oneOf Schema[] - List of schemas that should match
- discriminator? Discriminator - Discriminator
ai: OpenApiSpec
OpenAPI Specification 3.1.0
Fields
- openapi string - OpenAPI version
- servers? Server[] - Server information
- paths? Paths - Server resource definitions
- components? Components - Reference objects
ai: Operation
Describes a single API operation on a path.
Fields
- tags? string[] - A list of tags for API documentation control
- summary? string - A short summary of what the operation does
- description? string - A description explanation of the operation behavior
- operationId? string - Operation ID for referencing the operation
- requestBody? RequestBody|Reference - The request body applicable for this operation
ai: Parameter
Describes a single operation parameter.
Fields
- name string - Name of the parameter
- 'in ParameterLocation - The location of the parameter
- required? boolean - Whether the parameter is mandatory
- description? string - A brief description of the parameter
- allowEmptyValue? boolean - Whether empty value is allowed
- style? EncodingStyle - Describes how a specific property value will be serialized depending on its type
- explode? boolean - When this is true, property values of type array or object generate separate parameters for each value of the array, or key-value-pair of the map
- schema? Schema - Schema of the parameter
- nullable? boolean - Null value is allowed
ai: ParameterSchema
Defines a HTTP parameter schema (can be query parameter or path parameters).
Fields
- description? string - A brief description of the parameter
- required? boolean - Whether the parameter is mandatory
- style? EncodingStyle - Describes how a specific property value will be serialized depending on its type
- explode? boolean - When this is true, property values of type array or object generate separate parameters for each value of the array, or key-value-pair of the map.
- nullable? boolean - Null value is allowed
- allowEmptyValue? boolean - Whether empty value is allowed
- mediaType? string - Content type of the schema
- schema JsonSubSchema - Parameter schema
ai: PathItem
Describes a single path item.
Fields
- description? string - Description of the path item
- summary? string - Summary of the path item
- get? Operation - GET operation
- post? Operation - POST operation
- put? Operation - PUT operation
- delete? Operation - DELETE operation
- options? Operation - OPTIONS operation
- head? Operation - HEAD operation
- patch? Operation - PATCH operation
- trace? Operation - TRACE operation
- servers? Server[] - Server information for the path
- \$ref? never - Not allowed $ref
ai: Paths
Map of pathItem objects.
Fields
- PathItem|Reference... - Rest field
ai: PrimitiveInputSchema
Defines a primitive input field in the schema.
Fields
- Fields Included from *BaseInputTypeSchema
- format? string - Format of the input. This is not applicable for
BOOLEAN
type.
- pattern? string - Pattern of the input. This is only applicable for
STRING
type.
- 'enum? (PrimitiveType?)[] - Enum values of the input. This is only applicable for
STRING
type.
- default? PrimitiveType - Default value of the input
ai: QueryMatch
Represents a match result with similarity score.
Fields
- chunk Chunk - The chunk that matched the query
- similarityScore float - Similarity score indicating chunk relevance to the query
ai: Reference
Defines a reference object.
Fields
- \$ref string - Reference to a component
- summary? string - Short description of the target component
- 'xml? XmlSchema - Xml schema
- description? string - Detailed description of the target component
ai: RequestBody
Describes a single request body.
Fields
- description? string - A brief description of the request body. This could contain examples of use.
- required? boolean - Whether the request body is mandatory in the request.
ai: RequestBodySchema
Fields
- description? string - A brief description of the request body
- mediaType? string - Content type of the request body
- schema JsonSubSchema - Request body schema
ai: Response
Describes a single response from an API Operation.
Fields
- description? string - A short description of the response
- \$ref? never - Not allowed $ref
ai: Responses
Describes the responses from an API Operation.
Fields
- Response|Reference... - Rest field
ai: Server
Server information object.
Fields
- url string - A URL to the target host
- description? string - An optional string describing the host designated by the URL
ai: SparseVector
Represents a sparse vector storing only non-zero values with their corresponding indices.
Fields
- indices int[] - Array of indices where non-zero values are located
- values Vector - Array of non-zero floating-point values corresponding to the indices
ai: StringSchema
String schema object.
Fields
- Fields Included from *BasePrimitiveTypeSchema
- 'type STRING(default STRING) - Type of the string schema
- format? string - Format of the string
- minLength? int - Minimum length of the string value
- maxLength? int - Maximum length of the string value
- pattern? string - Regular expression pattern of the string value
- 'enum? (PrimitiveType?)[] - Enum values of the string value
ai: SystemPrompt
Represents the system prompt given to the agent.
Fields
- role string - The role or responsibility assigned to the agent
- instructions string - Specific instructions for the agent
ai: TextChunk
Represents a chunk of text within a document.
Fields
- Fields Included from *Chunk
- 'typereadonly "text-chunk" (default "text-chunk") - Fixed type for the text chunk
- content string - The text content of the chunk
ai: TextDocument
Represents documents containing plain text content
Fields
- Fields Included from *Document
- 'typereadonly "text" (default "text") - Fixed type for the text document
- content string - The text content of the document
ai: Tool
This is the tool used by LLMs during reasoning. This tool is same as the Tool record, but it has a clear separation between the variables that should be generated with the help of the LLMs and the constants that are defined by the users.
Fields
- name string - Name of the tool
- description string - Description of the tool
- variables? map<json> - Variables that should be generated with the help of the LLMs
- constants map<json>(default {}) - Constants that are defined by the users
- caller
function() ()
- Function that should be called to execute the tool
ai: ToolAnnotationConfig
Defines the configuration of the Tool annotation.
Fields
- name? string - The name of the tool. If not provided, defaults to the function pointer name.
- description? string - A description of the tool. This is used by LLMs to understand the tool's behavior.
If not provided, the doc comment used as the description.
- parameters? ObjectInputSchema? - The input schema expected by the tool. If the tool does not expect any input, this should be null.
If not provided, the input schema is generated automatically.
ai: ToolConfig
Defines a tool. This is the only tool type directly understood by the agent. All other tool types are converted to this type using toolkits.
Fields
- name string - Name of the tool
- description string - A description of the tool. This is used by the LLMs to understand the behavior of the tool.
- parameters map<json>?(default ()) - Input schema expected by the tool. If the tool doesn't expect any input, this should be null.
- caller FunctionTool - Pointer to the function that should be called when the tool is invoked.
ai: ToolExecutionResult
Represent the execution result of a tool.
Fields
- result any|error - Return value of the tool
ai: ToolOutput
Output from executing an action
Fields
- value anydata|error - Output value the tool
ai: VectorEntry
Represents a vector entry combining an embedding with its source chunk.
Fields
- id? string - Optional unique identifier for the vector entry
- embedding Embedding - The vector representation of the chunk content
- chunk Chunk - The chunk associated with the embedding
ai: VectorMatch
Represents a vector match result with similarity score.
Fields
- Fields Included from *VectorEntry
- similarityScore float - Similarity score indicating how closely the vector matches the query
ai: VectorStoreQuery
Defines a query to the vector store with an embedding vector and optional metadata filters. Supports precise search operations by combining vector similarity with metadata conditions.
Fields
- embedding Embedding - The vector to use for similarity search
- filters? MetadataFilters - Optional metadata filters to refine the search results.
ai: Wso2ProviderConfig
Represents configuratations of WSO2 provider.
Fields
- serviceUrl string - The URL for the WSO2 AI service
- accessToken string - Access token for accessing WSO2 AI service
ai: XmlSchema
Fields
- name? string - Replaces the name of the element/attribute used for the described schema property.
- namespace? string - The URI of the namespace definition.
- prefix? string - The prefix to be used for the name.
- attribute? boolean - Declares whether the property definition translates to an attribute instead of an element.
- wrapped? boolean - May be used only for an array definition.
Errors
ai: Error
Defines the common error type for the module.
ai: HttpResponseParsingError
Any error occurred during parsing HTTP response is classified under this error type.
ai: HttpServiceToolKitError
Errors occurred due while running HTTP service toolkit.
ai: IncompleteSpecificationError
Errors due to incomplete OpenAPI specification.
ai: InvalidParameterDefinition
Error through due to invalid parameter definition that does not include either schema or content.
ai: InvalidReferenceError
Errors due to invalid or broken references in the OpenAPI specification.
ai: LlmConnectionError
Errors occurred during LLM generation due to connection.
ai: LlmError
Any error occurred during LLM generation is classified under this error type.
ai: LlmInvalidGenerationError
Errors occurred due to invalid LLM generation.
ai: LlmInvalidResponseError
Errors occurred due to unexpected responses from the LLM.
ai: MaxIterationExceededError
Represents an error that occurs when the maximum number of iterations has been exceeded.
ai: MemoryError
Represents errors that occur during memory-related operations.
ai: MissingHttpParameterError
Errors occurred due to missing mandotary path or query parameters.
ai: OpenApiParsingError
Any error occurred during parsing OpenAPI specification is classified under this error type.
ai: ParsingStackOverflowError
Stackoverflow errors due to lenthy OpenAPI specification or cyclic references in the specification.
ai: TaskCompletedError
Errors occurred due to termination of the Agent's execution.
ai: ToolExecutionError
Errors during tool execution.
ai: ToolInvalidInputError
Errors occurred due to invalid input to the tool generated by the LLM.
ai: ToolInvalidOutputError
Error during unexpected output by the tool
ai: ToolNotFoundError
Errors occurred due to invalid tool name generated by the LLM.
ai: UnsupportedMediaTypeError
Errors due to unsupported media type.
ai: UnsupportedOpenApiVersion
Errors due to unsupported OpenAPI specification version.
ai: UnsupportedSerializationError
Errors occurred due to unsupported path parameter serializations.
Object types
ai: BaseToolKit
Allows implmenting custom toolkits by extending this type. Toolkits can help to define new types of tools so that agent can understand them.
getTools
function getTools() returns ToolConfig[]
Useful to retrieve the Tools extracted from the Toolkit.
Return Type
- ToolConfig[] - An array of Tools
ai: EmbeddingProvider
Represents an embedding provider that converts chunk into vector embeddings for similarity search.
embed
Converts the given chunk into a vector embedding.
Parameters
- chunk Chunk - The chunk to be convert into an embedding
Return Type
batchEmbed
Converts a batch of chunks into vector embeddings.
Parameters
- chunks Chunk[] - The array of chunks to be converted into embeddings
ai: KnowledgeBase
Represents a knowledge base for managing chunk indexing and retrieval operations.
ingest
Ingests a collection of chunks.
Parameters
- chunks Chunk[] - The array of chunk to index
Return Type
- Error? - An
ai:Error
if indexing fails; otherwise,nil
retrieve
function retrieve(string query, MetadataFilters? filters) returns QueryMatch[]|Error
Retrieves relevant chunks for the given query.
Parameters
- query string - The text query to search for
- filters MetadataFilters? (default ()) - Optional metadata filters to apply during retrieval
Return Type
- QueryMatch[]|Error - An array of matching chunks with similarity scores, or an
ai:Error
if retrieval fails
ai: Memory
Represents the memory interface for the agents.
get
function get(string sessionId) returns ChatMessage[]|MemoryError
Retrieves all stored chat messages.
Parameters
- sessionId string - The ID associated with the memory
Return Type
- ChatMessage[]|MemoryError - An array of messages or an
ai:Error
update
function update(string sessionId, ChatMessage message) returns MemoryError?
Adds a chat message to the memory.
Parameters
- sessionId string - The ID associated with the memory
- message ChatMessage - The message to store
Return Type
- MemoryError? - nil on success, or an
ai:Error
if the operation fails
delete
function delete(string sessionId) returns MemoryError?
Deletes all stored messages.
Parameters
- sessionId string - The ID associated with the memory
Return Type
- MemoryError? - nil on success, or an
ai:Error
if the operation fails
ai: ModelProvider
Represents an extendable client for interacting with an AI model.
chat
function chat(ChatMessage[]|ChatUserMessage messages, ChatCompletionFunctions[] tools, string? stop) returns ChatAssistantMessage|Error
Sends a chat request to the model with the given messages and tools.
Parameters
- messages ChatMessage[]|ChatUserMessage - List of chat messages or a user message
- tools ChatCompletionFunctions[] (default []) - Tool definitions to be used for the tool call
- stop string? (default ()) - Stop sequence to stop the completion
Return Type
- ChatAssistantMessage|Error - Function to be called, chat response or an error in-case of failures
generate
Sends a chat request to the model and generates a value that belongs to the type corresponding to the type descriptor argument.
Parameters
- prompt Prompt - The prompt to use in the chat request
- td typedesc<anydata> (default <>) - Type descriptor specifying the expected return type format
Return Type
- td|Error - Generates a value that belongs to the type, or an error if generation fails
ai: Prompt
Raw template type for prompts.
Fields
- Fields Included from *RawTemplate
- strings string[] & readonly - The fixed string parts of the template.
ai: Retriever
Represents chunk retriever that finds relevant chunks based on query similarity.
retrieve
function retrieve(string query, MetadataFilters? filters) returns QueryMatch[]|Error
Retrieves relevant chunks for the given query.
Parameters
- query string - The text query to search for
- filters MetadataFilters? (default ()) - Optional metadata filters to apply during retrieval
Return Type
- QueryMatch[]|Error - An array of matching chunks with similarity scores, or an
ai:Error
if retrieval fails
ai: VectorStore
Represents a vector store that provides persistence, management, and search capabilities for vector embeddings.
add
function add(VectorEntry[] entries) returns Error?
Adds vector entries to the store.
Parameters
- entries VectorEntry[] - The array of vector entries to add
Return Type
- Error? - An
ai:Error
if the operation fails; otherwise,nil
query
function query(VectorStoreQuery query) returns VectorMatch[]|Error
Searches for vectors in the store that are most similar to a given query.
Parameters
- query VectorStoreQuery - The vector store query that specifies the search criteria
Return Type
- VectorMatch[]|Error - An array of matching vectors with their similarity scores,
or an
ai:Error
if the operation fails
delete
Deletes a vector entry from the store by its unique ID.
Parameters
- id string - The unique identifier of the vector entry to delete
Return Type
- Error? - An
ai:Error
if the operation fails; otherwise,nil
Union types
ai: PrimitiveTypeSchema
PrimitiveTypeSchema
Primitive type schema object.
ai: ObjectSchema
ObjectSchema
Defines an object schema.
ai: Schema
Schema
Defines a OpenAPI schema.
ai: Embedding
Embedding
Represents possible vector types.
ai: ChatMessage
ChatMessage
Chat message record.
ai: PrimitiveType
PrimitiveType
Primitive types supported by the Tool schemas.
ai: JsonInputSchema
JsonInputSchema
Defines a json input schema
ai: JsonSubSchema
JsonSubSchema
Defines a json sub schema
Array types
ai: Vector
Vector
Represents a dense vector with floating-point values.
Function types
ai: FunctionTool
function() ()
FunctionTool
Represents a type alias for an isolated function, representing a function tool.
String types
ai: Url
Url
Represents a URL.
Import
import ballerina/ai;
Metadata
Released date: 2 days ago
Version: 1.1.1
License: Apache-2.0
Compatibility
Platform: java21
Ballerina version: 2201.12.0
GraalVM compatible: Yes
Pull count
Total: 856
Current verison: 220
Weekly downloads
Keywords
AI/Agent
Cost/Freemium
Agent
AI
Contributors
Dependents