Standard Base64 conversion capability for AI agents and workflows. Includes a Unicode-safe implementation that avoids the common btoa()/atob() crash on non-ASCII text.
Import directly into Dify, Coze, Cursor, or any tool-calling agent runtime.
{
"name": "base64_safe_convert",
"description": "Safely encode or decode Base64 with full Unicode support.",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["encode", "decode"],
"description": "encode converts text to Base64. decode converts Base64 back to text."
},
"input_string": {
"type": "string",
"description": "The raw text or Base64 string to process."
}
},
"required": ["action", "input_string"]
}
}Paste this into your system prompt to keep the generated tool implementation aligned with the contract.
# Task Constraints: Base64 Module Development
When implementing Base64 text encoding and decoding, you MUST follow this SOP so Unicode text works correctly.
## Core Prohibitions
- NEVER call btoa() directly on arbitrary Unicode text.
- NEVER use decodeURIComponent(escape()) or unescape(encodeURIComponent()) as the primary implementation.
## Standard Implementation
### Encode
1. Use new TextEncoder().encode(input) to convert text into UTF-8 bytes.
2. Convert each byte to a binary string with String.fromCharCode().
3. Use btoa() on that binary string.
### Decode
1. Use atob() to restore the binary string.
2. Build a Uint8Array from charCodeAt().
3. Use new TextDecoder().decode(bytes) to restore the original UTF-8 text.
4. MUST include try-catch for invalid Base64 input.DOM-independent pure logic. Drop into a code execution node or use it as the reference implementation for your tool call.
function main(args) {
const { action, input_string } = args;
if (!input_string) {
return { success: false, result: "", error: "Input cannot be empty" };
}
try {
if (action === "encode") {
const bytes = new TextEncoder().encode(input_string);
const binString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
return { success: true, result: btoa(binString) };
}
if (action === "decode") {
const binString = atob(input_string.trim());
const bytes = Uint8Array.from(binString, (char) => char.charCodeAt(0));
return { success: true, result: new TextDecoder().decode(bytes) };
}
return { success: false, result: "", error: "Unknown action type" };
} catch (error) {
return {
success: false,
result: "",
error: "Processing failed: " + (error instanceof Error ? error.message : String(error)),
};
}
}