Exploring Autonomous Agents: A Semi-Technical Dive

Mike's Notes

An article by Dan Chen was published on Sequoia.

Resources

References

  • Reference

Repository

  • Home > Ajabbi Research > Library >
  • Home > Handbook > 

Last Updated

18/05/2025

Exploring Autonomous Agents: A Semi-Technical Dive

By: Dan Chen
Sequoia: 11/04/2023

Agents are all the rage, but their planning capabilities currently outpace their ability to act reliably. How do we make them truly autonomous?

Over the past several weeks, autonomous AI agents have taken the world by storm. AutoGPT is one of the fastest growing Github repos in history, rocketing past PyTorch, every major Python web framework, and Python itself (sorry Guido) in number of stars. It’s led to some pretty sweet—albeit cherry-picked— demos and has captured the imagination of Twitter thought leaders and AI doomers alike. In a weird twist of fate, the popularity of agents has probably accelerated AI doomerism more than it has accelerated progress towards the superintelligence doomers fear.

An agent’s primary distinction from LLMs is that they run in a self-directed loop, largely augmented by a lightweight prompting layer and some kind of persistence or memory. The architecture varies from agent to agent, with some focused on task prioritization and others taking a more conversational roleplaying approach. The use cases are far reaching, from personal assistants to automated GTM teams. If you’re looking for an excellent primer and thesis on agents, look no further than my colleague Lauren Reeder’s post. And if you’re looking for the cutting edge for this family of agents, there’s LangChain’s recent post on Plan-and-Execute Agents.

Pretty exciting, but how far are we from this reality? In order to truly understand, I am a strong believer in getting to the nuts and bolts. This means getting your hands dirty with the code. So I sat down for an afternoon and took a quick look at the codebases for some popular agents. Here are some observations.

Implementation

The core autonomous agent loops are pretty straightforward. For instance, for AutoGPT, each agent has access to an initial prompt, a set of actions to execute, a history of messages, and a workspace where it can write executable code and files on the fly. An initial prompt might be something like “plan my daughter’s birthday—she really likes unicorns.” The agent then runs on a modified ReAct loop and is able to critique its own action through a second chat completion call with a special prompt that roughly boils down to: “review the proposed action and tell me whether it’s good or bad and why.” The agent calls the OpenAI chat completion endpoint with the following context: the original directive describing the goal of the agent (“plan a sweet unicorn-themed party”), some commands that represent procedural code the agent can run, as well as some short-term memory (the historical context of the agent’s prior reasoning and actions, up to the token limit). The text completion is formatted to a JSON dict of “thoughts” reasoning through the next action to take as well as the next selected action—potentially through another chat completion call. The agent pauses after each loop and waits for user input, which will be included in future context. The context and history can be persisted in storage: Pinecone, Redis, or more recently, Milvus or Weaviate—but honestly a JSON dump works just fine.

Some immediate observations: Although the demos can be astounding, agent implementations are pretty straightforward under the hood. AutoGPT is in essence a light prompting layer running on a recursive loop with persistent memory and which can write executable code on the fly. LangChain has a partial implementation of AutoGPT where they augmented their base agent with the optional human feedback component. It’s important to note: LangChain is a framework that allows for the implementation of various agents, including not just AutoGPT, but also BabyAGI and direct translations of existing research (e.g., ReAct, MRKL – here). AutoGPT is an agent implementation that has made specific decisions on overall architecture and prompting strategy.

    def generate_prompt_string(self) -> str:

        """Generate a prompt string.

        Returns:

            str: The generated prompt string.

        """

        formatted_response_format = json.dumps(self.response_format, indent=4)

        prompt_string = (

            f"Constraints:n{self._generate_numbered_list(self.constraints)}nn"

            f"Commands:n"

            f"{self._generate_numbered_list(self.commands, item_type='command')}nn"

            f"Resources:n{self._generate_numbered_list(self.resources)}nn"

            f"Performance Evaluation:n"

            f"{self._generate_numbered_list(self.performance_evaluation)}nn"

            f"You should only respond in JSON format as described below "

            f"nResponse Format: n{formatted_response_format} "

            f"nEnsure the response can be parsed by Python json.loads"

        )


        return prompt_string


// Prompting strategy in the LangChain AutoGPT implementation

An immediately achievable next step to making these agents useful in practice is expanding their action space: LangChain tools or AutoGPT plugins. These modules define the extended set of commands that an agent can perform. Examples include searching Google or writing some code on the fly. The open source community might expand this finite set of actions with, for instance, Twitter integrations to let the agent read and post tweets, or payments integrations to navigate checkout flows. This is where LangChain and AutoGPT excel: due to recent attention, developers flock to these projects to build plugins. It’s a really interesting moat where, similar to proof-of-work consensus in blockchains, developers are incentivized to build on the most complete plugin ecosystem—the longest chain, so to speak. The hard part is that the set of actions a user can take on the internet is near infinite. To get agents that can do everything humans can do online the long term solution is to have agents reliably write their own procedural code to gracefully handle novel cases, but we need a step function improvement in models before this future is within reach.


