Skip to main content

Functions Reference

This page documents the custom FLOIP functions available in Turn's Journey Builder. These functions extend the standard FLOIP specification with Turn-specific functionality.

Messaging

send_content()

Sends a content card (pre-defined message template) from Turn's content library.

Configuration:

FieldTypeRequiredDescription
content.uuiduuidYesUUID of the content card to send
content.wait_for_inputboolean | expressionYesWhether to wait for user input after sending

Example:

card Card do
send_content("content-uuid-here")
# Or wait for response:
resp = send_content("content-uuid-here", true)
end

add_label()

Adds a label to a message in the current context.

Configuration:

FieldTypeRequiredDescription
labelslistYesList of labels to apply
messagestringYesThe message reference to label

Example:

card Card do
add_label("important")
add_label(operator)
end

text()

Sends a text message to the user.

Configuration:

FieldTypeRequiredDescription
promptstringYesThe message content to send

Example:

card Greetings do
text("Hello @contact.name!")
text("Welcome to our service.")
end

Input

ask()

Asks the user for a free-form text response with optional character limit.

Configuration:

FieldTypeRequiredDescription
max_response_charactersnumberNoMaximum allowed response length
promptstringYesThe question to ask the user

Returns: The text response entered by the user

Example:

card AskName, then: Greetings do
name = ask("What's your name?")
end

card Greetings do
text("Hello @name!")
end

buttons()

Presents the user with a set of options as buttons and waits for them to select one.

Configuration:

FieldTypeRequiredDescription
choiceslistYesList of button options (card names or [value, label] pairs)
promptstringYesThe message text displayed with the buttons

Returns: Map with value, name, index, and label of the selected choice

Example:

card ReadDocument do
buttons([Accept, Decline]) do
text("Please read and accept the terms")
document("https://example.org/terms.pdf")
end
end

card Accept do
text("Thank you for accepting!")
end

Control

log()

Logs a message to the system log for debugging purposes.

Configuration:

FieldTypeRequiredDescription
messagestringYesThe message to log

Example:

card Card do
log("user not opted in for follow ups")
log("hello @today()")
end

run_stack()

Runs another journey (stack) and returns to the current flow when complete.

Configuration:

FieldTypeRequiredDescription
flow_iduuidYesUUID of the flow to run

Example:

card Card do
run_stack("10dca9d0-3f0b-11ed-b878-0242ac120002")
end

schedule_stack()

Schedules a journey to run at a future time, or cancels a previously scheduled journey.

Configuration:

FieldTypeRequiredDescription
flow_iduuidYesUUID of the flow to schedule
schedule_atdatetimeNoSpecific datetime to run the flow
schedule_inintegerNoNumber of seconds in the future to run the flow

Example:

card Card do
# Schedule to run in 1 hour
schedule_stack("10dca9d0-3f0b-11ed-b878-0242ac120002", in: 3600)

# Or schedule at a specific time
schedule_stack("some-uuid", at: datetime_add(now(), 2, "D"))
end

Notes: Either schedule_at or schedule_in must be provided. To cancel, only provide flow_id.


wait()

Introduces a delay in the journey flow to control timing between actions.

Configuration:

FieldTypeRequiredDescription
secondsinteger | expressionYesNumber of seconds to wait (supports expressions)

Example:

card DelayCard do
text("Starting delay...")
wait(2)
text("Delay completed!")
end

Contact

update_contact()

Updates one or more properties on the current contact.

Example:

card SavePreferences do
update_contact(name: "Boaty", surname: "McBoatFace")
update_contact(opted_in: true)
end

Data

update_dictionary()

Updates a key-value pair in a dictionary variable.

Configuration:

FieldTypeRequiredDescription
keystringYesThe key to set
referencestringYesThe dictionary variable to update
valueexpressionYesThe value expression to evaluate and store

Example:

card Deposit do
update_dictionary(account, "balance", account.balance + 1)
text("You've deposited $1")
end

