Robofy API
HomeChangelog
HomeChangelog
Visit Website
Sign In
Create an account
  1. Start Guide
  • Start Guide
    • Overview
    • Architecture
    • Authentication
    • Changelog
    • Function Tool Call
    • Chat Widget Custom CSS Classes
    • Agent Widget JavaScript SDK
  • Robofy API
    • Chat
      • Generate Client Token (Handshake)
      • Send Message (Streaming)
      • Send Message (Non Streaming)
      • Send WhatsApp Message
    • Chatbot / Agent
      • List Agents
      • Create Agent
      • Retrieve Agent
      • Update Agent
      • Delete Agent
      • Delink Asset
      • List Linked Assets
      • Delete Widget Tab
    • Account
      • Retrieve Account Details
      • Update Account Details
      • Retrieve Account Limit
    • Prompt & Persona
      • Update System Prompt
      • Retrieve Agent Settings
      • Update Persona
      • Retrieve Persona
    • Inbox
      • List Sessions
      • List Session Messages
    • Project
      • Create Project
      • List Projects
      • Update Project
      • Retrieve Project
    • Leads
      • List Leads
    • Content
      • Add Website
      • Get Crawl Status
      • Add Text Content
      • Add File
    • Stats
      • Stats
    • License
      • Create License
      • List License
      • Update License
      • Retrieve License
      • Delete License
      • Update License Limit
    • Partner
      • Onboard
    • Schemas
      • Account
      • AccountDetailDto
      • Address
      • AgentCredentialInsertResponseDto
      • AgentCredentialRequestDto
      • AgentCredentialResponseDto
      • AgentDataPoint
      • AgentLeadCapture
      • AgentLeadReportDto
      • AgentLinkageDto
      • AgentMcpServerDto
      • AgentMcpServerInsertResponseDto
      • AgentMcpServerRequestDto
      • AgentMcpServerUpdateRequestDto
      • AgentPromptVersionDto
      • AgentSessionListDto
      • AgentSessionListItemDto
      • AgentStatsDto
      • AgentThemeDto
      • AgentThemeListDto
      • AgentToolLinkageInsertResponseDto
      • AgentToolLinkageRequestDto
      • AgentWhatappIntrgrationResponse
      • AgentWhatsAppLinkageDto
      • Button
      • CarouselCard
      • CategoryStats
      • ChatBotDetailsDto
      • ChatBotDetailsRequest
      • ChatBotDetailsUpdateRequest
      • ChatbotAISettingsDto
      • ChatbotAISettingsRequest
      • ChatbotAdvanceSettingsDto
      • ChatbotAdvanceSettingsRequest
      • ChatbotAppearanceSettingsDto
      • ChatbotAppearanceSettingsRequest
      • ChatbotAssetDelinkDto
      • ChatbotAssetLinkageDataDto
      • ChatbotAssetLinkageDelinkRequest
      • ChatbotAssetLinkageDetailsDto
      • ChatbotAssetLinkageDto
      • ChatbotAssetLinkageRequest
      • ChatbotTextLinkageRequest
      • ClientData
      • CommonResponse
      • Component
      • Contact
      • ContactName
      • CrawlStatusDto
      • CrawlWebsiteRequest
      • CreateOrUpdateProjectRequest
      • CreatePhoneNumberRequest
      • CreateTemplateRequest
      • CreateWebhookConfigRequest
      • DeLinkWhatsAppRequest
      • Email
      • Error
      • ErrorResponse
      • Example
      • FailureStats
      • FailureStatsDataPoint
      • FormField
      • GoogleSheetDto
      • GoogleSheetIntegrationRequest
      • InboxChatDto
      • InboxDto
      • InboxMessage
      • InboxSession
      • IntelligentMetricsDto
      • Interactive
      • InteractiveAction
      • InteractiveBody
      • InteractiveButton
      • InteractiveFooter
      • InteractiveHeader
      • InteractiveMedia
      • InteractiveProductItem
      • InteractiveProductSection
      • InteractiveReply
      • InteractiveRow
      • InteractiveSection
      • LeadCaptureForm
      • LeadData
      • LeadDataField
      • LeadFormData
      • LeadReport
      • LicenseCreateRequest
      • LicenseDto
      • LicenseLimitRequest
      • LicenseUpdateRequest
      • LimitedTimeOffer
      • LinkWhatsAppRequest
      • LinkedCredentialDto
      • LinkedMcpServerDto
      • Location
      • Media
      • MessageMetaData
      • MessageRequest
      • MessageResponse
      • MessageStats
      • MessageStatsDataPoint
      • MessageTemplate
      • NamedParameter
      • OrgLimitDto
      • Organization
      • PaginatedWebhookLogsResponse
      • Part
      • PartnerClientSession
      • PartnerClientSessionDto
      • Phone
      • PhoneNumberRequest
      • PhoneVerifyCodeRequest
      • PhoneVerifyRequest
      • PlatformStats
      • ProjectDetailDto
      • ProjectWABADetail
      • Reaction
      • ReadTypingIndicatorRequest
      • RecentInsightDto
      • Response
      • SessionInsightItemDto
      • SessionInsightsDto
      • SessionMetaDto
      • SessionMetricsDto
      • SessionSummaryDetailDto
      • StartUrl
      • SubcribedAppsRequest
      • SupportedApp
      • TemplateAction
      • TemplateButtons
      • TemplateCarousel
      • TemplateComponent
      • TemplateCurrency
      • TemplateDateTime
      • TemplateLimitedTimeOffer
      • TemplateMedia
      • TemplateParameter
      • TemplateProductItem
      • TemplateSection
      • TemplateTapTargetConfiguration
      • Text
      • ThemeMetaDto
      • TypingIndicator
      • UpdateOnboardStatusRequest
      • UpdateOnboardStatusResponseDto
      • UploadMedia
      • Url
      • WABADetail
      • WABADto
      • Webhook
      • WebhookConfigDto
      • WebhookConfiguration
      • WebhookLogDto
      • WebsiteDto
      • WhatsAppBusinessApiData
      • WhatsAppBusinessProfile
      • WidgetIntegration
  1. Start Guide

