Generating PlantUML Diagrams with ChatGPT

10 min read Original article ↗

Lars de Ridder

Press enter or click to view image in full size

Photo by James Harrison on Unsplash

Using ChatGPT to generate diagrams offers a streamlined and efficient way to visually represent complex systems, processes, and relationships. By converting natural language prompts into detailed graphical representations, ChatGPT enables users to quickly create a wide variety of diagrams, such as UML diagrams, flowcharts, and more. Additionally, this approach should improve communication among team members, simplify documentation, and enhances the overall understanding of the underlying concepts or systems being modeled.

In this article, we will focus on PlantUML for diagrams. PlantUML is a powerful tool that helps you create diagrams and visualizations using simple text-based syntax. Combining the power of ChatGPT with PlantUML allows you to generate diagrams by simply describing them in plain text.

In this article, we will explore how to use ChatGPT to generate PlantUML diagrams from various sources, such as code snippets, descriptions, and even real-world Kubernetes cluster configurations. We will cover the following types of PlantUML diagrams: class diagrams, sequence diagrams, activity diagrams, deployment diagrams, and more.

Prerequisites:

  1. Basic understanding of PlantUML syntax
  2. Access to ChatGPT (e.g., through OpenAI API)
  3. PlantUML rendering tool (such as plantuml.jar or an online service)

Understand PlantUML Basics