Chat

assign_chat_to()

Assigns the current chat to a user or queue.

Configuration:

FieldTypeRequiredDescription
assign_tostringYesEmail of the user to assign the chat to

Example:

card Card do
assign_chat_to("support@example.com")
end

WhatsApp

catalog()

Displays a WhatsApp product catalog allowing users to browse and order products.

Configuration:

FieldTypeRequiredDescription
catalog.footerstringNoOptional footer text
catalog.textstringYesThe catalog body text

Returns: The user's order/selection from the catalog

Example:

card Card do
catalog("Check out our products!") do
footer("Visit our store")
end
end

request_location()

Requests the user's location via WhatsApp's native location sharing feature.

Configuration:

FieldTypeRequiredDescription
request_location.textstringYesThe message text prompting the user to share their location

Returns: The user's shared location data

Example:

card RequestLocation do
location = request_location("Please share your location")
end

card ThankYou, when: "@input.location != nil" do
text("Thank you for sharing your location!")
end

whatsapp_flow()

Sends a WhatsApp Flow (interactive form) for native data collection on WhatsApp.

Configuration:

FieldTypeRequiredDescription
flow.ctastringYesCall-to-action button text
flow.footerstringNoOptional footer text
flow.headerstringNoOptional header text
flow.idstringYesThe WhatsApp Flow ID
flow.screenstringYesThe screen to display
flow.textstringYesMessage body text

Returns: JSON data captured by the WhatsApp Flow

Example:

card Card do
whatsapp_flow("Start Survey", "flow-id", "WELCOME") do
text("Please complete our survey")
end
end

send_message_template()

Sends a WhatsApp message template with dynamic parameters.

Configuration:

FieldTypeRequiredDescription
template.componentslistYesList of template components with parameters
template.language.codestringYesLanguage code for the template
template.namestringYesThe name of the template

Returns: Map with value and index when template has reply buttons

Example:

card Card do
send_message_template("template_name", "en", ["param-1", "param-2"])
end

mark_as_read()

Marks a WhatsApp message as read and optionally shows a typing indicator.

Configuration:

FieldTypeRequiredDescription
message_idexpressionYesThe message ID to mark as read (e.g., @event.message.id)
show_typingbooleanNoWhether to show a typing indicator (default: false)

Returns: No value is returned; this is a fire-and-forget operation.

Example:

card MyCard do
# Simply mark the message as read
mark_as_read(@event.message.id)
end

card WithTypingIndicator do
# Mark as read and show typing indicator to simulate bot composing
mark_as_read(@event.message.id, show_typing: true)
wait(3)
text("Here's the information you requested...")
end

Notes: The typing indicator automatically disappears after 25 seconds or when the next message is sent. The journey continues regardless of whether the API call succeeds.


post_reaction()

Posts an emoji reaction to a WhatsApp message, or removes an existing reaction.

Configuration:

FieldTypeRequiredDescription
emojistringYesThe emoji to react with (use empty string to remove reaction)
message_idexpressionYesThe message ID to react to (e.g., @event.message.id)

Returns: No value is returned; this is a fire-and-forget operation.

Example:

card MyCard do
# React with thumbs up to the triggering message
post_reaction(@event.message.id, "👍")
end

card AcknowledgeAndProcess do
# React to acknowledge receipt
post_reaction(@event.message.id, "👀")
# Process the request...
text("Processing your request...")
end

card RemoveReaction do
# Remove an existing reaction by passing empty emoji
post_reaction(@event.message.id, "")
end

Notes: Pass an empty string as emoji to remove an existing reaction. The journey continues regardless of whether the API call succeeds.


Integration

conversion()

Sends conversion events to Meta's Conversions API for ad optimization and measurement.

Configuration:

FieldTypeRequiredDescription
conversion.event_namestringYesThe conversion event name (e.g., "Purchase", "Lead")
conversion.optional_fieldsmapNoOptional fields like event_id, event_source_url
conversion.user_datamapYesUser data for matching (email, phone, etc.)

