The rule editor is where you create and refine the smart function for a Data Preparation rule. It provides an AI assistant for code generation, a Javascript code editor, and a test data panel for validating your transformation logic before deployment.
Explore the topics below to learn about each part of the rule editor.
AI assistant
The AI assistant is the primary interface for creating and refining smart functions in Data Preparation. Instead of writing code manually, you describe what your device data looks like and what you want to achieve, and the AI generates the Javascript transformation logic for you.
Important
AI-generated code is produced on a best-effort basis. Always review the generated smart function and test cases before deploying a rule to production. Verify that the code handles your data correctly by running the provided tests and inspecting the outputs.
The AI assistant is powered by the AI Agent Manager. To use the assistant, your tenant must have a global AI provider configured. If you need to use a specific AI model or provider for Data Preparation, you can configure a local provider for the Data Preparation agent.
Overview
The AI assistant panel is on the left side of the rule editor. You interact with it by typing messages in the text box or by selecting one of the suggested actions. The AI responds with explanations in the chat and updates the smart function code and test cases directly in their respective panels.
When you create/open a new rule, the AI greets you and offers several starting points:
Convert to a Cumulocity measurement — generate code to map device data to measurements.
Convert to a Cumulocity alarm — generate code to create alarms from device conditions.
Help me to generate input data to test with — produce sample payloads for your tests.
Create a rule based on information about the IoT device — describe your device and let the AI determine the correct data format.
Writing effective prompts
The quality of the generated code depends on the context you provide. The more specific and detailed your prompt, the better the result.
Provide sample data
The most effective approach is to add a representative payload to the Test data panel before prompting. When sample data is present, the AI analyzes its structure and generates code that matches your actual device output exactly.
For example, enter a JSON payload in the test data input:
The AI uses the field names, value types, and structure from your sample to produce precise transformation code.
Be specific about your requirements
Good prompts include:
The data format: JSON, CBOR, binary, Protobuf, OPC UA, or other protocols.
Which fields to extract: Name the sensor readings, statuses, or identifiers you need.
The desired output type: Measurements, events, alarms, or a combination.
Units and naming: Specify units (°C, %, hPa) and the Cumulocity fragment names you prefer.
Conditional logic: Describe thresholds or conditions (for example, “raise an alarm if temperature exceeds 80°C”).
Examples of effective prompts:
Prompt
Why it works
“My device sends JSON with fields temp and vibration. Convert into two measurements using the clientID as the externalId.”
Specifies format, fields, output type, and device identity.
“My HVAC device gives a temperature reading. Always send a measurement. If temperature is above 76°F, also raise an alarm.”
Describes conditional logic clearly.
“I have a Modbus device sending binary data. Here is the decode function…”
Provides the codec so the AI can integrate it directly.
“Convert this climate sensor JSON to a measurement. Filter out readings where temperature is below 15°C or above 35°C.”
Includes validation requirements.
Prompts to avoid
Vague requests without sample data or context (for example, “Write me some code”).
Prompts that assume the AI knows your specific device without providing its data format.
Requests to use features not supported by the smart function API — the AI informs you if something is not possible.
Using suggestions
After each response, the AI offers clickable suggested next requests that guide you toward common next steps. These suggestions are contextual — they change based on the current state of your code and conversation.
Click any suggestion to send it as your next message. You can also type your own request instead.
Tool call indicators
When the AI updates the smart function or test cases, you see confirmation indicators in the chat:
Updated smart function — the AI has modified the Javascript code in the code editor.
Updated tests — the AI has added or modified test cases in the test data panel.
These indicators confirm that the corresponding panel has been updated. Expand them to see a summary of what changed.
Explaining code
To understand what the current smart function does, click Explain code above the code editor. The AI responds in the chat with a plain-language description of the transformation logic — explaining what data is extracted, how it is processed, and what outputs are produced.
This is useful when you inherit a rule from another user or want to verify the behavior of AI-generated code before deploying.
Iterative refinement
You do not need to get everything right in a single prompt. The AI maintains context across the conversation, so you can build up your smart function step by step:
Start with a simple conversion (for example, “Convert to a Cumulocity measurement”).
Add complexity (for example, “Also group humidity and pressure into a separate fragment called c8y_Environment”).
Handle edge cases (for example, “Raise an exception if fields are missing or any value is greater than 100.0”).
Generate tests (for example, “Generate test cases for edge cases such as missing values to validate this code”).
Each iteration builds on the previous code. The AI does not start from scratch unless you explicitly ask it to.
Fixing failing tests
If tests fail after a code change, click Fix smart function. The AI analyzes the failing tests, identifies what went wrong, and updates the code so that all tests pass. Review the changes before deploying — the AI adjusts code to match your expected outputs, so confirm the changes are correct across all scenarios.
Working with binary and IoT-specific data
The AI supports a range of IoT data formats beyond JSON:
CBOR — Concise Binary Object Representation, common in constrained IoT devices.
Protobuf — Protocol Buffers, used by gRPC and Sparkplug B.
OPC UA — Binary DataValue and Variant encoding for industrial protocols.
Base64-encoded payloads — the AI can decode and process these.
When working with binary data, provide either:
A sample payload (the AI attempts to detect the format automatically), or
A description of the format or a decode function for the AI to integrate.
If the AI cannot determine the format, it asks for clarification rather than guessing.
Test generation
Ask the AI to generate test cases for your current code. The AI creates tests that cover:
Normal operation with typical values.
Edge cases such as zero values, boundary conditions, or extreme readings.
Error scenarios with missing fields or unexpected data types.
To protect your test suite, the AI only adds or modifies tests — it never deletes existing tests. If you ask the AI to remove a test, it explains this limitation and offers to create a new test with updated content instead.
When the number of tests grows large, the AI can offer to consolidate related tests by grouping similar scenarios into a single test with multiple inputs, while leaving the original tests untouched for you to clean up manually.
Limitations
The AI assistant is designed to help you work efficiently while protecting your data:
Tests are protected — the AI adds and updates tests but never deletes them. Your test suite only grows, ensuring previously validated scenarios remain covered.
Code stays within the smart function API — the AI only generates code that uses the supported smart function interfaces. If you request something outside the API capabilities, the AI informs you of the limitation.
Best-effort generation — while the AI produces high-quality code for most IoT scenarios, always run tests and review the output before deploying. Complex or unusual data formats may require additional prompts or manual adjustments.
Recommended AI model — the assistant uses the AI model configured in your tenant’s AI Agent Manager. The quality of responses depends on the configured provider. Anthropic’s claude-sonnet-4-6 is the recommended and tested model.
Smart function editor
The smart function editor allows you to view and edit the smart function for the current rule. For a full reference on writing smart functions, including the API and examples, see Smart functions.
Smart function editor visibility
The code editor is minimized by default when a rule is first created. It opens automatically when the AI assistant creates your smart function.
Alternatively, the layout of the editor can be manually adjusted to suit your workflow:
Click the maximize icon to expand the code editor to full height, covering the test data panel.
Click the restore icon to reveal the test data panel again.
Drag the resize handle at the top edge of the code editor to adjust its height.
Editing code
The AI assistant automatically updates the code in the editor each time it edits or refines the smart function. You can also edit the code directly in the editor at any time.
Use the Undo or Redo buttons above the code editor to step backward or forward through your recent edits.
Click the Save draft or Save and deploy button to save your code. See To save or deploy a rule for more information.
To get an explanation of the current code, click Explain code. The AI assistant responds in the chat with a description of what the smart function does.
Test data
Use the Test data panel in the rule editor to verify that your smart function produces the correct Cumulocity objects before you deploy a rule to live traffic. Every change to a smart function has the potential to introduce unexpected behavior. A comprehensive set of tests gives you confidence that:
The function handles all the message formats your devices send.
Edge cases such as missing fields, unexpected types, or empty payloads are handled gracefully.
Later code changes do not break previously working behavior (regression detection).
Build a thorough set of test cases to catch errors early, validate edge cases, and detect regressions when the smart function changes.
To configure your first test
In the rule editor, locate the Test data panel.
Add a typical device payload to the Input section.
The test is now associated with the current rule.
Each input message displays the following properties as chips below the payload editor:
Payload type — the format for displaying and editing the message payload (for example, JSON).
Time — the timestamp indicating when the transport received the message.
Client ID — the client (typically a device identifier or device gateway) that sent the message.
Topic — the MQTT topic the message was published to.
To edit these properties, click the edit icon next to the chips.
To create additional tests
We recommend creating additional tests to check for edge cases such as missing values, out of range values, and other inputs that might require special handling in your rule. To do this, open the tests drop-down, and duplicate the existing test to a new one that describes what it’s for. You can also generate tests using the AI assistant. For any edge cases where it’s not possible to generate a valid Cumulocity object, raise a Javascript exception so that an alarm will be created to notify you about the problem.
Click the test name dropdown at the top of the test data panel.
Select an existing test to use as a starting point and click Duplicate test.
Enter a short name describing what the new test covers, for example “Null values”, “Out-of-range values”, “Device protocol v2”.
Edit the Input payload for the case you wish to test, for example, missing values, different field types, or out-of-range values.
Each test is independent and runs separately against the smart function. Create a test for every distinct message format, edge case, or error scenario you want to validate.
To add multiple messages to a test
A single test can contain more than one message. This is useful when you want to simulate a batch of device messages.
You can also add multiple messages to group related test cases and avoid having a large number of separate tests. However, note that when you run the tests, the outputs panel will show a list of all outputs generated by all inputs of a given test. So we recommend using separate tests instead of multiple inputs per test if you need to distinguish which output came from each input.
To add additional messages to a single test:
Click the menu icon in the test data panel.
Select Add message to this test.
Enter the additional payload.
To manage tests
Click the test name dropdown. From within the dropdown, you can:
Duplicate the current test: Click Duplicate test. Enter a name for the new test.
Create a new test: Click Create new test to create a new empty test.
Rename a test: Click the rename icon next to the test. Enter a new name for the test and confirm.
Delete a test: Click the delete icon next to the test.
Generating tests with the AI assistant
The AI assistant helps you expand test coverage quickly, especially for edge cases you have not considered.
Ask the AI assistant to create test cases for you.
The AI assistant adds new tests with relevant sample payloads.
Review the payloads and save expected outputs so they serve as regression checks in future test runs.
To protect your test suite, the AI assistant cannot delete tests.
To run tests
Click Run tests.
The platform executes your smart function against every test input. The outputs from each invocation of the smart function are displayed for you to inspect, but are not sent to the platform itself.
To inspect outputs
The Outputs section displays the results for each test after a test run. Each test produces its own output, so you can review results individually. The output includes:
Function return values — the Cumulocity objects (measurements, events, alarms, and operations) that the smart function produces for each test message. Each one also identifies the Cumulocity external “source” device they would be created on.
Log messages — any log output from the smart function. Log messages appear below the function return values in the output section.
Errors and exceptions — if the smart function throws an error or encounters an exception during execution, the error message and stack trace (if available) appear in the output section for that test.
Review the output carefully to confirm that the smart function produces the correct Cumulocity objects and does not create any unexpected errors.
To detect failures
If one or more tests cannot be executed or raise a Javascript exception:
An error icon appears next to the test name dropdown.
Within the dropdown, an error icon appears next to the specific tests that are failing.
It is good practice to make your smart function throw an exception for any cases the smart function cannot correctly handle instead of just dropping the message. This creates an alarm notification including information about the message that caused the problem. This can be very helpful for debugging problems and you can use the information in the alarm to add a new test if you want to improve your smart function.
Expected output
Once you have verified that the smart function is producing the correct output, save the output of your test as the expected output to create a baseline. If a future code change causes the output to differ from the saved expectation, the test is marked as failing, and the differences are displayed. This provides automated regression checking and is much less effort than checking manually.
To ensure the expected output can be compared, avoid using the current time (new Date()) in your smart functions. Instead use the msg.time from the input message, which remains stable each time the test is executed.
To save or update the expected output
Run the tests to produce output.
Review the output and confirm it is correct.
Click the menu icon in the output section.
Under EXPECTED OUTPUT click Save.
The current output is now stored as the expected output for that test.
To detect regressions
After you save expected outputs, every subsequent test run compares the actual output against the saved expectation. If the output no longer matches:
An error icon appears next to the test name dropdown.
Within the dropdown, an error icon appears next to the specific tests that are failing.
A comparison between the Actual output and Expected output is displayed. This helps to identify which part of the output has changed.
Run the tests after each change to your smart function and check for regressions against your saved expected outputs.
To fix failing tests
If one or more tests are failing, an error icon appears next to the test name dropdown.
If you saved an expected output which no longer matches, check whether the new output is correct. If it is, save the new expected output. If the output is not correct, you can ask the AI to help fix the code automatically:
Click Fix smart function.
The AI assistant analyzes the failing tests and updates the smart function so that all tests pass.
Run the tests again to verify the fix.
Review the AI’s changes before deploying. The AI adjusts the code to match your expected outputs, so confirm that the changes are correct for all scenarios, not only the failing tests.