Custom function
Create and publish a function that validates the check digit of a Mexican RFC (tax id). The calculation needs no HTTP calls or secrets; run the test through the API.
Before you start
- A Platica API key in
PLATIC_API_KEY. - Each test and publication counts toward the workspace's limit of 50 daily deployments. Each run counts as a call.
- Node.js 20.3 or newer and
npm install platic-sdk.
Verify, test and publish
- Creates the function as a draft. Nothing is deployed and no agent sees it.
- Verifies the code: it is compiled and checked without running. Issues come with their stage and line.
- Tests the draft once in a deployment separate from the live version. If the code fails, the test result includes the failure; the SDK does not throw an error.
- Publishes a new version, live and enabled in the workspace's catalog.
- With
PLATIC_EXAMPLE_CONNECT_AGENT=1: creates an agent, connects the function, runs the published version by hand and lists the runs. - Removes what it created, even when a step fails.
The code
import { Platic } from "platic-sdk";
const apiKey = process.env.PLATIC_API_KEY;
if (!apiKey) {
console.error("Set PLATIC_API_KEY to a Platica API key (pl_key_…).");
process.exit(1);
}
const connectAgent = process.env.PLATIC_EXAMPLE_CONNECT_AGENT === "1";
// The RFC check digit is a fixed calculation: a good fit for a function, with no HTTP call and no secret.
const source = `import { z } from "zod";
import { defineFunction } from "@platica/functions";
const ALPHABET = "0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ";
export default defineFunction({
input: z.object({
rfc: z.string().describe("Company (12) or person (13) RFC, with its check digit"),
}),
async run(input, { log }) {
const rfc = input.rfc.trim().toUpperCase();
if (rfc.length !== 12 && rfc.length !== 13) return { valid: false, reason: "length" };
const padded = rfc.length === 12 ? " " + rfc : rfc;
let sum = 0;
for (let i = 0; i < 12; i += 1) sum += ALPHABET.indexOf(padded[i]) * (13 - i);
const rest = 11 - (sum % 11);
const digit = rest === 11 ? "0" : rest === 10 ? "A" : String(rest);
log.info("checked", { length: rfc.length });
return { valid: digit === padded[12], expected: digit };
},
});
`;
const platic = new Platic({ apiKey });
const cleanup: Array<[string, () => Promise<unknown>]> = [];
try {
// 1. A draft: nothing is deployed and no agent sees it yet.
const fn = await platic.tools.functions.create({
name: `rfc_check_${Date.now().toString(36)}`,
description: "Checks whether a Mexican RFC has a valid check digit. Use it before saving a customer's RFC.",
source,
});
cleanup.unshift([`function ${fn.id}`, () => platic.tools.functions.delete(fn.id)]);
console.log(`function ${fn.toolName}: ${fn.nextStep}`);
// 2. Verify: compile and check the code without running it. Issues come with their stage and line.
const check = await platic.tools.functions.verify(fn.id);
if (!check.ok) {
for (const issue of check.issues) console.error(`${issue.stage} line ${issue.line ?? "?"}: ${issue.message}`);
throw new Error("the code did not pass the verification");
}
// 3. Test the draft once, deployed apart from any live version. A failure inside the code is an answer, not an error.
const test = await platic.tools.functions.test(fn.id, { input: { rfc: "XAXX010101000" } });
console.log(`test: ${test.ok ? JSON.stringify(test.output) : `${test.error?.code}: ${test.error?.message}`} in ${test.durationMs} ms`);
if (!test.ok) throw new Error("the test did not pass");
// 4. Publish: a new version, live and enabled in the workspace's catalog.
const { version, toolId } = await platic.tools.functions.publish(fn.id, { notes: "First version" });
console.log(`version ${version} is live`);
if (connectAgent && toolId) {
// 5. Give it to an agent, and run the published version by hand as the agent would.
const agent = await platic.agents.create({ name: "RFC checker", instructions: "Check every RFC with your tool before saving it." });
cleanup.unshift([`agent ${agent.id}`, () => platic.agents.delete(agent.id)]);
await platic.agents.tools.connect(agent.id, toolId);
const run = await platic.tools.functions.run(fn.id, { input: { rfc: "XAXX010101000" } });
console.log(`agent ${agent.id} can call ${fn.toolName}; manual run: ${run.ok ? JSON.stringify(run.output) : run.error?.code}`);
const { data } = await platic.tools.functions.runs({ functionId: fn.id, limit: 5 });
console.log(`runs: ${data.map((entry) => `${entry.trigger}:${entry.ok ? "ok" : entry.errorCode}`).join(", ")}`);
}
} finally {
await cleanUp(cleanup);
}
// Runs every step, even when one fails, and says what could not be removed.
async function cleanUp(steps: Array<[string, () => Promise<unknown>]>): Promise<void> {
for (const [label, step] of steps) {
try {
await step();
console.log(`removed ${label}`);
} catch (error) {
console.error(`could not remove ${label}: ${error instanceof Error ? error.message : String(error)}`);
process.exitCode = 1;
}
}
} Run it
Save the code in custom-function.ts and run it with tsx.
Set your API key and run the script:
export PLATIC_API_KEY=pl_key_...
npx tsx custom-function.ts To also connect it to a new agent and run the published version by hand:
PLATIC_EXAMPLE_CONNECT_AGENT=1 npx tsx custom-function.ts What to expect
function rfc_check_…: <next step from the API>
test: {"valid":true,"expected":"0"} in … ms
version 1 is live
removed function … The exact output of the test depends on the check digit. With PLATIC_EXAMPLE_CONNECT_AGENT=1 you also see the manual run and the list of runs. The function and the agent are removed at the end.
API reference used
- Create a custom function
- Verify a custom function
- Test a custom function
- Publish a custom function
- Run a custom function
- List executions
- Connect a tool to an agent
Query a service with authentication
Use this flow for HTTP calls, SOAP or XML, chained calls, custom signatures or authentication, calculations or response processing. The example looks up a company by its tax ID in a service that requires a credential.
Before you start
You need an agent with its id in AGENT_ID, and your Platica API key in PLATIC_API_KEY.
To use the platform, see Custom functions and Secrets.
Save this code as company_lookup.ts:
import { z } from "zod";
import { defineFunction } from "@platica/functions";
export default defineFunction({
input: z.object({
taxId: z.string().describe("The customer's tax ID, 12 or 13 characters"),
}),
async run(input, { http, secrets, log }) {
const res = await http.fetch("https://api.acme.com/v1/companies/lookup", {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${secrets.API_KEY}` },
body: JSON.stringify({ taxId: input.taxId }),
});
if (res.status !== 200) return { found: false };
log.info("answered", { status: res.status });
return { found: true, name: res.json().legalName };
},
}); inputis azodschema. Platica turns it into the schema the agent sees, and the.describe(...)texts tell it what to send.run(input, { http, secrets, log })returns a JSON object. That is what the agent receives.http.fetch(url, { method, headers, body })is the only way out to the internet. It answers{ status, headers, text, json() }.secrets.API_KEYis not the key: it is a placeholder. Platica swaps it for the value only when the call goes to the origin declared for that slot.log.info,log.warnandlog.errorend up in the executions.
Allowed packages: zod, @platica/functions, date-fns, decimal.js, papaparse, lodash-es and fast-xml-parser. Get the environment gives their versions, the template and the exact types. Not allowed: fs, net, http, https, child_process, process, require, import(), eval, Function, the global fetch, WebAssembly, globalThis, XMLHttpRequest and WebSocket. Verify rejects code that uses them.
Create the function as a draft
The function is created in
draft. It is not deployed or available to agents until you publish it.Define
allowedDomains: up to 10 exact hosts, HTTPS only. Declare each credential insecretSlotswith the only origin it may be sent to. That host must be inallowedDomains. (Create a function)curl https://api.platic.ai/v1/tools/functions \ -H "Authorization: Bearer $PLATIC_API_KEY" \ -H "Content-Type: application/json" \ -d "$(jq -n --rawfile source company_lookup.ts '{ name: "company_lookup", description: "Looks up a company by its tax ID. Use it when the customer gives their tax ID.", source: $source, allowedDomains: ["api.acme.com"], secretSlots: [{ slot: "API_KEY", origin: "https://api.acme.com" }] }')"import { readFile } from "node:fs/promises"; import { Platic } from "platic-sdk"; const platic = new Platic({ apiKey: process.env.PLATIC_API_KEY! }); const agentId = process.env.AGENT_ID!; const fn = await platic.tools.functions.create({ name: "company_lookup", description: "Looks up a company by its tax ID. Use it when the customer gives their tax ID.", source: await readFile("company_lookup.ts", "utf8"), allowedDomains: ["api.acme.com"], secretSlots: [{ slot: "API_KEY", origin: "https://api.acme.com" }], }); console.log(fn.toolName, fn.nextStep);Create a custom function called company_lookup with the code in company_lookup.ts. It may only call api.acme.com and needs a secret called API_KEY for that origin. Use it when the customer gives their tax ID.
Tool:
create_function. Paste the code into the chat or point it to the file.Save the response's
idinFUNCTION_ID. The agent will see the tool asfn_company_lookup.Choose
namewhen creating it: you can't change it later. It must start with a lowercase letter, contain lowercase letters, digits or_, and have 3 to 41 characters. Indescription(10 to 1,000 characters), explain what it does and when the agent should use it.If you omit
source, you receive the starter template. You can also keep the code in your repository and create or update the function from your CI.Verify the code
It compiles and checks the code without running it: size, syntax, types, allowed packages, forbidden APIs, bundling, the input schema and the declared domains. A check that fails is still a
200, withok: false. (Verify a function)curl -X POST https://api.platic.ai/v1/tools/functions/$FUNCTION_ID/verify \ -H "Authorization: Bearer $PLATIC_API_KEY"const check = await platic.tools.functions.verify(fn.id); if (!check.ok) { for (const issue of check.issues) console.error(`${issue.stage} line ${issue.line ?? "?"}: ${issue.message}`); throw new Error("the code did not pass the verification"); }Verify the company_lookup function and tell me what is wrong with it, line by line.
Tool:
verify_function.Check
issues: each problem includes its stage (stage), line and reason. Fix the code and verify again. Testing and publishing also verify the code; this call lets you fix it before using a deploy.Bind its secret
The values of secrets never go through the functions API. Store the value as a workspace secret and bind it to the slot: it stays authorized only for that slot's origin. (Bind a secret to a function)
curl https://api.platic.ai/v1/secrets \ -H "Authorization: Bearer $PLATIC_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Acme · companies API", "kind": "bearer", "value": "<your API key>" }' curl https://api.platic.ai/v1/tools/functions/$FUNCTION_ID/secrets \ -H "Authorization: Bearer $PLATIC_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "slot": "API_KEY", "secretId": "'$SECRET_ID'" }'const secret = await platic.secrets.create({ name: "Acme · companies API", kind: "bearer", value: process.env.ACME_API_KEY!, }); await platic.tools.functions.bindSecret(fn.id, { slot: "API_KEY", secretId: secret.id });Bind the secret Acme · companies API to the API_KEY slot of company_lookup.
Tool:
bind_function_secret. To keep the key out of the chat, store it yourself in Integrations → Functions → Secrets first.The code receives a placeholder instead of the secret. Platica replaces it with the real value only when calling the authorized origin. Sending it elsewhere sends the placeholder. The value does not appear in logs or executions.
If the binding is missing, the execution returns
SECRET_MISSING. To remove it, useunbind_function_secret.Test the draft
The test verifies the draft, deploys it separately and runs it once with your input. Agents keep using the published version. If the code fails, the test returns
200withok: falseand anerror.code. (Test a function)curl -X POST https://api.platic.ai/v1/tools/functions/$FUNCTION_ID/test \ -H "Authorization: Bearer $PLATIC_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "input": { "taxId": "XAXX010101000" } }'const test = await platic.tools.functions.test(fn.id, { input: { taxId: "XAXX010101000" } }); console.log(test.ok ? JSON.stringify(test.output) : `${test.error?.code}: ${test.error?.message}`, `${test.durationMs} ms`); if (!test.ok) throw new Error("the test did not pass");Test company_lookup with the tax ID XAXX010101000.
Tool:
test_function.The response has
output(what the agent would receive),logs,httpCalls(method, host, status and duration of each call) and arunIdthat stays in the executions withtrigger: "test".ImportantHTTP calls really go out to the allowed domains. If your code creates or changes something in another system, the test does it too.
EGRESS_DENIEDmeans the code called a domain that isn't inallowedDomains: add it with Update a function.TIMEOUT,INPUT_INVALIDandOUTPUT_TOO_LARGEare the other ways an execution can fail, along withFUNCTION_ERROR(the code threw: readlogs).Publish it and connect it to the agent
Publish the draft to deploy a fixed version and set the function to
enabledin the workspace catalog. Then connect the tool to the agent. The connection applies immediately and doesn't require publishing the agent. (Publish a function, Connect a tool)curl -X POST https://api.platic.ai/v1/tools/functions/$FUNCTION_ID/publish \ -H "Authorization: Bearer $PLATIC_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "notes": "First version" }' curl -X PUT https://api.platic.ai/v1/agents/$AGENT_ID/tools/$TOOL_ID \ -H "Authorization: Bearer $PLATIC_API_KEY"const { version, toolId } = await platic.tools.functions.publish(fn.id, { notes: "First version" }); console.log(`version ${version} is live`); if (toolId) await platic.agents.tools.connect(agentId, toolId);Publish company_lookup with the note "First version" and give it to the Sales agent.
Tool:
publish_functionandconnect_agent_tool.Keep the
toolIdfrom the response inTOOL_ID. Every publication is a fixed version. Editing changes the draft; agents keep using the published version until you publish again.
Check it worked
Run the published version with Run a function and check its output. Use Get executions to review the test and agent calls; trigger identifies the source of each execution.
const run = await platic.tools.functions.run(fn.id, { input: { taxId: "XAXX010101000" } });
const { data } = await platic.tools.functions.runs({ functionId: fn.id, limit: 5 }); Check that the function has status: "enabled", liveVersion and an entry with kind: "function" in the workspace catalog.
To recover a previous version, restore it (rollback_function). To stop its use, pause the function: it becomes unavailable to agents and keeps its code, versions and connections. You can activate it later.
Limits
| What | Limit |
|---|---|
| Functions per workspace | 20 |
| Time per execution | 1 to 60 s; 20 s by default |
| Memory | 256 MB |
| HTTP calls per execution | 20, up to 15 s and 2 MB each |
| Input and output | 256 KB each. The agent reads up to 16,000 characters of the output |
| Code | 100 KB (1 MB bundled) |
| Allowed domains | 10 per function |
| Secret slots | 10 per function |
| Calls | 60 per minute per function; 5,000 per day and 50,000 per month per workspace |
| Deploys (publish and test) | 50 per day per workspace |
Get usage says how much you have used. Past a limit, the response is LIMIT_REACHED with details.limit and, for calls, details.resetAt. Each function runs alone, in its own environment, with no access to other functions, other workspaces or Platica's data.
Next steps
All SDK examples: the next one is Upload a file.