Example:

card Card do
conversion("Purchase", phone: "+1234567890", email: "user@example.com")
end

get() / post() / put() / patch() / delete()

Makes HTTP requests to external APIs. Supports GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, and TRACE methods.

Configuration:

FieldTypeRequiredDescription
bodystring | listNoRequest body (string or key-value pairs)
headerslistYesList of [key, value] header pairs
methodstringYesHTTP method (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE)
modestringYes"sync" or "async" execution mode
querylistNoList of [key, value] query parameter pairs
timeoutnumberYesRequest timeout in milliseconds (max 20000)
urlstringYesThe URL to call

Returns: Map with url, status, body, query, mode, and headers of the response

Example:

card MyCard do
response = get("https://api.example.org/data",
timeout: 5000,
query: [["id", "@contact.id"]]
)
text("Status: @response.status")
end

app()

Calls a function in an installed Lua app and returns the result.

Configuration:

FieldTypeRequiredDescription
app_namestringYesThe name of the app definition to call
argslistYesList of arguments to pass to the function (supports expressions)
function_namestringYesThe name of the function to execute

Returns: A map with result (function return value) and success (boolean) fields. Also stored in app_result variable.

Example:

card MyCard do
# Call a function in a Lua app with arguments
result = app("calculator", "add_numbers", ["10", "20"])
text("Result: @(result.result)")
end

card WithExpressions do
# Use expressions to pass dynamic values
result = app("my_app", "process_data", ["@(contact.name)", "@(event.message.text)"])

# Check if the call succeeded
result when result.success do
text("Success: @(result.result)")
end

result when not result.success do
text("Error: @(result.result)")
end
end

card UsingAppResult do
# Results are also stored in the app_result variable
app("weather", "get_forecast", ["@(contact.city)"])
text("The weather is: @(app_result.result)")
end

Notes: The app must be installed and enabled. Function arguments support expressions that are evaluated at runtime.


AI (Vendor-Agnostic)

ai_add_function()

Adds a function definition to the AI context for tool calling.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesThe AI connection object
descriptionexpressionYesFunction description for the AI
nameexpressionYesFunction name
parametersexpressionYesJSON Schema defining function parameters

Returns: Updated connection object with the function definition added.

Example:

card MyCard do
ai = ai_connect("openai", "gpt-4", @(secrets.openai_token))

# Add a function the AI can call
ai = ai_add_function(ai, "make_booking", "Book an appointment for the user", parse_json("""
{
"type": "object",
"properties": {
"date": {"type": "string", "description": "Appointment date in YYYY-MM-DD format"},
"time": {"type": "string", "description": "Appointment time in HH:MM format"},
"service": {"type": "string", "enum": ["consultation", "followup", "checkup"]}
},
"required": ["date", "time", "service"]
}
"""))

ai = ai_add_message(ai, "user", @(event.message.text))
result = ai_chat_completion(ai)

# Check if the AI called a function
result when result.response.functions != [] do
# Handle the function call
text("Booking confirmed!")
end
end

Notes: Parameters must be a valid JSON Schema object. The AI will call the function when appropriate and return arguments in result.response.functions.


ai_add_image()

Adds an image to the AI context for vision-capable models.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesThe AI connection object
image_urlexpressionYesURL of the image (public URL or data URI)
max_tokensexpressionNoMaximum tokens for the response
promptexpressionYesText prompt describing what to do with the image
roleexpressionYesMessage role (typically user)

Returns: Updated connection object with the image message added.

Example:

card MyCard do
ai = ai_add_image(ai, "user", "Describe this image", @(event.message.image.url), 300)
end

ai_add_message()

Adds a single message to the AI conversation context.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesThe AI connection object
messageexpressionYesThe message content
roleexpressionYesMessage role (system, user, or assistant)

Returns: Updated connection object with the new message added.

Example:

card MyCard do
ai = ai_connect("openai", "gpt-4", @(secrets.openai_token))

# Add a system message to set the AI's behavior
ai = ai_add_message(ai, "system", "You are a helpful customer support agent.")

# Add the user's message
ai = ai_add_message(ai, "user", @(event.message.text))

# Get the AI response
result = ai_chat_completion(ai)
text(@(result.response))
end

Notes: Roles: system (instructions), user (customer input), assistant (AI responses for context).


ai_add_messages()

Adds multiple messages to the AI conversation context.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesThe AI connection object
messagesexpressionYesList of message contents
roleexpressionYesMessage role (system, user, or assistant)

Returns: Updated connection object with the new messages added.

Example:

card MyCard do
ai = ai_add_messages(ai, "user", ["Hello", "How are you?"])
end

ai_agent()

Runs an AI agent with intents, skills, and conversation memory for complex interactions.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesThe AI connection object
contact_fieldsexpressionNoContact fields to include in context
dataexpressionYesAdditional data context for the agent
instructionsexpressionYesSystem instructions for the agent
intentsexpressionYesList of intents the agent can recognize
skillslistNoList of skills the agent can call. Includes knowledge skills (static content) and code skills (Lua functions). See AI Agent Skills.

Returns: Agent response with action (recognized intent or 'continue_conversation'), response (AI text to display), status (HTTP status), and error (boolean).

Example:

# Agent conversation loop pattern
# The agent card calls itself to create a multi-turn conversation

card Agent do
ai = ai_assistant("assistant-uuid")
ai = ai_conversation_memory(ai, "journey")

# Define intents the agent can recognize
intents = parse_json("""
[
{"id": "book_appointment", "name": "Book Appointment", "description": "When the user wants to schedule an appointment"},
{"id": "get_info", "name": "Get Information", "description": "When the user asks about hours or services"}
]
""")

# Data to collect from the user (empty list if not collecting data)
data_to_collect = parse_json("[]")

agent_result = ai_agent(ai, "You are a friendly booking assistant. Help users schedule appointments.", intents, data_to_collect)

# Handle errors
then(ErrorCard when agent_result.error == true)

# Handle end of conversation
then(EndCard when agent_result.action == "end_conversation")

# Handle recognized intents - route to specific flows
then(BookAppointment when agent_result.action == "book_appointment")
then(GetInfo when agent_result.action == "get_info")

# Display the agent's response and wait for user input
ask("@agent_result.response")

# Loop back to continue the conversation
then(Agent when agent_result.action == "continue_conversation")
end

card ErrorCard do
text("Sorry, something went wrong. Please try again later.")
end

card EndCard do
text("Thank you for chatting! Have a great day.")
end

card BookAppointment do
run_stack("booking-flow-uuid")
end

card GetInfo do
text("We're open Monday-Friday, 9am-5pm at 123 Main St.")
end

Notes: Create conversation loops by having the agent card call itself when action is 'continue_conversation'. Use ask() to display the response and wait for user input. Built-in actions: submit_recognized_intent() triggers intent routing, end_conversation() ends the loop.


ai_chat_completion()

Executes a chat completion request with all messages and functions in the connection.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesThe AI connection object with messages
json_schemamapNoJSON Schema for structured output (when response_format is json_object)
response_formatstringNoResponse format (text or json_object)

Returns: A map with status, error, and response (containing sentences, functions, combined, and value).

Example:

card MyCard do
ai = ai_connect("openai", "gpt-4", @(secrets.openai_token))
ai = ai_add_message(ai, "system", "You are a helpful assistant.")
ai = ai_add_message(ai, "user", @(event.message.text))

result = ai_chat_completion(ai)

# result contains:
# %{
# "status" => 200,
# "error" => false,
# "response" => %{
# "__value__" => "Hello! How can I help you today?",
# "sentences" => ["Hello!", "How can I help you today?"],
# "functions" => [],
# "combined" => [...]
# }
# }

