Accelerating Application Modernization with Agentic AI

Accelerating Application Modernization with Agentic AI

arrow

December 12, 2024

  • 12 mins read

What is Agentic AI?

Agentic AI refers to a class of autonomous artificial intelligence systems capable of performing tasks with minimal human intervention, exhibiting decision-making abilities, and executing goal-directed behavior. Unlike traditional AI, which typically follows predefined instructions, Agentic AI can interact with its environment, adapt to new situations, and make real-time decisions. These agents are designed to accomplish complex goals and workflows with an advanced level of autonomy.

How Does Agentic AI Work?

Agentic AI systems combine multiple advanced AI techniques to create autonomous agents capable of managing complex tasks. Below are the core components that enable Agentic AI to function:

  1. Autonomy: At the core, Agentic AI is designed to work without constant human supervision. Using reinforcement learning (RL) or unsupervised learning techniques, the system can explore environments, learn from their experiences, and take actions based on feedback, gradually refining its capabilities.
  1. Contextual Understanding: To interpret and act upon tasks, Agentic AI needs to comprehend the environment, which often includes understanding ambiguous instructions or contextual information. It employs Natural Language Understanding (NLU) to process natural language queries, allowing for more intuitive human-agent interactions. Furthermore, it utilizes semantic knowledge graphs to provide deeper understanding and reasoning over information.
  1. Action Execution: Agentic AI systems often integrate with a variety of technologies (e.g., APIs, IoT devices, cloud services) to execute physical or digital actions based on the decisions made. These agents act autonomously but within the parameters of specific goals or constraints, ensuring that tasks are carried out effectively and efficiently.

Leveraging Agentic AI for Application  Modernization

Agentic AI is significantly transforming  application modernization, offering solutions to tasks like code conversion, debugging, version upgrading, and test case generation. The following steps explains how it can be applied in a technical context:

1. Code Conversion:

Task Breakdown: Agentic AI can convert legacy code from one programming language to another, such as from COBOL to Java., Flask to Fastapi. It uses deep learning models trained on large datasets of code snippets, leveraging NLP to understand the semantic structure of code and translate it into a different programming language with equivalent functionality.

AI Techniques: This process uses code analysis techniques such as Abstract Syntax Trees (AST) parsing and semantic code understanding. The agent performs syntax-based mapping and code restructuring while maintaining the original logic and functionality.

Real-time Adaptation: By analyzing developer input and external contexts (e.g., evolving language features), Agentic AI ensures continuous accuracy in code conversion, adapting to new language constructs or deprecated features.

Conversion of Flask to FastAPI

In the code, the key objective is converting Flask-based applications to FastAPI, which is more efficient, faster, and supports asynchronous execution natively.

Python code example:

#Importing Necessary Libraries
import os
import sys
from groq import Groq
from autogen import ConversableAgent, config_list_from_json

Configuration Setup:

We configure the Groq API key and the LLM model name:

GROQ_API_KEY = os.getenv("GROQ_API_KEY")
LLM_MODEL_NAME = os.getenv("LLM_MODEL_NAME")

config_list = [
{
"model": LLM_MODEL_NAME,
"api_key": GROQ_API_KEY,
"api_type": "groq",
}
]

llm_config = {
"config_list": config_list,
"temperature": 0.7,
}

Directory Setup for Saving Files:

work_dir = "./fastapi_conversion"
os.makedirs(work_dir, exist_ok=True)

We create a directory (./fastapi_conversion) to save the converted FastAPI code, test cases, and results.

Helper Functions:

def is_termination_msg(content):
if isinstance(content, dict):
content = content.get('content', '')
return isinstance(content, str) and content.strip().lower() == "task completed"

This function checks if a message indicates task completion. It helps in ending the conversation flow after the process is finished.

Functions to Save Files:

def save_fastapi_code(agent, messages, sender, config):
last_message = messages[-1]['content']
if "```python" in last_message:
fastapi_code = last_message.split("```python")[1].split("```")[0].strip()
else:
fastapi_code = last_message.strip()
file_path = os.path.join(work_dir, 'converted_fastapi_code.py')
with open(file_path, 'w') as f:
f.write(fastapi_code)
return True, f"FastAPI code saved as 'converted_fastapi_code.py'. Now writing test cases."