LANGCHAIN TOOLS

Currently, agents run like your run-of-the-mill MBA graduate or entry level consultant: they are very good at describing plausible solutions but very poor at executing on them. Put another way, the Act component of ReAct performs poorly in unconstrained environments (ReAct is constrained to a predefined action space), and it is clear that the agent isn’t able to reason at a deeper level about novel situations or problem solve on the fly. A concrete example of this is that agents often hit a wall when the output of an action isn’t what they expect: they try to pull up a tweet, hit a 403: Unauthorized error, and are not quite sure what to do next as they have no notion that calling Twitter might give a different response if the user is not logged in. Practically speaking, the current generation of agents still need quite a bit of human intervention and direction to be effective.

So what’s next?

Building a working autonomous agent in an unconstrained environment is an open research problem. We are still far from this reality. That said, models are improving at an accelerating clip. AutoGPT-like agents represent an interesting practical experiment on agents in an unconstrained environment. Through experimentation and iteration on architecture and prompting strategy and enough open source contributions in the action space (plugins), this approach could plausibly start to bridge the gap between AI doomer fantasy and reality. Here is my agent wishlist to try to get us there:

  • A better headless browser. The kinds of agent directives that work best are the ones that involve researching things on the internet. This works well when the agent starts with a Google search. It works less well when the agent then visits an arbitrary web page. Not only do agents need to understand and gracefully handle various HTTP errors, but also parse an arbitrarily large webpage and potentially execute Javascript to fully mimic a human user experience. Then, the agent would have to map the perceived UX to a limited context window. This is a very hard problem, but if you have a potential solution, here are some places to start.
  • Better command selection. Currently, chat completion is responsible for command selection (“determine which command to use…”). This leads to some pretty crazy hallucinations: for instance, the birthday planning agent shown below tries to reference as an argument a file that doesn’t actually exist. There is probably some clever combination of prompting and procedural code that can minimize hallucinations and help guide the agent in the right direction. For instance, you could try cosine similarity between the embedding vectors across more descriptive versions of current commands and the chat completion response. Or you could try to craft the prompt in a way to minimize edge cases or restrict the creativity of completion outputs. It’s unclear what the right solution is, but there is a lot of room for improvement here. As an aside, this a great opportunity to explore toolformers at the model level.

    {

      ...

      "speak": "Let's start by analyzing any previous conversations or notes we have about the daughter's interests and preferences for her birthday party. This will help us come up with creative and unique ideas for themes, decorations, activities, and entertainment that align with her incentives and preferences. Then we can move on to managing the logistics of the party, including venue selection, guest list management, catering, and budgeting. Finally, we should anticipate and address potential issues or challenges that may arise during the planning and execution of the party to minimize stress and maximize satisfaction."

    },

    "command": {

      "name": "read_file",

      "args": { "filename": "daughter_preferences.txt" }

    }


// Example hallucination (no such file exists!)

  • Optimizations around the action space. While the LangChain agent is parameterized by default (you decide which tools to pass on instantiation), AutoGPT defaults to a set of out of the box actions. Some of these actions give agents a ton of functionality: they can read, write and execute arbitrary code and files. In the best case, this will make agents truly autonomous and self-improving. However, agents are not yet able to generate code and files in productive ways more reliably than they are to fail or hallucinate in doing so. This leads agents to get stuck more often than it leads to novel and working outcomes. The suggestion here is threefold: 1) do a bit of “hyperparameter optimization” around which subset of actions lead to the best agents—and for LangChain, include this as the default set of tools; 2) allow agents to change the action set on the fly, either automatically once they have hit an edge case and run into a loop (should be easy to detect) or manually on user input; 3) build out guardrails, input validation, and better failure mode handling for existing actions (similar to the suggestion for a better headless browser). Also, for AutoGPT, potentially remove some of the more powerful “out there” commands until the models get better.
  • A discriminator to rank actions. The recent Generative Agents paper described a strategy that ranked observations in memory by some linear combination of “recency,” “importance,” and “relevance.” We could try implementing something like this for both memory context and task selection/action prioritization. The devil is in the details. For instance, the paper suggested a separate prompt to rank importance (“on a scale of 1 to 10…”); however, depending on the use case, “importance” could be better estimated by a numerical model (e.g. likelihood estimator) depending on the objective. There is likely no one size fits all solution, and the best approach is likely to start with a simple prompt and go from there.