Function Tool Call

How to Build a Function Tool Call for Your Chatbot#

TIP
In this guide: Configure one Function Tool Call in four steps, test the request, save it, and verify the chatbot calls it correctly.
Related: Agent Widget JavaScript SDK for setAuth, setContext, and other host APIs.
AudienceDifficultyTime
Chatbot owners and API integratorsIntermediate15-25 minutes

What is Function Tool Call?#

Function Tool Call lets you teach the chatbot a named action it can call during a conversation. You define:
When the AI should use it
Which values the AI must collect
Which HTTPS endpoint to call
How inputs, website context, and credentials map into the request
Whether the visitor must approve the call (web chat)
The chatbot uses the tool description and input descriptions to decide when to call it. The platform builds and executes the HTTP request on the server, then gives the API response back to the model.

Before you start#

Make sure you have:
An HTTPS API endpoint reachable from the public internet
The request method and expected path, headers, query parameters, and body
A sample value for every required input
The authentication method: public, stored credential, or signed-in visitor
A concise API response that the chatbot can interpret
Permission to manage the selected chatbot
WARNING
Security requirements: Function Tool Calls cannot use HTTP URLs, private/internal network addresses, or redirecting URLs. Secrets can be placed only in request headers - never in the URL, query string, or body.

Open the Function Tool Call builder#

1
Open chatbot settings
Open your chatbot settings in the product dashboard.
2
Open Integrations
Go to Integrations (or Install & Integrations).
3
Select Function Tool Call
Select Function Tool Call.
4
Create a tool
Click New tool or Create your first tool.
NOTE
You can configure up to 15 Function Tool Calls per chatbot.

Step 1 - Basics#

Goal: Give the tool a stable machine name and clearly tell the AI when to use it.
custom-tool-step-1-basics.svg
custom-tool-step-1-basics.svg

Tool name#

Use a short machine-readable name such as lookup_order, create_support_ticket, or add_knowledge_content.
Use 3-64 characters.
Start with a letter.
Use letters, numbers, and underscores only.
Lowercase with underscores is recommended.
The name must be unique within the chatbot.
Do not use the reserved names file_search or Knowledge_search_tool.