text(@(result.response))
end

card WithJsonResponse do
ai = ai_connect("openai", "gpt-4", @(secrets.openai_token))
ai = ai_add_message(ai, "user", "List 3 colors")

# Request JSON response format
result = ai_chat_completion(ai, response_format: "json_object")
end

Notes: The value field contains the full text response. Use response_format: "json_object" for structured JSON output.


ai_connect()

Creates an AI connection object for any supported vendor (OpenAI, Anthropic, Google, etc.).

Configuration:

FieldTypeRequiredDescription
modelexpressionYesThe AI model to use (e.g., gpt-4, claude-3-opus)
tokenexpressionYesAPI token for authentication
vendorexpressionYesAI vendor identifier (openai, anthropic, google, etc.)

Returns: A connection object with type, token, model, vendor, messages, functions, and max_tokens fields.

Example:

card MyCard do
# Connect to OpenAI
ai = ai_connect("openai", "gpt-4", @(secrets.openai_token))
end

card AnthropicExample do
# Connect to Anthropic Claude
ai = ai_connect("anthropic", "claude-3-opus-20240229", @(secrets.anthropic_token))
end

card MetaExample do
# Connect to Meta Llama
ai = ai_connect("meta_ai", "llama-3", @(secrets.meta_ai_token))
end

Notes: Supported vendors: openai, anthropic, google, meta_ai. Use the appropriate model name for each vendor.


ai_assistant()

Creates a connection to a pre-configured AI Assistant.

Configuration:

FieldTypeRequiredDescription
uuidexpressionYesUUID of the assistant to connect to

Returns: A connection object with assistant details, vendor, messages, functions, and max_tokens fields.

Example:

card MyCard do
ai = ai_assistant("assistant-uuid")
end

ai_conversation_memory()

Configures conversation memory settings for the AI connection.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesThe AI connection object
memory_settingexpressionYesMemory mode: journey (session-scoped), longterm, or none

Returns: Updated connection object with memory settings configured.

Example:

card MyCard do
ai = ai_connect("openai", "gpt-4", @(secrets.openai_token))

# Use long-term memory (persists across sessions)
ai = ai_conversation_memory(ai, "longterm")

ai = ai_add_message(ai, "user", @(event.message.text))
result = ai_chat_completion(ai)
end

card SessionMemory do
ai = ai_connect("openai", "gpt-4", @(secrets.openai_token))

# Use journey-scoped memory (clears when journey ends)
ai = ai_conversation_memory(ai, "journey")
end

card NoMemory do
ai = ai_connect("openai", "gpt-4", @(secrets.openai_token))

# Disable memory (each interaction is independent)
ai = ai_conversation_memory(ai, "none")
end

Notes: Memory modes: journey (default, session-scoped), longterm (persists across sessions for the contact), none (stateless).


ai_text_classification()

Classifies user input into predefined categories using AI.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesThe AI connection object
optionsexpressionYesList of classification options
system_promptexpressionYesInstructions for classification
user_inputexpressionYesThe text to classify

Returns: Classification result with the selected option.

Example:

card MyCard do
ai = ai_connect("openai", "gpt-4", @(secrets.openai_token))

# Classify user sentiment
result = ai_text_classification(
ai,
@(event.message.text),
"Classify the sentiment of this customer message",
["positive", "negative", "neutral"]
)

result when result == "negative" do
text("I'm sorry you're having trouble. Let me connect you with support.")
end

result when result == "positive" do
text("Great to hear! How else can I help?")
end
end

card LanguageDetection do
ai = ai_connect("openai", "gpt-4", @(secrets.openai_token))

# Detect the language of the message
language = ai_text_classification(
ai,
@(event.message.text),
"Detect the language of this text",
["english", "spanish", "french", "portuguese", "other"]
)
end

Notes: Returns one of the provided options. Useful for routing, sentiment analysis, language detection, and intent classification.


OpenAI (Legacy)

openai_add_image()

Deprecated