Before you use ChatGPT to generate PlantUML graphs, it is useful to familiarize yourself with PlantUML syntax. The official documentation (https://plantuml.com/) is a great resource for understanding the different types of diagrams you can create and their syntax. You should be able to follow this article without more than a basic understanding however.

Basic flow

Setting Up ChatGPT for PlantUML

To use ChatGPT for PlantUML, you will be sending text prompts to ChatGPT describing the diagram you want to create. For instance, if you want to create a class diagram, you can send a prompt like:

Generate a PlantUML class diagram with three classes: Person, Student, and Teacher. Student and Teacher classes should inherit from the Person class.

Process ChatGPT Output

When you send the prompt, ChatGPT will return a PlantUML code snippet based on your description. For example:

@startuml
class Person {
+display_info(): void
}

class Student {
+calculate_grade(): void
}

class Teacher {
+Students: List<Student>
}

Person <|-- Student
Person <|-- Teacher
Teacher "1" -- "many" Student: teaches
@enduml

Render the diagram

You can now render the generated PlantUML code using your preferred tool. You can either use the PlantUML command-line tool (plantuml.jar) or an online service like http://www.plantuml.com/plantuml/. To render your diagram, simply paste the PlantUML code into the rendering tool, and it will generate the corresponding diagram.

Iterating over the result

Use the ChatGPT response to improve and iterate over the diagram. ChatGPT remembers what you said before, so an iterative process works really well. You don’t need to provide all details up front, you can work on it as you go.

Some example prompts to improve or expand the above model:

  • “Add a method called ‘display_info()’ to the Person, Student, and Teacher classes in the PlantUML diagram.”
  • “Add a relationship between the Student class and the Teacher class, indicating that a Teacher can have multiple students.”

You can also correct mistakes in the generated diagram by providing a new prompt with instructions to fix the issue. For example, if the diagram is missing a specific method, you can provide a prompt like:

  • “Add a ‘calculate_grade()’ method to the Student class in the PlantUML diagram.”

Generating different types of diagrams

In this section, we will explore how you can use ChatGPT to generate two other types of PlantUML diagrams, specifically sequence diagrams and activity diagrams.

Sequence Diagrams:

Sequence diagrams are used to visualize interactions between objects in a time-ordered sequence. You can generate a sequence diagram with ChatGPT by providing a prompt describing the interactions you want to represent.

Example Prompt:

Generate a PlantUML sequence diagram with participants ‘User’, ‘Server’, and ‘Database’. The ‘User’ sends a request to the ‘Server’, which queries the ‘Database’ and returns the result to the ‘User’.

ChatGPT Output:

@startuml
participant User
participant Server
participant Database

User -> Server: Request
Server -> Database: Query
Database --> Server: Result
Server --> User: Response
@enduml

And rendered as image:

Activity Diagrams:

Activity diagrams are used to represent the flow of actions and decisions within a system. They are useful for visualizing complex processes and workflows. To generate an activity diagram with ChatGPT, provide a prompt that describes the flow of actions and decisions in your system.

Example Prompt:

Generate a PlantUML activity diagram representing a simple login process. The process starts with ‘Enter Credentials’, followed by a decision to check if the credentials are valid. If valid, it proceeds to ‘Login Successful’, otherwise, it goes to ‘Show Error Message’ and loops back to ‘Enter Credentials’.

ChatGPT Output:

@startuml
start
:Enter Credentials;
if (Credentials are valid) then (yes)
:Login Successful;
stop
else (no)
:Show Error Message;
endif
-> Enter Credentials;
@enduml

Which visually looks as follows:

Generating diagrams from code

Using ChatGPT to create diagrams using code as input offers a powerful way to visualize the structure and logic of software systems or data models. By interpreting and transforming code snippets into graphical representations, ChatGPT allows developers to more easily communicate a business process to business experts. Furthermore, the ability to generate diagrams directly from code ensures a higher level of consistency between the codebase and the visual representation, while also streamlining the process of keeping diagrams up to date as the code evolves.

As long as you trust ChatGPT to understand your code correctly, of course.

Consider the below Python code. This contains functionality to create a user account, perform database queries, and update the user account status upon too many failed OTP attempts.

import sqlite3

def create_user_table():
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, username TEXT UNIQUE, password TEXT, active INTEGER, failed_attempts INTEGER)''')
conn.commit()
conn.close()

def create_user(username, password):
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("INSERT INTO users (username, password, active, failed_attempts) VALUES (?, ?, 1, 0)", (username, password))
conn.commit()
conn.close()

def find_user_by_username(username):
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("SELECT * FROM users WHERE username=?", (username,))
user = c.fetchone()
conn.close()
return user

def verify_password(user, password):
return user[2] == password

def is_active(user):
return user[3] == 1

def update_failed_attempts(user):
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("UPDATE users SET failed_attempts=? WHERE id=?", (user[4] + 1, user[0]))
conn.commit()
conn.close()

def lock_account(user):
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("UPDATE users SET active=0 WHERE id=?", (user[0],))
conn.commit()
conn.close()

def authenticate(username, password):
user = find_user_by_username(username)

if user is None:
return 'User not found'

if not verify_password(user, password):
return 'Invalid password'

if not is_active(user):
return 'User account is inactive'

login_attempts = 0
while login_attempts < 3:
otp = generate_otp()
send_otp(user, otp)
entered_otp = input("Enter the OTP: ")

if entered_otp == otp:
return 'Authenticated'
else:
login_attempts += 1
update_failed_attempts(user)
if login_attempts == 3:
lock_account(user)
return 'Max OTP attempts reached'

return 'Error'

Example prompt:

Generate a PlantUML activity diagram based on the following complex Python code snippet with database interaction: (include the Python code snippet from above)

ChatGPT output:

Admittedly, this diagram is still quite low level, and not so easy to read. But we can fix that. Remember, with ChatGPT, iteration is your friend. Additional prompt:

Make the PlantUML diagram a bit more higher level, to show the concepts instead of going through the code line by line

And result:

This makes the flow of an application readable for a non-programmer, bridging the gap from developer to business expert more efficiently.

Diagram of a Kubernetes cluster

In this example, we will explore how you can use ChatGPT to generate a PlantUML deployment diagram based on a Kubernetes cluster configuration. To achieve this, provide a brief description of the Kubernetes cluster components to ChatGPT and request the generation of a corresponding deployment diagram.

Example Kubernetes cluster description:

We have a Kubernetes cluster consisting of two nodes: Node1 and Node2. There are three pods running on the cluster: Pod1, Pod2, and Pod3. Pod1 and Pod2 are running on Node1, while Pod3 runs on Node2. Pod1 contains two containers: Container1A and Container1B. Pod2 has one container: Container2. Pod3 has one container: Container3.

Example Prompt:

Generate a PlantUML deployment diagram based on the following Kubernetes cluster description: (include the Kubernetes cluster description from above)

ChatGPT Output:

@startuml
!define AWSPUML https://raw.githubusercontent.com/awslabs/aws-icons-for-plantuml/v15.0.0/AdvancedUseCase/AWSCommon.puml
!includeurl AWSPUML

actor Node1
actor Node2

artifact Pod1 {
component [Container1A]
component [Container1B]
}

artifact Pod2 {
component [Container2]
}

artifact Pod3 {
component [Container3]
}

Node1 -- Pod1
Node1 -- Pod2
Node2 -- Pod3
@enduml

Unfortunately the above output cannot be parsed, because the mentioned URL is not available. A simple prompt can resolve this issue:

It says cannot open url for AWSPUML

This then results in the below image:

Press enter or click to view image in full size

I am sure that including the right icons and such for Kubernetes will improve this diagram. I asked ChatGPT to revise his answer but unfortunately he just provided another invalid URL.

Diagram of a live Kubernetes cluster

Manually describing the cluster would become tiresome fast. To create a prompt containing the cluster description from an actual Kubernetes cluster, you can use the kubectl command-line tool to query the cluster for the required information. Once you have this information, you can create a string that describes the cluster and use it as input for ChatGPT.

Below is a sample Python script that uses the subprocess module to run kubectl commands and collect the required information. The script then constructs a cluster description string and prompt for ChatGPT. The script is limited to nodes, pods and containers and would of course need expansion to include the full view of a Kubernetes cluster, but it provides the basic idea.

import subprocess

def get_nodes():
output = subprocess.check_output(["kubectl", "get", "nodes", "-o", "jsonpath='{.items[*].metadata.name}'"])
return output.decode('utf-8').strip("'").split(' ')

def get_pods(namespace):
output = subprocess.check_output(["kubectl", "get", "pods", "-n", namespace, "-o", "jsonpath='{.items[*].metadata.name}'"])
return output.decode('utf-8').strip("'").split(' ')

def get_namespaces():
output = subprocess.check_output(["kubectl", "get", "namespaces", "-o", "jsonpath='{.items[*].metadata.name}'"])
return output.decode('utf-8').strip("'").split(' ')

def get_containers(pod_name, namespace):
output = subprocess.check_output(["kubectl", "get", "pod", pod_name, "-n", namespace, "-o", "jsonpath='{.spec.containers[*].name}'"])
return output.decode('utf-8').strip("'").split(' ')

def get_cluster_description():
nodes = get_nodes()
namespaces = get_namespaces()
description = f"We have a Kubernetes cluster consisting of {len(nodes)} nodes: {', '.join(nodes)}."

pod_descriptions = []
for namespace in namespaces:
pods = get_pods(namespace)
for pod in pods:
if pod: # Ensure pod name is not empty
containers = get_containers(pod, namespace)
pod_description = f"{pod} in namespace {namespace} contains {len(containers)} containers: {', '.join(containers)}."
pod_descriptions.append(pod_description)

description += f" There are {len(pod_descriptions)} pods running on the cluster: {', '.join(pod_descriptions)}"
return description

cluster_description = get_cluster_description()
chatgpt_prompt = f"Generate a PlantUML deployment diagram based on the following Kubernetes cluster description: {cluster_description}"
print(chatgpt_prompt)

The script assumes that you have kubectl configured on your system and are authenticated with the Kubernetes cluster.

Once you have the chatgpt_prompt string, you can use it as input to ChatGPT to generate a PlantUML deployment diagram based on the actual Kubernetes cluster. Example Prompt:

Generate a PlantUML deployment diagram based on the following Kubernetes cluster description: (include the cluster description string)

The above script is just to show the basic idea. I ran it on a decently large cluster and it definitely gave output which was usable (after removing the invalid URLs) on ChatGPT 4, but ChatGPT 3.5 didn’t even try. Regardless, I can imagine you might hit the max input or answer limit of ChatGPT quite quickly, at which point you are probably better off to generate a PlantUML specification directly instead of going through ChatGPT. But your mileage may vary.

Conclusion

This article has demonstrated the power of ChatGPT in generating a wide range of PlantUML diagrams based on various types of input, such as plain text descriptions, code snippets, and Kubernetes cluster specifications. By iteratively refining the results, you can obtain accurate and meaningful visual representations of your concepts or systems. Using ChatGPT to create diagrams from code or other structured inputs can significantly streamline your documentation process and save you time, making it a valuable tool for software developers, engineers, and other professionals who frequently work with diagrams