When should the AI use this?#

Write a complete instruction that explains both what the tool does and when to call it. The description must be at least one sentence.
Good example:
Look up an order's current status and estimated delivery date. Use this whenever a customer asks where an order is, when it will arrive, or whether it has shipped.
Weak example:
Order tool.
The AI sees this description, so avoid internal implementation details and describe the user's intent in natural language.

Enabled for the agent#

Turn this on if the chatbot should be able to call the tool after it is saved. A new or edited configuration remains a draft until Test API succeeds and you save it. Imported tools always start Disabled until you test and enable them.

Step 2 - Inputs#

Goal: Define only the values the AI should obtain from the conversation.
custom-tool-step-2-inputs.svg
custom-tool-step-2-inputs.svg
Before adding an input, decide where the value should come from:
Value sourceUse it forConfigure it in
AI inputA value the user supplies or the AI derives from chat, such as an order number or messageStep 2 - Inputs
Fixed literalA constant the AI must not invent, such as an API versionStep 3 - Request body or query parameters
Website contextA value the embedding page already knows, such as project or organization IDStep 3 - From your website
SecretAn API key or access tokenStep 3 - Authentication and Headers
TIP
Do not ask visitors for internal IDs that your website already knows. Pass them with AgentWidget.setContext(...) and use a {host...} token instead. AgentWidget only exists on pages where the embed script is loaded (see When is AgentWidget available? below).

Add one card per AI input#

For each input, configure:
Name: A unique identifier such as order_id, content, or file_name. Start with a letter and use letters, numbers, and underscores.
Type: string, number, boolean, or array.
Description for the AI: Explain exactly what belongs in the field and include an example when useful.
Required: Turn on when the API cannot run without the value.
Default value: Used when the AI omits the input. If a default is set, the field behaves as optional even when Required is on.

Optional constraints#

Constraints reduce invalid tool calls:
Allowed values: Restrict strings or numbers to a fixed set. Add a note explaining when each value applies.
Number range: Set minimum and maximum values.
String pattern: Add a regular expression, either as a raw pattern or /pattern/flags.
String length: Set minimum and maximum length.
Do not combine Allowed values with a string pattern. For numbers, do not combine allowed values with minimum/maximum. Choose the rule that best represents the API.
A tool may have no AI inputs if every value comes from a fixed literal, stored credential, or website context.

Step 3 - API call#

Goal: Build the exact HTTP request the platform will issue.

A. Endpoint and visitor approval#

custom-tool-step-3-api-call-endpoint-auth.svg
custom-tool-step-3-api-call-endpoint-auth.svg
1.
Select GET, POST, PUT, or DELETE.
2.
Enter the complete HTTPS endpoint.
3.
Insert tokens into the path where needed, for example:
https://api.example.com/orders/{order_id}
4.
If the action is sensitive or changes data, enable Ask the visitor to confirm before running.
5.
Edit the Approval message: the full sentence shown on the confirm card (visitors never see the tool name).
Default message:
The assistant wants to take an action. Approve to continue.
Write a clear full sentence such as:
The assistant wants to create this support ticket with the details below. Approve to continue.
The approval card is available only in the web widget. WhatsApp calls run immediately. The approval message can be up to 200 characters and is shown exactly as you type it (no forced prefix).

Token reference#

TokenSourceAllowed locations
{order_id}AI input named order_idURL path, headers, body, query
{host.project_id}AgentWidget.setContext({ project_id: ... })URL path, headers, body, query
{credential.api_key}Encrypted stored credential fieldHeaders only
{visitor.token}Signed-in visitor token supplied by the host siteHeaders only
The endpoint hostname must always be fixed. For example, https://api.example.com/projects/{host.project_id} is valid, but https://{host.api_domain}/projects/123 is blocked.

B. Authentication#

Choose one mode:
ModeUse whenImportant behavior
NoneThe endpoint is publicNo authentication is added automatically
Stored secretEvery visitor uses the same API key or secretValues are encrypted, write-only, and resolved on the server
Signed-in visitorYour API must act as the current logged-in userWeb chat only; not available on WhatsApp; omitted until the site supplies the visitor token