RANKING ACTIONS FROM THE GENERATIVE AGENTS PAPER

  • More tools and plugins. Over the past two weeks, the number of approved plugins on AutoGPT has ballooned from 2 to almost 20—from Telegram to Wikipedia to crypto. LangChain tools are just as comprehensive. Each additional working plugin expands an agent’s action space and gets it that much closer to mimicking a human on the internet.
  • Agent-to-agent messaging. As agents are deployed in the wild, they can start communicating with each other in novel ways. These ideas are explored in multi-agent simulation environments, but AutoGPT and other unconstrained agents currently operate in single player mode. Messaging could introduce the possibility of more complex relationships between agents with different directives, such as student-coach or competitive peer-peer. This would require a persistence layer for agents, the ability for agents to query all other agents, and a messaging layer, potentially with a discriminator to rank messages by importance that are received between each iteration of the agent (h/t @nicktindle for this observation).
  • Better models. This is a must-have for the frequent gaps in logic the agent exhibits. We don’t quite get there with GPT-4—maybe the next generation of models? In addition, current autonomous agents are slow and expensive. Perhaps it is worth exploring fine-tuning on agent trajectories to make them faster, cheaper and effective for a subset of tasks. Toolformers remain underexplored but promising.

If there is one takeaway from all of this, agents’ reasoning ability is pretty good but their action-taking aspect is still pretty rudimentary. In research, agents largely run in constrained environments with limited abilities to act, like toddlers playing with toy cars in a sandbox. With autonomous commercial agents, we are seeing the first experimental attempts to have agents run in the wild unconstrained. We are giving these toddlers actual cars, so to speak. This is exciting and unprecedented, and would represent a zero-to-one improvement in agents once they work reliably. However, these toddlers don’t know how to drive and are currently crashing into most obstacles that come their way. Do we replace the cars with Tonkas or do we hope that the toddlers grow up? I have made some suggestions on the toy car side in the hopes of making some surprisingly competent toddlers, but if we want truly working autonomous agents, we also need to wait for better models.

Thanks to my colleagues at Sequoia, Lauren Reeder and Charlie Curnin, and to Ankush Gola from LangChain and Michael Graczyk for their thoughtful review and helpful suggestions for this post.

50+ different concepts as code

Mike's Notes

From Patrick Debois. This article is now rescued from the Internet Archive.

Resources

References

  • Reference

Repository

  • Home > Ajabbi Research > Library >
  • Home > Handbook > 

Last Updated

18/05/2025

In depth research and trends analyzed from 50+ different concepts as code

By: Patrick Debois
Jedi.be: 23/02/2022

We all know “infrastructure as code”. It is expanding to bigger constructs , devsecops, workflow , data , documentation, and slowly getting into the business domain. I analyzed the trends from over 50+ concepts “as code”. Do tell me what I’m missing.

As code trends summary

Here’s the TL;DR of the trends:

  • Constructs are getting bigger: we are combining multiple parts in to bigger concepts
  • DevSecOps as code explosion: security is working it’s way into the code constructs
  • Capturing process workflow: not just the infrastructure but also how we act/react to situations
  • Shift “regular” code to declarative code: some aspects can better be defined instead of being coded
  • Data as code: with the advent of MLOps, DataOps, the lines between code and data are blurring
  • Capturing knowledge as code: documentation, architecture and other aspect are becoming part of coding
  • Closer to the business: service levels, business experiments are increasingly getting defined as code


As you can see, expansion is still strong. The concept is now so embedded in our thinking that it feels the natural thing to do. It’s interesting that at the same time as we are expanding “as code” , the term NoCode is resurfacing in our industry. I guess it’s more about “less code”, or more bang for the buck per line of code. Though the concepts of “NoCode” and “NoOps” are just a pipe dream, it makes things more accessible and easier to work with , I’m all for it!

Please read on for a more detailed listing of all the concepts I found. I was surprised with new new findings and I’ve been monitoring the space for a long time.

Is “as Code” the new Model ?

This blogpost started while researching how we think about models in IT. In the old days we would have UML diagrams representing how things work. Maybe it was the Agile manifesto that urged people “Working software over comprehensive documentation”. So code is the new model these days ? As a exploration to see what models , ahum , code are available these days in the IT industry, I sent out the following tweet:

Semantics are getting fluid

I was surprised at the creativity of people’s responses and ideas so I thought it’d be valuable to summarize the feedback:

  • “software defined” is considered an alternative name to “as code”
  • the term “as code” is sometimes perceived as developer centric , yet aren’t we all developer now
  • it is interrelated to DSL (Domain Specific Languages)

People these days seem to take a relaxed view on things being “as code”. It doesn’t matter if it’s YAML or a program language. And even for that matter just data: Infrastructure as code (IaC) and Infrastructure as data (IaD) are often used interchangeably. Reminds me of Lisp where the lines between code and data were also fluid.