Adds an image to the OpenAI context for use with the Vision API.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesOpenAI connection object
max_tokensexpressionYesMaximum tokens for the response
messageexpressionYesText prompt for the image
roleexpressionYesMessage role (typically user)
urlexpressionYesURL of the image

Returns: Updated connection object with the image message added.

Example:

card MyCard do
openai = openai_add_image(openai, "user", "What's in this image?", @(image_url), 300)
end

openai_connect()

Deprecated: Use ai_connect() instead.

Creates an OpenAI connection object for use with other OpenAI blocks.

Configuration:

FieldTypeRequiredDescription
modelexpressionYesOpenAI model name (e.g., gpt-4, gpt-3.5-turbo)
tokenexpressionYesOpenAI API token

Returns: A connection object with type, token, model, messages, functions, max_tokens, and vendor fields.

Example:

card MyCard do
openai = openai_connect(@(secrets.openai_token), "gpt-4")
end

openai_connect_assistant()

Deprecated: Use ai_assistant() instead.

Creates a connection to an OpenAI Assistant using the session UUID as thread ID.

Returns: A connection object with assistant thread details.

Example:

card MyCard do
openai = openai_connect_assistant()
end

openai_create_speech()

Generates speech audio from text using OpenAI's text-to-speech API.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesOpenAI connection object
modelexpressionYesTTS model (tts-1 or tts-1-hd)
textexpressionYesText to convert to speech
voiceexpressionYesVoice to use (alloy, echo, fable, onyx, nova, shimmer)

Returns: An attachment object with external_id for use in audio messages.

Example:

card MyCard do
openai = openai_connect(@(secrets.openai_token), "gpt-4")

# Generate speech from text
speech = openai_create_speech(openai, "Hello! How can I help you today?", "nova", "tts-1")

# Send the audio to the user
audio(@(speech.external_id))
end

card DynamicVoiceResponse do
openai = openai_connect(@(secrets.openai_token), "gpt-4")

# Use a variable for the text
speech = openai_create_speech(openai, @(ai_response), "alloy", "tts-1-hd")
audio(@(speech.external_id))
end

Notes: Available voices: alloy, echo, fable, onyx, nova, shimmer. Models: tts-1 (faster) or tts-1-hd (higher quality).


openai_transcribe()

Transcribes audio to text using OpenAI's Whisper API.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesOpenAI connection object
languageexpressionYesLanguage code (e.g., en, es, fr)
promptexpressionYesPrompt to guide transcription (can be empty string)
urlexpressionYesURL of the audio file to transcribe

Returns: Transcribed text from the audio file.

Example:

card MyCard do
openai = openai_connect(@(secrets.openai_token), "gpt-4")

# Transcribe audio from a voice message
transcription = openai_transcribe(openai, @(event.message.audio.url), "", "en")
text("You said: @(transcription)")
end

card WithPromptHint do
openai = openai_connect(@(secrets.openai_token), "gpt-4")

# Use a prompt to guide transcription (useful for domain-specific terms)
transcription = openai_transcribe(
openai,
@(event.message.audio.url),
"Medical terminology including diagnoses and prescriptions",
"en"
)
end

card SpanishTranscription do
openai = openai_connect(@(secrets.openai_token), "gpt-4")

# Transcribe Spanish audio
transcription = openai_transcribe(openai, @(event.message.audio.url), "", "es")
end

Notes: Uses OpenAI's Whisper model. The prompt can contain domain-specific terms to improve accuracy. Language codes follow ISO 639-1 (en, es, fr, etc.).


Lelapa AI

lelapa_connect()

Creates a connection to Lelapa's VulaVula AI services.

Configuration:

FieldTypeRequiredDescription
tokenexpressionYesLelapa API token

Returns: A connection object with type and token fields.

Example:

card MyCard do
# Create a Lelapa connection using your API token from secrets
lelapa = lelapa_connect(@(secrets.lelapa_token))