Create and manage stored credentials#

1.
In Function Tool Call, open Credentials, then New credential. You can also create one inside the tool editor.
2.
Give it a recognizable name, such as Production API key.
3.
Add one or more fields, such as api_key or api_secret, and enter their secret values.
4.
Save the credential.
5.
Select it in the tool and insert its token in a header, for example:
Authorization: Bearer {credential.api_key}
Credential values are write-only: they are never shown again and are not included when tools are exported. You can list credential names, see which tools use them, and delete unused ones. Deleting a credential clears it from tools that referenced it.

When is AgentWidget available?#

AgentWidget is the global JavaScript API from the chat embed script (agent-widget.js). Use it only on the customer-facing site where the widget is installed.
SituationAvailable?
Page includes the embed script with valid project and chatbot idsYes - window.AgentWidget exists after the script runs
Embed script missing or failed to loadNo
Immediately after script load, before the widget iframe is readyObject exists; setAuth / setContext are queued until ready
After the widget ready event (AgentWidget.isReady())Fully ready for chat and host commands
After AgentWidget.destroy()No longer usable on that page
WhatsApp / admin builderNo - host SDK runs only on the embedded web page
Minimal install on your site:
Recommended before relying on auth or context inside the chat:
You can call setAuth / setContext before ready; the SDK queues them. Waiting for ready is the safest way to know the visitor chat session can use them. Full method list: see Agent Widget JavaScript SDK.

Supply signed-in visitor auth#

Use AgentWidget.setAuth(...) when the API must act as the currently logged-in user. Call it after login (or whenever you refresh the access token). Call AgentWidget.clearAuth() on logout. Requires the embed script on the page (when available).
// After the user signs in (or after you refresh their access token)
AgentWidget.setAuth({
  kind: "bearer",
  token: visitorAccessToken,
});

// On logout
AgentWidget.clearAuth();
Use Authorization: Bearer {visitor.token} when your API expects a bearer token. If you do not add an Authorization header yourself, the signed-in visitor mode supplies the bearer token automatically.
Until the embedding page sets auth, signed-in visitor tools are not offered in chat. They also do not run on WhatsApp.

Sample use cases for setAuth#

1. Customer portal: "show my orders"
The site already has a session. After login, pass the same access token the portal uses for its own API:
async function onUserLoggedIn(session) {
  AgentWidget.setAuth({
    kind: "bearer",
    token: session.accessToken,
  });
}

function onUserLoggedOut() {
  AgentWidget.clearAuth();
}
In the tool: auth mode Signed-in visitor, endpoint such as https://api.example.com/me/orders. The chatbot can call it without asking the user for a password.
2. Helpdesk: "create a ticket as me"
Support agents are signed into your dashboard. Set their JWT so the ticket API records the correct assignee:
AgentWidget.setAuth({
  kind: "bearer",
  token: agentJwt,
});
Enable visitor approval so the agent confirms before the ticket is created.
3. Token refresh
When your SPA refreshes the access token, call setAuth again with the new token. Do not leave an expired token in place - either update it or call clearAuth().
authClient.onTokenRefreshed((newToken) => {
  AgentWidget.setAuth({ kind: "bearer", token: newToken });
});

C. Headers, body, query, and website context#

custom-tool-step-3-api-call-mapping.svg
custom-tool-step-3-api-call-mapping.svg
Headers: Add authentication and any API-specific headers. Secret tokens are available only here.
Request body: For POST, PUT, and DELETE, map each JSON field to an input, website-context token, or fixed literal. A DELETE body is optional.
Query parameters: For GET, the main mapping becomes the query string. Write methods have a separate Extra query parameters section.
From your website: List context keys that the embedding page supplies. A key named project_id becomes {host.project_id}.

Supply website context with setContext#

Use AgentWidget.setContext(...) for values the page already knows (tenant, store, locale, selected record). Requires the embed script (when available). List the same keys under From your website in the tool, then reference them as {host.key_name}.
AgentWidget.setContext({
  project_id: currentProjectId,
  organization_id: currentOrganizationId,
});
Update context whenever the page selection changes (for example the user switches project or store). Keys you omit are not sent; pass the full object you want available to tools.
WARNING
Website context is browser-supplied convenience data, not proof of identity. Your API must determine tenant and data access from a verified visitor token or server-side credential - not from project_id alone.