Anyways , what people seem to care about:

  • version controlled : able to refer to a specific version
  • repeatable (automated) process : a version can be consistently reproduced
  • easily review changes : most prefer text yet given the right viewer it means human comprehensible change
  • favor declarative over imperative: we prefer to define the future state, not the whole execution in between. Though I personally think sometimes that you want to capture just that.

See how Gartner sees the declarative market or Dan North explaining declarative in the context of a DSL

”Code” is short for “encoded knowledge” IMHO. A config file is distilled source code. Yes. A yaml is IaC - @danbjson

Another way of viewing it how Juan Flores puts it :

For me it’s runtime config. If it’s code, you should be able to test it. Can you test yaml configuration?.

This does raise the question if tests as a concept are required in the concept of Declarative . It’s another one of this outstanding debates whether you test things you define ; I’ve seen the f.i. thje need to test combinations of multiple roles applied to the same node. It would not test the code that puts it into that state, but I’d have to test the combination (Business logic?) I create myself.

Intermezzo : the fun section

Before we dive into the long list of thing I’ve found , I thought we needed a little break ; here’s some gems I found that did not make the serious list:

  • No Code aka No Programmer as code
  • Bugs as code aka Developer as code
  • Code as code aka Bots writing code
  • Chaos as code aka Another day in the office as code
  • ASCII code aka Characters I see

Shout out to @Sam Aaron who promotes “Music as Code”: Related to the concept of Algorave , SonicPI is a great way to make music in realtime while writing beats as code.

And why stop at code? Have a look at The Folders programming language - No code, just folders. More languages like this can be found at https://esoteric.codes/ : Languages, platforms, and systems that break from the norms of computing.

Now we got the fun out of the way on to the real meat of the post: Everything else as code. Note that I tried to link to an article mentioning the flavor of “As code” , google to find more products in that space.

Infrastructure as code and friends

While tests as code (although I never saw that term), were arguably the first as code, it was the concept of Infrastructure as code that popularized the notion. Ruby as a programming language making DSLs easy to create played a big part in this.

Starting with CFengine, Puppet , Chef, Ansible, Salt , Terraforma and now Pulumi this evolved into this popular notion of as code. Technically they all had a mixture of config, code and data that allowed them to spin up infrastructures in a repeatable way (often related to the concept of idempotent code.

Many different specific aspects (storage, network…) spun off and created their own language.

[TABLE]

As code flavor Description

Infrastructure as code managing and provisioning computer data centers through machine-readable definition files

Storage as code / Software Defined Storage defining the allocation of storage in a programmatic way

Network as code / Software Defined Network setup of network components by defining the state

Software Defined Hardware (SDH) runtime-reconfigurable hardware and software that enables near ASIC performance

Configuration as Code (Gitops) Everything that is a configuration change moves through the CI/CD process

Yaml as code (Kubernetes) Standardized way to define cross-cloud cloud-native components

Bigger and Higher level Constructs as code

As code is still expanding beyond the traditional cloud production infrastructure to other parts such as the CI and test environments ; now even defining test infrastructure in code and developer laptops environments.

At the same time there is movement towards combining other concepts as code into a bigger construct such as Platform as code, Environment as code and Application as code.

[TABLE]

As code flavor Description

Pipeline as code A practice of defining deployment pipelines through source code

Platform as code Allows the developers to define their own platform

Environments as code Abstraction over Infrastructure as Code and calls various Infrastructure as Code Components in the right order

Application as code Deploy the app, the infra and all the management tools around it

Dev environment as code Define a developer laptop setup as code

Test Infra as code Define the test infrastructure required as part of your test code

Workflow and Supporting services as code

Now that we got the infrastructure part under control , more and more we can define the supporting infrastructure to support the process of running the infrastructure. In addition we start codifying our workflow and our knowledge of intervention in case of issues or migrations.

[TABLE]

As code flavor Description

Dashboards as code Automate the addition of metrics dashboard/changes along with your infrastructure.

Monitoring as code Automate the entire observability lifecycle, including automated diagnosis, alerting and incident management, and even automated remediation.

DNS as code Managing your DNS configuration as code

Jobs as code Standardizing and automating job scheduling by embedding code using a simple notation that makes API calls to a scheduling engine

Workflow as code Orchestrate the processing of those tasks on different servers — in a way both reliable, scalable, and easy to manage

Operations as code Codifying operational processes into a system capable of executing them on their own.

Security as code

With DevSecOps increasingly becoming an additional driver in DevOps pipelines, it’s only natural that they have their own “as code” explosion. Parts of it are extensions of infrastructure as code theme, but we are learning that other security aspects can be expressed as code.

[TABLE]

As code flavor Description

Security as code Building security into DevOps tools and practices

IAM as code Express the roles and identity creation in code

Policy as code Writing code in a high-level language to manage and automate policies

Detection as code Systematic and comprehensive approach to software-driven threat detection, i.e. machine-readable definition files and descriptive models

Privacy as code Make automated privacy checks part of your CI pipeline

Threatmodel as code Any time someone wants to conduct a threat model, she would open a PR with her changes to a repository

Parts of the code are also being declared

Sometimes we would forget that parts of our code can just be configured/declared, instead of writing code. This is often a result of abstraction or externalization of logic to external services.

[TABLE]

As code flavor Description

Project as code Speedup the creation and maintenance of software projects with code

API as code (OpenAPI) Define the API endpoints so we can both connect our code to it and use it verify what should be allowed in and out

UI as code Instead of pixel positioning each component in code, it’s a lot easier to define these layout compare to coding

Comments as code aka Github Co-pilot Compiled from various and random github projects turning comments into code suggestions

Data being declared

Data schema changes, data quality control, data publishing. All these (past) manual changes are now increasingly done by coding them, making them repeatable and reviewable.

[TABLE]

As code flavor Description

Database as code Managing database schema changes as part of code instead of manually changing them

Data as code The ability to process, manage, consume, and share data in the same way we do for code during software development

Data bias as code / Equity as code Removing bias in data through an approach and methodological tools to impose equity controls on AI algorithm

Documentation and Architecture as code

Many have tried to generate diagrams from their “as code”. This automation always resulted in a bit of “meh”, so now we are extending documentation: just as we are doing “Test Driven” , we can also do “Documentation Driven” , documentation resulting in better capturing of knowledge: architecture, diagrams and even business directions. This complemented with Architectural Decision Records (ADR), make it seem documentation is making a comeback but now in a way that it is integrated in our workflow.

[TABLE]

As code flavor Description

Documentation as code Philosophy that you should be writing documentation with the same tools as code

Diagrams as code Code as an executable architecture description language … use of these tools in order to generate diagrams and documentation during your build process.

Presentation as code No more locked down in presentation, creating presentations is now part of writing code

Architecture as code

(Wardley) mapping as code It takes map code written in the editor and renders it as a Wardley Map

Moving closer to the business - Pipelines are everywhere

Pipelines are everywhere , not just in IT. We have pipelines in Marketing , Sales, Hiring , Legal … No wonder the “as code” paradigm is finding its way in there as well. It is a good sign we’re getting closer to the business ! Also …. a lot scarier as it involves contracts and money :)

