Integrating AI with network automation allows us to analyze network data more efficiently. Instead of manually reviewing command outputs, the AI can process parsed results, highlight potential issues, and even detect patterns that may not be explicitly encoded in standard validation logic. For this purpose, we use the OpenAI GPT-3.5-Turbo model, which helps save time, reduce routine work, and make troubleshooting faster and easier.
Intelligent Network Automation
During this course, we have used pyATS to perform network automation, focusing on writing test cases that automatically test network components. We learned how to use pyATS to connect and disconnect from devices using a testbed and how to use Genie to structure command outputs for easier automated processing.
Now, we are taking a step further by integrating AI into network automation. Instead of manually analyzing command outputs, we can feed the data to AI, which can process it more efficiently, provide more accurate insights, and even identify patterns that are usually difficult for humans to notice.
AI in Network Automation Script Example
To better understand how AI can be applied in network automation, we will start with a simple script example.
The first section of this script handles the setup, connection, and data collection from network devices. It loads a pyATS testbed YAML file describing the devices, connects to all of them, and iterates through each device to run the show ip interface brief
command. The parsed JSON output from each device is then sent to the OpenAI GPT model, which acts as a network assistant to evaluate the health of all interfaces. This allows the AI to identify issues such as down interfaces, misconfigurations, or inconsistencies that might be overlooked during manual inspection. By converting raw JSON into a human-readable analysis, the AI streamlines network monitoring and troubleshooting.
(majid) majid@majid-ubuntu:~/devnet/pyats$ cat 11.0.interface_health_check_openai.py # pip install pyats genie.libs # pip install openai # export OPENAI_API_KEY="your_api_key_here" import os import json import logging import pytest from genie.testbed import load from openai import OpenAI # Setup logging logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) # OpenAI API key from environment openai_api_key = os.getenv("OPENAI_API_KEY") if not openai_api_key: raise RuntimeError("Please set the OPENAI_API_KEY environment variable.") # Instantiate OpenAI client client = OpenAI(api_key=openai_api_key) # Load your pyATS testbed YAML TESTBED_FILE = "testbed.yaml" # Change this to your testbed file testbed = load(TESTBED_FILE) # Connect to all devices log.info("Connecting to devices...") testbed.connect() def save_json(data, filename="interface_data.json"): """Save JSON data to a file.""" with open(filename, "w") as f: json.dump(data, f, indent=2) def analyze_interface_with_ai(interface_state): """Send interface JSON to OpenAI GPT for health analysis.""" response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ { "role": "system", "content": "You are a helpful network assistant who will analyze Cisco 'show ip interface brief' JSON and report its health." }, { "role": "user", "content": f"Please analyze this JSON and tell me if the interfaces are healthy or have issues:\n{json.dumps(interface_state)}" } ] ) ai_output = response.choices[0].message.content return ai_output # Main test for device_name, device in testbed.devices.items(): log.info(f"Parsing 'show ip interface brief' on device: {device_name}") try: # Parse command instead of learn parsed_json = device.parse("show ip interface brief") save_json(parsed_json, f"{device_name}_show_ip_int_brief.json") # Analyze the whole parsed result at once log.info(f"Analyzing interfaces on {device_name}...") ai_result = analyze_interface_with_ai(parsed_json) log.info(f"AI analysis for {device_name}:\n{ai_result}\n") except Exception as e: log.error(f"Error on device {device_name}: {e}") # Disconnect devices after testing log.info("Disconnecting devices...") testbed.disconnect() log.info("Test complete.")
A valid OpenAI API key is required to connect to OpenAI’s servers. This key can be obtained by creating an account on OpenAI’s platform and generating a key from the account dashboard. While creating the key is free, using the API beyond free trial credits incurs usage-based costs.
The function analyze_interface_with_ai(interface_state)
is defined to take one argument: interface_state
, which is expected to be the parsed JSON output of the show ip interface brief
command. Within the function, this JSON is converted to a string and sent to the OpenAI GPT model via client.chat.completions.create()
. In the OpenAI Chat API, messages structure the conversation for the model, with three key components: model
, role
, and content
. The model
parameter specifies which OpenAI model to use, such as "gpt-3.5-turbo"
, which can be replaced with other models like "gpt-4"
or "gpt-4-turbo"
depending on the required accuracy, reasoning ability, or cost.
Each message also includes a role
:
System message sets the overall behavior, instructions, or “persona” of the AI.
User message contains the actual input to analyze, such as the interface JSON.
Assistant message (optional) represents prior AI responses, used to maintain context in ongoing conversations.
The function extracts the AI’s response from response.choices[0].message.content
and returns it as a human-readable analysis. After processing all devices, the script disconnects from the testbed and logs the completion of the test.
Validating Network Interface Health with AI
When the script is executed, it connects to the devices in the testbed and runs the show ip interface brief
command. The output is parsed into structured JSON using Genie and then sent to OpenAI’s GPT-3.5 model for analysis. The AI reviews the interface states and returns a plain-language health check: for example, on R1 all interfaces were reported as healthy, while on R2 most interfaces were fine except for GigabitEthernet3, which was flagged as administratively down. After completing the analysis, the script disconnects from the devices and logs the results, providing an automated and AI-driven summary of network interface health.
(majid) majid@majid-ubuntu:~/devnet/pyats$ python 11.0.interface_health_check_openai.py > openai_showipintbrief INFO:__main__:Connecting to devices... INFO:__main__:Parsing 'show ip interface brief' on device: R1 INFO:__main__:Analyzing interfaces on R1... INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK" INFO:__main__:AI analysis for R1: Based on the provided JSON data from the 'show ip interface brief' command, all interfaces appear to be healthy as they have "interface_is_ok" set to "YES", the "status" is "up", and the "protocol" is also "up". All interfaces seem to have IP addresses assigned and are operational. In summary, there are no reported issues with the interfaces based on this information. INFO:__main__:Parsing 'show ip interface brief' on device: R2 INFO:__main__:Analyzing interfaces on R2... INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK" INFO:__main__:AI analysis for R2: Based on the provided JSON data from the 'show ip interface brief' command, here is the analysis of the interfaces: 1. GigabitEthernet1: - IP Address: 10.13.14.17 - Interface Status: up - Protocol Status: up - Interface Health: Healthy 2. GigabitEthernet2: - IP Address: 10.13.15.17 - Interface Status: up - Protocol Status: up - Interface Health: Healthy 3. GigabitEthernet3: - IP Address: 192.168.170.1 - Interface Status: administratively down - Protocol Status: down - Interface Health: There seems to be an issue with this interface as it is administratively down. 4. Loopback0: - IP Address: 2.2.2.2 - Interface Status: up - Protocol Status: up - Interface Health: Healthy 5. Loopback2: - IP Address: 4.2.2.4 - Interface Status: up - Protocol Status: up - Interface Health: Healthy 6. Loopback3: - IP Address: 8.8.8.8 - Interface Status: up - Protocol Status: up - Interface Health: Healthy 7. Loopback100: - IP Address: 10.10.100.100 - Interface Status: up - Protocol Status: up - Interface Health: Healthy 8. Loopback101: - IP Address: 192.168.171.1 - Interface Status: up - Protocol Status: up - Interface Health: Healthy 9. NVI0: - IP Address: unassigned - Interface Status: up - Protocol Status: up - Interface Health: Healthy Overall, most of the interfaces are healthy, except for GigabitEthernet3 which is administratively down. This might need to be checked and corrected to ensure proper network connectivity. INFO:__main__:Disconnecting devices... INFO:__main__:Test complete.