Sample use cases for setContext#

1. Multi-tenant SaaS: scope every call to the open workspace
The user is viewing workspace ws_42. Pass that id so tools never ask the visitor to type it:
AgentWidget.setContext({
  workspace_id: "ws_42",
  organization_id: "org_9",
});
In the tool:
From your website: workspace_id, organization_id
Endpoint: https://api.example.com/v1/workspaces/{host.workspace_id}/orders/{order_id}
AI input: only order_id (what the customer says in chat)
2. Online store: current shop and currency
On a multi-store admin or storefront page:
AgentWidget.setContext({
  store_id: selectedStore.id,
  currency: selectedStore.currency, // e.g. "USD"
});
Map {host.store_id} into the path or body, and {host.currency} into a query field or JSON field. The AI still collects product name or SKU from the conversation.
3. CRM: selected account on the page
When an agent opens an account record, pass its id so "update this account" tools target the right row:
// When the account page loads or the selection changes
AgentWidget.setContext({
  account_id: openAccount.id,
  pipeline: openAccount.pipeline,
});
Tool body example:
{
  "account_id": "{host.account_id}",
  "note": "{note}"
}
Here note is an AI input; account_id comes from the page.
4. Combine with setAuth (common pattern)
Pass non-secret page context with setContext, and the user token with setAuth:
AgentWidget.setAuth({
  kind: "bearer",
  token: session.accessToken,
});

AgentWidget.setContext({
  project_id: session.projectId,
  locale: document.documentElement.lang || "en",
});
Then the tool can use signed-in visitor auth plus {host.project_id} in the URL, without putting secrets in context.

Complete example: add knowledge content#

Example configuration (adjust the hostname to your own API):
SettingValue
Tool nameadd_knowledge_content
Inputschatbot_id, content, file_name - all required strings
MethodPOST
Endpointhttps://api.example.com/v1/ai-agent/link_content/{host.project_id}
AuthenticationSigned-in visitor
HeaderAuthorization: Bearer {visitor.token}
Website contextproject_id
ApprovalEnabled, full message such as: The assistant wants to add this file to knowledge. Approve to continue.
Request body mapping:
{
  "chatbot_id": "{chatbot_id}",
  "content": "{content}",
  "file_name": "{file_name}"
}
At runtime, the brace tokens are replaced with the actual values; the API does not receive the brace syntax.

Step 4 - Preview and Test API#

Goal: Confirm both the outgoing request and what the AI sees before saving.
custom-tool-step-4-preview.svg
custom-tool-step-4-preview.svg
The Preview page shows:
Outgoing request: Method, resolved sample URL, headers, query, and body
How the AI sees this: Tool description, input types, required/optional status, and input descriptions
Blocking issues (if any), with a link to jump to the first problem tab
Check that:
The method and endpoint are correct
Every token resolves from an input, website-context key, or credential
Secrets are masked and appear only in headers
The request body keys match your API contract
The AI description clearly says when to use the tool
Required inputs are truly required
The approval message (if enabled) reads clearly as a full visitor-facing sentence

How Test API behaves#

MethodTest behavior
GETSends the real read request with your sample values and displays the response
POST, PUT, DELETEBuilds the exact request as a dry run and does not send the write; it also performs a safe GET reachability/auth check against the same URL
In the Test API dialog you may be asked for:
Sample values for each AI input
Host-context values for keys listed under From your website
A short-lived visitor token or credential field values for this probe only
Those samples are not stored on the tool.
1
Open Test API
Click Test API.
2
Enter sample values
Provide sample values for inputs, host context, and (if needed) auth for this probe only.
3
Run or validate
For a GET, click Run test. For a write method, click Validate request.
4
Review and fix
Review the result and fix any issues. Validation errors appear on the Basics / Inputs / API call tabs.
5
Save
When the test succeeds, click Create tool or Save changes.
NOTE
Any configuration change after a successful test invalidates the result. Run Test API again before saving.
INFO
A write endpoint may return an "inconclusive" auth check if it does not support GET. This does not send the write; use the redacted request preview to verify the final method, URL, headers, and body.