def save_test_cases(agent, messages, sender, config):
last_message = messages[-1]['content']
if "```python" in last_message:
test_code = last_message.split("```python")[1].split("```")[0].strip()
else:
test_code = last_message.strip()
file_path = os.path.join(work_dir, 'test_fastapi_code.py')
with open(file_path, 'w') as f:
f.write(test_code)
return True, "Test cases saved. Now executing tests."

def save_test_results(agent, messages, sender, config):
last_message = messages[-1]['content']
test_results = last_message.strip()
file_path = os.path.join(work_dir, 'test_results.txt')
with open(file_path, 'w') as f:
f.write(test_results)
# Parse and summarize the test results
total_tests = test_results.count("test_")
passed_tests = test_results.count("PASSED")
failed_tests = test_results.count("FAILED")
summary = f"""
Test Execution Summary:
Total tests run: {total_tests}
Tests passed: {passed_tests}
Tests failed: {failed_tests}

Detailed results have been saved in 'test_results.txt'.
"""
return True, f"Test results saved. {summary}\nTask completed."

This function saves the converted fastapi code, test cases, and test execution results and provides a summary of the tests (total tests, passed and failed).

Conversable Agents:

Each of the following agents handles a specific task in the conversation flow:

Flask Code Receiver Agent:

def flask_code_receiver(llm_config):
agent_flask_receiver = ConversableAgent(
name="agent_flask_receiver",
system_message="""You are an agent that receives Flask code and passes it to the FastAPI converter agent. 
After receiving the converted code, save it and end the conversation by saying 'Task completed'.""",
llm_config=llm_config,
human_input_mode="NEVER",
max_consecutive_auto_reply=1,
is_termination_msg=is_termination_msg
)
return agent_flask_receiver

This agent receives Flask code and passes it to the FastAPI converter agent. It will end the conversation once the task is completed.

def convert_flask_to_fastapi(llm_config):
agent_fastapi_converter = ConversableAgent(
name="agent_fastapi_converter",
system_message="""You are an expert in converting Flask code to FastAPI code. 
When you receive Flask code, convert it to equivalent FastAPI code. 
Return only the converted FastAPI code without any additional explanations.""",
llm_config=llm_config,
human_input_mode="NEVER",
max_consecutive_auto_reply=1,
is_termination_msg=is_termination_msg)
return agent_fastapi_converter

This agent converts Flask code into equivalent FastAPI code.

2. Code Test Cases:

Test Generation: Agentic AI can automatically generate unit tests, integration tests, and performance tests. It utilizes techniques such as symbolic execution, constraint solving, and combinatorial test generation to create comprehensive test suites for a given codebase.

Test Coverage Analysis: The AI agent analyzes the code’s coverage by comparing test results with the code’s logic and identifies areas that require additional test cases. The system can also suggest edge cases or boundary conditions that would typically be missed in manual testing.

Automated Test Execution: Using CI/CD pipelines, Agentic AI executes these tests autonomously, monitors the results, and flags any regressions or issues detected during test execution, providing real-time feedback to developers.

Test Cases Writer Agent:

def test_cases_writer(llm_config):
agent_test_writer = ConversableAgent(
name="agent_test_writer",
system_message="""You are an expert in writing test cases for FastAPI applications.
When you receive FastAPI code, write comprehensive test cases for it.
Include tests for all endpoints and edge cases. Use pytest for writing the tests.
Import the necessary components from the 'converted_fastapi_code.py' file in your test code.
Ensure that your test cases are specific to the provided FastAPI code and its endpoints.""",
llm_config=llm_config,
human_input_mode="NEVER",
max_consecutive_auto_reply=1,
is_termination_msg=is_termination_msg)
return agent_test_writer

This agent generates test cases for the FastAPI code using pytest.

Test Cases Executor Agent:

def test_cases_executor(llm_config):
agent_test_executor = ConversableAgent(
name="agent_test_executor",
system_message="""You are an expert in executing test cases for FastAPI applications.
When instructed, execute all the test cases in 'test_fastapi_code.py' for the FastAPI code in 'converted_fastapi_code.py'.
Use pytest to run the tests and provide a detailed summary of all passed and failed tests.
Ensure you run every single test case and report on each one.
Your output should include:
1. The total number of tests run
2. The number of tests passed
3. The number of tests failed
4. Detailed information on any failed tests, including the test name and error message
5. A list of all test names that were executed
Assume both files are in the current working directory.
After execution, format your response as a structured report.""",
llm_config=llm_config,
human_input_mode="NEVER",
max_consecutive_auto_reply=1,
is_termination_msg=is_termination_msg)
return agent_test_executor

This agent executes the test cases using pytest and provides a detailed test execution summary.

Full FLow:

def agent_conversation_flow(flask_code):
agent_flask_receiver = flask_code_receiver(llm_config)
agent_fastapi_converter = convert_flask_to_fastapi(llm_config)
agent_test_writer = test_cases_writer(llm_config)
agent_test_executor = test_cases_executor(llm_config)
agent_flask_receiver.register_reply(
[agent_fastapi_converter],
reply_func=save_fastapi_code,
config={"cancel_on_output": True}
)

agent_fastapi_converter.register_reply(
[agent_test_writer],
reply_func=save_test_cases,
config={"cancel_on_output": True}
)

agent_test_writer.register_reply(
[agent_test_executor],
reply_func=save_test_results,
config={"cancel_on_output": True}
)

agent_flask_receiver.initiate_chat(
agent_fastapi_converter,
message=f"Convert this Flask code to FastAPI:\n\n{flask_code}"
)

fastapi_file_path = os.path.join(work_dir, 'converted_fastapi_code.py')
with open(fastapi_file_path, 'r') as f:
fastapi_code = f.read()
return fastapi_code

This function initiates the conversation flow. The Flask code is passed through each agent, and the system follows the sequence of converting the code, writing test cases, executing them, and saving the results.

Exploring the Diverse Use Cases of Agentic AI

Agentic AI is turning heads in multiple dimensions, such as in automating activities, decision-making, and guesstimation in manners that were not moldable in the past. Some of the significant use cases of Agentic AI are as Followed:

  1. AI Agents in HR: AI agents are transforming human resources by automating tasks like resume screening, interview scheduling, payroll processing, and performance monitoring. Tools like Kompas AI and PepsiCo's Hired Score use AI to streamline recruitment and enhance decision-making processes.
  2. AI Agents as Developers: Solutions such as Github Copilot assist developers in executing their tasks effectively by suggesting code, fixing bugs, and sometimes even debugging the work completely. Such AI agents assist in offering vast codes and prediction models to propose solutions while also automating monotonous coding operations, thus improving interoperability throughout the development timeline.
  3. AI Agents as Human-like Gaming Characters: In gaming, automatic controlling agents revolutionize the behavior of NPCs. The Stanford AI Village is a perfect example, where 25 AI agents are deployed to act as players and graze in the adaptive environment, interacting with the players. These agents alter their actions based on those of the players and exhibit sophisticated behaviors such as resourcefulness in finding the intended location.
  4. AI Agents as Writers: AI writing assistants have made headlines as changing the communication landscape — be it technical writing or novels. These agents employ natural language processing (NLP) whereby users provide content input, and such agents comprehend instructions and generate vertical-specific content, including grammar checking, anti-plagiarism, and audience-based writing styles.
  5. AI Agents as Insurance Assistants: In the insurance sector, Agentic AI automates underwriting, claims processing, fraud detection, and customer support. By analyzing data from claims, policies, and customer interactions, AI agents assist in streamlining operations and improving accuracy and efficiency.

Conclusion

Agentic AI is at the forefront of transforming industries by enabling autonomous decision-making, efficient task execution, and intelligent problem-solving. From automating code generation and debugging to enhancing user experiences in gaming, retail, and insurance, Agentic AI applications are proving to be a game changer in various sectors. By leveraging deep learning, reinforcement learning, and advanced reasoning techniques, Agentic AI brings efficiency, speed, and accuracy to traditionally complex processes. As AI continues to evolve, Agentic AI will become an integral part of how businesses operate, innovate, and scale their operations.