DEV Community

vishalmysore
vishalmysore

Posted on

Java Agentic Actions with Real time updates

This article explores how DatabaseExample and ActionLoopExample function within the Tools4AI framework. These examples share a similar structure but illustrate distinct use cases: single-action processing with status updates versus dynamic action loops or chains.
Code for this article is here

Common Setup in Both Examples

Both examples follow a standard initialization pattern to configure and run AI-driven actions.

Configuration

System.setProperty("tools4ai.properties.path", "path/to/tools4ai.properties");
Enter fullscreen mode Exit fullscreen mode

This sets the path to a properties file that configures the framework, including API keys, model settings, and action mappings.

AIProcessor Initialization

AIProcessor processor = PredictionLoader.getInstance().createOrGetAIProcessor();
log.info("AI Processor initialized: " + (processor != null));
Enter fullscreen mode Exit fullscreen mode

Creates or retrieves a singleton AIProcessor instance responsible for NLP-based action prediction and execution.

Callback Creation and Context Setup

LongRunningCallback callback = new LongRunningCallback(); // or MultiActionCallback
AtomicReference<Object> context = new AtomicReference<>("MCP");
callback.setContext(context);
Enter fullscreen mode Exit fullscreen mode
  • Initializes a callback for status updates.
  • Uses AtomicReference<Object> for thread-safe context sharing (e.g., user preferences or session data).

Action Processing

String result = processor.processSingleAction(query, callback);
log.info("Result: " + result);
Enter fullscreen mode Exit fullscreen mode

Processes the query via NLP to select and execute an action, with the callback receiving real-time updates.

Error Handling

try {
    // processing code
} catch (AIProcessingException e) {
    throw new RuntimeException(e);
}
Enter fullscreen mode Exit fullscreen mode

Handles exceptions during AI processing.

DatabaseExample: Single Action with Status Updates

Purpose

Demonstrates a long-running database query action with real-time progress feedback, simulating transparency in slow operations.

Code Snippet

package io.github.vishalmysore.simple;

import com.t4a.processor.AIProcessingException;
import com.t4a.processor.AIProcessor;
import com.t4a.processor.PredictionLoader;
import lombok.extern.java.Log;

import java.util.concurrent.atomic.AtomicReference;

@Log
public class DatabaseExample {
    public static void main(String[] args) {
        System.setProperty("tools4ai.properties.path", "src/main/resources/io/github/vishalmysore/simple/tools4ai.properties");
        AIProcessor processor = PredictionLoader.getInstance().createOrGetAIProcessor();
        log.info("AI Processor initialized: " + (processor != null));

        LongRunningCallback callback = new LongRunningCallback();
        AtomicReference<Object> context = new AtomicReference<>("MCP");
        callback.setContext(context);

        String query = "can you get me details of customer id 007, name is james bond he is a spy";
        try {
            String result = processor.processSingleAction(query, callback);
            log.info("Result: " + result);
        } catch (AIProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Execution Flow

  1. NLP predicts an action like DatabaseProcessingAction.getCustomerDetailsFromDatabase based on the query.
  2. The action runs (potentially in a background thread), calling sendtStatus periodically to log progress (e.g., "Processing customer ID: 007").
  3. The result (e.g., customer details in JSON) is returned and logged.

Thread-Safety

  • AtomicReference ensures safe concurrent access to context.
  • Callbacks are stateless, promoting thread-safety.

ActionLoopExample: Action Loops and Chains

Purpose

Illustrates dynamic action chaining, where one action can trigger others based on logic, mimicking workflows.

Code Snippet

package io.github.vishalmysore.multi;

import com.t4a.processor.AIProcessingException;
import com.t4a.processor.AIProcessor;
import com.t4a.processor.PredictionLoader;
import com.t4a.processor.loader.ActionList;
import lombok.extern.java.Log;

import java.util.concurrent.atomic.AtomicReference;

@Log
public class ActionLoopExample {
    public static void main(String[] args) {
        System.setProperty("tools4ai.properties.path", "src/main/resources/io/github/vishalmysore/multi/tools4ai.properties");
        AIProcessor processor = PredictionLoader.getInstance().createOrGetAIProcessor();
        log.info("AI Processor initialized: " + (processor != null));

        ActionList listOfActions = PredictionLoader.getInstance().getActionGroupList();
        log.info("Available action groups: " + listOfActions.getGroupActions());

        MultiActionCallback callback = new MultiActionCallback();
        AtomicReference<Object> context = new AtomicReference<>("MCP");
        callback.setContext(context);

        String query = "i need to eat fruit salad";
        try {
            String result = processor.processSingleAction(query, callback);
            log.info("Result: " + result);
        } catch (AIProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Execution Flow

  1. NLP predicts FoodPrepareAction for the query.
  2. During execution, the action may check conditions (e.g., ingredient availability) and trigger another action like OrderIngredientsAction.
  3. Creates a chain: Prepare → Check → Order → Complete, with each step sending status updates.
  4. Final result is logged.

Thread-Safety

  • AtomicReference protects shared context across actions.
  • Supports concurrent action execution with safe updates.

Key Differences

  • DatabaseExample: Focuses on one action with progress logging for transparency.
  • ActionLoopExample: Emphasizes chaining for dynamic, decision-based workflows.
  • Both use NLP for action selection and callbacks for feedback, ensuring thread-safety with AtomicReference.

Use Cases

1. Enterprise Data Retrieval

In a CRM system, use DatabaseExample-style actions for querying customer data with progress updates, allowing users to monitor long-running searches without blocking the UI.

2. Workflow Automation

ActionLoopExample can automate business processes, such as order fulfillment: Receive order → Check inventory → Place supply order → Ship, with real-time status to stakeholders.

3. IoT Device Management

For smart home systems, chain actions like "Turn on lights" → "Adjust thermostat" → "Send notification," using callbacks for status in multi-device scenarios.

4. E-commerce Recommendations

Single actions for product searches with updates, or chains for "Search product" → "Check reviews" → "Suggest alternatives" based on user preferences.

5. Healthcare Monitoring

In medical apps, long-running actions for patient data analysis with progress, or chains for "Monitor vitals" → "Alert doctor" → "Update records."

6. Financial Transactions

Secure, audited actions for transfers with status updates, or chains for "Validate account" → "Process payment" → "Send confirmation."

7. Content Generation

AI-driven content creation with progress (e.g., "Generating article outline"), or chains for "Research topic" → "Write draft" → "Edit and publish."

8. Logistics and Supply Chain

Track shipments with updates, or automate "Receive order" → "Route delivery" → "Update inventory" chains.

9. Educational Platforms

Personalized learning paths: Assess knowledge → Recommend modules → Track progress, with callbacks for user feedback.

10. Gaming and Interactive Experiences

Dynamic story generation or NPC behaviors, chaining actions based on player choices with real-time updates.

Conclusion

Tools4AI's callback mechanism and NLP-driven action selection enable flexible, thread-safe AI integrations. DatabaseExample suits straightforward tasks with feedback, while ActionLoopExample handles complex workflows. These patterns apply to various domains, enhancing user experience through transparency and automation. For deeper dives, explore the framework's documentation or experiment with custom actions!

Top comments (0)