Verify the tool in your chatbot#

After saving:
1.
Confirm the tool is marked Enabled (imported tools start disabled).
2.
Open the web chatbot in a test environment.
3.
Ask a natural-language question that matches the tool description.
4.
Confirm the chatbot collects missing required inputs.
5.
If approval is enabled, verify the approval card shows your full message and the expected values.
6.
Approve the call and verify the result in both the conversation and your API logs.
7.
Test a missing or invalid value to confirm your API returns a clear, safe error.
8.
For signed-in visitor mode, test login, token expiration, refresh, and logout behavior.
9.
If you use WhatsApp, confirm visitor-auth and approval behave as described in the channel table below.

Troubleshooting#

Create tool or Save changes is not available
Fix all validation errors on each tab.
Run Test API successfully.
If you edited anything after testing, test again.
The AI does not call the tool
Make the tool description more specific about user intent.
Confirm the tool is enabled.
Make each input description unambiguous.
For signed-in visitor mode, make sure the embedding page calls AgentWidget.setAuth(...); otherwise the tool is omitted.
Remember that signed-in visitor tools are not available on WhatsApp.
A placeholder is undefined
Add it as an input, or
Add the key under From your website and use the {host.key} form, then
Make sure the host page sends the same key through AgentWidget.setContext(...).
The API returns 401 or 403
Check that the correct stored credential is selected.
Confirm the header uses the correct credential field.
For visitor auth, obtain a current token after login and refresh or replace it when it expires.
The URL is blocked or the test says Tool fails security checks
Use a complete https:// URL with a public hostname.
Use the final endpoint directly; redirects are not followed.
Keep the hostname fixed.
Move credential and visitor tokens into headers.
Remove private, localhost, or internal-network destinations.
Import skipped tools or unsafe
Invalid JSON is rejected entirely.
Rows missing name, description, or HTTPS URL are skipped; valid tools still import.
Entries that fail safety checks (bad name, secrets in the URL, reserved name, non-HTTPS, and similar) are skipped with a toast.
If the file has more tools than free slots (max 15), pick which ones to import.
The request times out
Function Tool Call requests have a 12-second timeout. Optimize the endpoint or redesign it as a fast request that starts an asynchronous job and returns a job ID.
The response is too large
Keep tool responses compact and task-focused. The model receives at most approximately 8,000 characters from a Function Tool Call response.

Channels and security#

CapabilityWeb chatWhatsApp
Function Tool Call (public or stored secret)YesYes
Signed-in visitor authYesNo (tool not offered)
Visitor approval before runningYesNo (call runs immediately)
Other limits:
Stored secrets are encrypted, write-only, resolved server-side, and allowed only in headers.
Browser-provided website context must never be the sole authorization signal.
Requests do not follow redirects.
Write methods are not automatically retried (avoids duplicate side effects).
Each chatbot can have up to 15 Function Tool Calls.

Import and export#

Use Export to download selected tools as JSON and Import to copy them to another chatbot.
Secret values are not exported; only credential references are included.
Imported tools always start disabled.
Name collisions get a suffix (for example lookup_order_2).
Distorted or incomplete rows are skipped when possible; the rest can still import.
When the file exceeds remaining slots under the 15-tool limit, choose which tools to import.
After import: open each tool, select or create the correct credential, run Test API, then enable it.

Final checklist#

Tool name is stable and machine-readable
Description states what the tool does and when to use it
Inputs contain only values the AI should collect
Website-known IDs use {host.key}
Secrets appear only in headers
Endpoint is public HTTPS with a fixed hostname
Approval uses a clear full sentence (max 200 characters) where appropriate
Preview matches the API contract
Test API succeeds
Tool is saved and enabled
Visitor auth verified on the embedding page if required
End-to-end chat behavior is verified on the channels you use
Modified at 2026-08-13 08:21:22
Previous
Changelog
Next
Chat Widget Custom CSS Classes
Built with