[TABLE]

As code flavor Description

Service Level Agreements (SLA) as code Using smart contracts to do payout in case a service is working well

Service Level Objectives (SLO) as code Declaratively defines reliability and performance targets using a simple YAML specification

Law as code When translating law to code, we are turning something liminal into 1s and 0s. Sometimes great ambiguity is hidden in a comma or a word like “reasonable.”

Analytics as code Process of managing and provisioning user behavior event tracking through machine-readable definition files, rather than requirements documents

Contracts as code Automating the process of creating contracts and extracting document data

Management as code Ok … imagine that .. if you find it, let me know

Other industries

I Didn’t really research beyond traditional IT, but found this one interesting to mention

[TABLE]

As code flavour Description

CAD as code Alternative way of creating 3d models in code instead of using a UI composer

AMAZING … YOU … MADE … IT … TILL THE END

Hehe, thanks for reading. Want to support future posts like this?

Subscribe to my musings on one of the socials listed at the top.

Did you find other concepts as code? Please leave a comment and I’ll add it to the list. Happy as code day !

References to tweets

A Modern Dilemma: When to Use Rules vs. Machine Learning

Mike's Notes

This is a great article on the differences between ML and rules.

Resources

References

  • Reference

Repository

  • Home > Ajabbi Research > Library >
  • Home > Handbook > 

Last Updated

18/05/2025

A Modern Dilemma: When to Use Rules vs. Machine Learning

By: Andrew Bonham
Capital One: 06/08/2020

Machine learning is taking the world by storm, and many companies that use rules engines for making business decisions are starting to leverage it. However, the two technologies are geared towards different problems. Rules engines are used to execute discrete logic that needs to have 100% precision. Machine learning on the other hand, is focused on taking a number of inputs and trying to predict an outcome. It’s important to understand the strengths of both technologies so you can identify the right solution for the problem. In some cases, it’s not one or the other, but how you can use both together to get maximum value.

Business Logic, Calculations and Workflows

Let’s start first with understanding business logic. I’ve worked with various types of logic in systems over the years and it’s important to understand the context.

What is business logic? At its simplest form, it’s logic that contains decisions that govern a business process. These decisions are business decisions. The logic tends to be variable with the market and may change often depending on that particular industry’s drivers. The logic focuses on the why and the when. Ultimately a condition has to be true before an action can be taken.