# Now use the connection with other Lelapa blocks
sentiment = lelapa_sentiment_analysis(lelapa, @(event.message.text))
end

lelapa_entity_recognition()

Identifies named entities (persons, locations, etc.) in text using Lelapa NER.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesLelapa connection object
textexpressionYesText to analyze (max 180 tokens)

Returns: List of entities with entity type, word, start, and end positions.

Example:

card MyCard do
lelapa = lelapa_connect(@(secrets.lelapa_token))
entities = lelapa_entity_recognition(lelapa, @(event.message.text))

# entities is a list like:
# [
# %{"entity" => "person", "word" => "Ramaphosa", "start" => 10, "end" => 19},
# %{"entity" => "location", "word" => "Emfuleni Municipality", "start" => 33, "end" => 54}
# ]
end

Notes: Supports multiple South African languages. Limited to 180 tokens per request. Entity types include: person, location, organization.


lelapa_intent_classification()

Classifies user input into specified intents with minimal training examples.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesLelapa connection object
examplesexpressionYesList of [intent, example] pairs for training
inputexpressionYesText to classify

Returns: Map with value (intent), intent, and score fields.

Example:

card MyCard do
lelapa = lelapa_connect(@(secrets.lelapa_token))

# Provide examples for each intent (supports multiple languages)
result = lelapa_intent_classification(lelapa, @(event.message.text), [
["greeting", "Hello!"],
["greeting", "Hi there!"],
["greeting", "Habari yako?"],
["goodbye", "Goodbye!"],
["goodbye", "See you later!"],
["goodbye", "Kwaheri"]
])

# result contains:
# %{"__value__" => "greeting", "intent" => "greeting", "score" => 0.74}
text("Detected intent: @(result.intent) with confidence @(result.score)")
end

Notes: Supports multiple languages with few-shot learning. Provide at least 2-3 examples per intent for best results.


lelapa_sentiment_analysis()

Analyzes sentiment (positive, negative, neutral) in text.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesLelapa connection object
textexpressionYesText to analyze

Returns: Map with value (label), label, score, text, and sentiments (for multi-sentence analysis).

Example:

card MyCard do
lelapa = lelapa_connect(@(secrets.lelapa_token))
sentiment = lelapa_sentiment_analysis(lelapa, @(event.message.text))

# sentiment contains:
# %{
# "__value__" => "positive",
# "label" => "positive",
# "score" => 0.99,
# "text" => "am happy",
# "sentiments" => [...] # detailed breakdown for multi-sentence text
# }

sentiment when sentiment.label == "negative" do
text("I'm sorry to hear that. How can I help?")
end
end

Notes: Labels are: positive, negative, neutral. For multi-sentence text, sentiments array contains per-sentence analysis.


lelapa_translate()

Translates text between South African languages using Lelapa's translation API.

Configuration:

FieldTypeRequiredDescription
connectionexpressionYesLelapa connection object
source_langexpressionYesSource language code (e.g., zul_Latn, eng_Latn)
target_langexpressionYesTarget language code
textexpressionYesText to translate

Returns: Map with value (translated text) and translation array.

Example:

card MyCard do
lelapa = lelapa_connect(@(secrets.lelapa_token))

# Translate from Zulu to English
translated = lelapa_translate(lelapa, @(event.message.text), "zul_Latn", "eng_Latn")
# translated.__value__ = "This sentence is written in Zulu."

text("Translation: @(translated)")
end

card TranslateToZulu do
lelapa = lelapa_connect(@(secrets.lelapa_token))

# Translate from English to Zulu
translated = lelapa_translate(lelapa, "Hello, how are you?", "eng_Latn", "zul_Latn")
text(@(translated))
end

Notes: Supported language codes: eng_Latn (English), zul_Latn (Zulu), xho_Latn (Xhosa), afr_Latn (Afrikaans), nso_Latn (Northern Sotho), sot_Latn (Southern Sotho), tsn_Latn (Tswana).