Business logic typically leverages business calculations. Unlike business logic, business calculations tend to stay the same. They focus on the what and the how. It’s important to decouple these two from a deployment aspect as they change at different rates. As a general rule, any reusable logic should be independently deployable. If reusable logic is tied to an application deployment, it can’t be individually reused and is coupled to other components. Ideally, we want to break apart the reusable pieces of an application into microservices so they are independently reusable and deployable. See Martin Fowler’s illustration under “Figure 1: Monoliths and Microservices” as an example.

How do we connect the different steps of business logic together? Workflows.

They are the structured flow or sequencing of work tasks in a business process. Workflows can either be human-based, system-based (e.g. orchestration) or a hybrid between the two. In a previous blog I discussed when to react vs orchestrate.

Approaches for Implementing Business Logic

Now that we understand how these pieces fit together, let’s discuss some approaches for building business logic. In general, there are three different approaches for implementing business logic: Application code, decision table, and a rules engine.

Application Code

Application is a good fit when the logic doesn’t change much and is fairly straightforward.

Decision Table
Condition 1 Condition 2 Condition 3
HasSpeedingTicket HadAccident SetDiscount;
False False 20
True False 10
False True 5
True True 0

Decision tables are a good fit for logic that changes often and has a large number of conditions that are easier to manage in a table than code.


Rules Engine

A rules engine is a good fit for logic that changes often and is highly complex, involving numerous levels of logic. Rules engines are typically part of a Business Rules Management System (BRMS) that provide extensive capabilities to manage the complexity.

If we put this guidance into quadrants, it would look something like the below:

Business logic usage graph

As the rate of complexity and rate of change increases, application code is no longer suitable for business logic. Decision tables provide some relief as the rate of change increases, but ultimately a BRMS provides the best fit for high rate of change and high complexity.

Business Rules Management System (BRMS)

Let’s take a closer look at the capabilities of a BRMS by reviewing the below capability reference view:



BRMS capability reference view

Let’s touch on a couple of the key capabilities in this reference view and highlight some that also overlap with machine learning capabilities.

Rule Authoring

A Technical rule or Guided rule provides two different ways to author rules geared towards different end users. Technical rules are more for your developer audience, where guided rules consist of a point and click approach that may be better for less technical users.

A Domain Specific Language (DSL) is another capability that can enable non-technical users to write rules in an easier to use language.
Neural Networks are a form of an algorithm used in machine learning, it’s interesting to see that some BRMS have integration with this.

Rule Management

The rule repository is one of the most powerful capabilities of a BRMS. It is the mechanism in which developers can find out what has already been built and what they may be able to reuse. Rule metadata is stored here that is critical in understanding the underlying intent.

Deployment

Typically, rules can be deployed in one of two ways - either as part of a standalone service that is invoked via REST API calls, or embedded as part of the application (in-process). A little later in this article, we will see that machine learning platforms share a similar model.

Rule Execution & Deployment

Predictive Model Markup Language (PMML), or Portable Format for Analytics (PFA), are both industry standard formats for making models interchangeable. They enable you to build a model in one language or platform and port it into another language or platform that supports PMML or PFA.

***

One such example of a BRMS is Drools. Drools is an open source Apache licensed, Java-based rules engine. It supports a forward and backward chaining inference engine that leverages the PHREAK algorithm. This inference engine comes in handy if you want the rules engine to decide the order of your rules. Drools provides guided rules, technical rule DRL syntax, and support for Domain Specific Language (DSL). Drools also supports both in-process and standalone deployment models.

Machine Learning Platforms

Now that we have a good understanding of Rules Engines, let's compare them to Machine Learning Platforms. In a previous post, I provided an overview of what machine learning is and how you can use it with open source BPM. In a similar post, I explain how you can use machine learning with Akka. Let’s now take a look at a capability reference view for a machine learning platform.



Machine Learning Platform Capability Reference View

Let’s touch on some of the key capabilities and again tie back to similar overlap with the BRMS view.

Data Ingestion

Data is the most important thing in machine learning. Your model is only as good as your data. You want as much data as possible and that may include both batch and real-time data sources.

Feature Engineering

Features are the inputs into models and some ML Platforms provide capabilities for you to create those features. Others provide capabilities that can automatically generate the features for you.

Modeling Paradigms

These different algorithms can be used in a machine learning model. An important thing to note here is they aren’t tied to Supervised, UnSupervised, or Reinforcement Learning categories, rather they can be used across all three.

Deployment & Execution

You will notice some similarities to the BRMS capabilities in this space, specifically in-process and standalone REST API deployments along with support for PMML.

Management

One of the most important aspects of managing a machine learning model is monitoring it for accuracy. A common fallacy with machine learning is that a ML model never needs to be retrained as it can learn itself. That is not the case as machine learning models have to be re-trained every so often as the data they are trained on starts to drift from the data they are executing against in production.


***

By comparing the capabilities of machine learning platforms with rules engines we can now see how there are similarities along with differences at the capability level. Given how products in these areas are continuing to become closer together, it’s understandable how the choice between the two can be difficult.



Comparison between rules engines and machine learning platforms

Guidance for When to Use Rules Engine vs. Machine Learning

So how do we make the decision of when to use a Rules Engine or Machine Learning? To answer this, let’s answer this question from the dimensions of logic, logic type, what creates the logic, and data. Rules are a good fit in the situation where:

  • Logic: Exact logic is known. With rules you know ahead of time the logic you want to execute.
  • Logic Type: Precision based. If then business logic is precise and does not involve any predictions. It results in boolean type outcomes based on evaluation of facts.
  • Logic Creation: Done by a human. Software Engineers or business users create the rules that represent business logic.
  • Data: Don’t need to automatically derive the logic from the data. Analysis typically occurs on data beforehand to determine what the exact logic should be.

Now, let’s look at machine learning using these same dimensions:

  • Logic: Exact logic is not known. Rather the inputs/features that are significant in creating a prediction may be known.
  • Logic Type: Prediction based using algorithms.
  • Logic Creation: Created by machine learning software that runs using algorithms via training.
  • Data: Is used to ultimately generate the model logic. Is the most important thing in machine learning. You want to use as much data as possible and also make sure the data is unbiased. If the data is biased, then the model will become biased.

In summary, leverage rules when you need precision and know the logic. Leverage machine learning when you want to predict something but don’t know exactly how.

But is it always as clear cut as that? What if you wanted to use the power of both? The answer is you can. There are a number of hybrid patterns where you can use machine learning and rules together to determine an outcome. Let’s look at an example use case.

Patterns for Using Machine Learning and Rules Engines Together

Imagine the use case where you are a realtor wanting to provide the best guidance to your clients on purchasing a home. Maybe there are several they are interested in, but aren’t sure how quickly they should act. Let’s walk through three different patterns for combining machine learning and rules together to achieve this.

Pattern 1: Leverage machine learning outputs as an input into rules

In this pattern, two different machine learning models execute. One determines the probability of a house selling in 10 days. Another determines the probability of the sellers dropping the asking price. Both of these predictions are an input into rules. The rules then evaluate the output of the model and ultimately provide a recommendation to the realtor. Specifically, if the probability of the house selling in 10 days is greater than 50%, and the probability of the sellers dropping the price is less than 50%, then this pattern makes a specific recommendation for the realtor.



Pattern 1: leverage machine learning output as an input into rules

Pattern 2: Leverage rule outputs as a feature input into machine learning models

In this pattern, we start with the rules being the input into the machine learning models. Rules execute business logic to determine boolean based values. Does the house need repairs? Is it the selling offseason? Do the sellers want to get rid of the house and sell it now? The output of these rules then are features into the machine learning models. The machine learning models then provide a probability back to the realtor of the house selling in 10 days and the sellers dropping the price. Notice in this pattern there is not a recommendation back to the realtor, rather the probability is provided and final recommendation left up to the realtor.


Pattern 2: Leverage rule outputs as a feature input into machine learning models


Pattern 3: Leverage both rule and machine learning outputs as inputs

In this pattern, it follows a mix of the previous two patterns. Both rules and machine learning outputs are inputs into a machine learning model. In this scenario the probability of the sellers dropping a price is an input into the probability of the house selling in 10 days. This pattern also leaves the ultimate recommendation up to the realtor.



Pattern 3: Leverage both rule and machine learning outputs as inputs

An Example Implementation

Now let’s apply these patterns to an actual proof of concept. I am going to build off of a previous reactive microservice machine learning proof of concept that I built in a previous post. We will enhance it to contain a rules service that the machine learning model takes as an input. It will use Pattern 1 above, Leverage machine learning outputs as an input into rules.

Let’s start with what we are changing in the proof of concept to support the integration of rules with machine learning. Below is a diagram that illustrates the architecture:



Architecture for example proof of concept

All components of the previous proof of concept hold true, (please see that previous blog for the details as I won’t repeat them here). The one new thing we introduced is the Java-based Rules MS. This is the rules microservice that will evaluate the output of the machine learning model probability. H20 outputs a confidence value as part of its predictions. For a transaction that the machine learning model determines is OK/Not Fraudulent, the rules service will check this confidence value. If the confidence value is less than 50%, then it will evaluate the output of some additional fraud checks, in this case name and address. If either of those failed, the rule will recommend that the transaction is Fraudulent.

Here is a sequence flow that walks through the steps:


Now let’s take a look at the Java Rules MS code to see how a drools rule would operate.

    rule “Trans OK and Prob < 0.50 and name check fail”
  when
     m : RulesData( modelProb <= 0.50, mymodelProb : modelProb)
     RulesData( status == “Transaction OK” )
     RulesData( nameCheck <= 0 )
  then
     m.setStatus(“Fraudulent Transaction from Rules, name check   
     failed”);
end
rule “Trans OK and Prob < 0.50 and address check fail”
  when
     m : RulesData( modelProb <= 0.50, mymodelProb : modelProb)
     RulesData( status == “Transaction OK” )
     RulesData( addressCheck <= 0 )
  then
     m.setStatus(“Fraudulent Transaction from Rules, address check
     failed”);
end

We can see this is using the Drools drl syntax, which is a way to write technical rules. There are two rules both checking if the transaction is OK and the machine learning output is less than 50%. The first rule also checks if a name check fails, where the second checks if an address check fails. You’ll notice in Drools there are not any else clauses. That is by design and rules fire based on  conditions you specify. Within each rule you notice a RulesData function that is checking the status of several variables. In order for Drools rules to be evaluated against data, you have to create a POJO that represents the data model. This will include the getters and setters. See example below:

    public static class RulesData {
  private int nameCheck=0, addressCheck=0;
  private String status=null;
  private double modelProb=0;
  public String getStatus() {
     return this.status;
  }
  public int getNameCheck() {
     return this.nameCheck;
  }
  public int getAddressCheck() {
     return this.addressCheck;
  }
  public double getModelProb() {
     return this.modelProb;
  }
  public void setNameCheck(int nameCheck) {
     this.nameCheck = nameCheck;
  }
  public void setAddressCheck(int addressCheck) {
     this.addressCheck = addressCheck;
  }
  public void setModelProb(double modelProb) {
     this.modelProb = modelProb;
  }
  public void setStatus(String status) {
     this.status = status;
  }
}

Let’s look at a snippet of the Java code that invokes the Drools rules, see below:

    //run drools rules
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
// go !
kSession.insert(applicant);
kSession.fireAllRules();
kSession.destroy();

This code creates a KieSession and then inserts the data we want the rules to execute against into the KieSession. FireAllRules() tells Drools to do just that, fire all rules. Then Destroy() is used for cleanup. The Java based Rules MS takes the output of the drools rules and ultimately writes it to Kafka where it can be consumed.

Summary

Rules and machine learning each have their own strengths and are even more powerful when used together. Using the right solution for the problem is key. Leverage rules when you need precision and know the logic, leverage machine learning when you want to predict something but don’t know exactly how. Both can be used in a reactive microservices architectural style that provides a more maintainable, scalable, and faster to deliver architecture.

I hope you found this blog valuable and thank you for your time!

Andrew Bonham, Senior Distinguished Engineer/Architect
Senior Distinguished Engineer with a passion in microservices, open source, cloud, reactive architectures. business process management, and rules engines.

Loss Functions

Mike's Notes

Nature recently had an interesting article about loss functions. This could be useful as a way to check Pipi.

Resources

References

  • Reference

Repository

  • Home > Ajabbi Research > Library >
  • Home > Handbook > 

Last Updated

18/05/2025

Inside the maths that drives AI

By: Michael Brooks
Nature: 03/07/2024

Loss functions provide a mathematical measure of wrongness: they tell researchers how well their artificial-intelligence (AI) algorithms are working. There are dozens of off-the-shelf functions. But choosing the wrong one, or handling it badly, can create AI systems that blatantly contradict human observations or obscure experiments’ central results. Programming libraries such as PyTorch and scikit-learn allow scientists to easily swap and trial functions. A growing number of scientists are creating their own loss functions. “If you’re in a situation where you believe that there are probably errors or problems with your data … then it’s probably a good idea to consider using a loss function that’s not so standard,” says machine-learning researcher Jonathan Wilton.

 ..." - Nature

Wikipedia

"In mathematical optimization and decision theory, a loss function or cost function (sometimes also called an error function) [1] is a function that maps an event or values of one or more variables onto a real number intuitively representing some "cost" associated with the event. An optimization problem seeks to minimize a loss function. An objective function is either a loss function or its opposite (in specific domains, variously called a reward function, a profit function, a utility function, a fitness function, etc.), in which case it is to be maximized. The loss function could include terms from several levels of the hierarchy.

In statistics, typically a loss function is used for parameter estimation, and the event in question is some function of the difference between estimated and true values for an instance of data. The concept, as old as Laplace, was reintroduced in statistics by Abraham Wald in the middle of the 20th century.[2] In the context of economics, for example, this is usually economic cost or regret. In classification, it is the penalty for an incorrect classification of an example. In actuarial science, it is used in an insurance context to model benefits paid over premiums, particularly since the works of Harald Cramér in the 1920s.[3] In optimal control, the loss is the penalty for failing to achieve a desired value. In financial risk management, the function is mapped to a monetary loss. ..." - Wikipedia