How to Visualise Code With GPT API

In this guide, you'll be given a bash script to visualise a codeblock using ChatGPT/GPT-4 API


May 6, 2023 671 Words

Read Time: 4 Minutes

A screenshot of the bash script to visualise code using chatGPT/GPT-4 API

Getting started:

A few points to keep in mind:

  1. Prompt outputs aren’t deterministic 1 – “…given a particular input, ChatGPT not produce the same output everytime”,

  2. Outputs often have syntax errors even with GPT-4. A little bit of mermaid syntax 2 knowledge is required of fix incorrect syntaxes,

  3. You can change the model to gpt-4 in the bash script (if you’re fine with higher billing)

  4. Be aware that, OpenAI will charge you πŸ’΅ everytime you prompt it using this script.

Setup & Requirments

🧠 I’ve built this on the macOS and I’ve written this guide for linux based operating system

Install jq using Home Brew

brew install jq

Generate OpenAPI Key

  • Go to the OpenAI website and signup if you don’t already have an account
  • From the OpenAI dashboard, click the “API keys” link in the top menu
  • Click the “Create” button to generate your API key and copy it
  • Store key in an environment variable called OPENAI_API_KEY for use while running bash script later

Get Bash Script


# Replace double quotes with Unicode character
function replace_double_quotes {
  echo "${1//\"/\u201C}"

# Replace single quotes with Unicode character
function replace_single_quotes {
  echo "${1//\'/\u2018}"

echo "Enter your multiline input. Type END to finish:"
while IFS= read -r line; do
    if [ "$line" = "END" ]; then

# Read the API key from an environment variable

echo "With breaks $STRING_WITH_BREAKS \n"

CUSTOM_PROMPT="You're an Expert Mermaid Markdown Writer and Code Analyser.

I'll provide a function and you're duty is to return a mermaid mardown flow chat for the function.

The mermaid diagram flowchart should explain the following:
1. Entry points to the code segment
2. All the possible flows and outcomes
3. How the Caller/Called stack interact with each other

You'll have to follow the below rules as well.

1. The syntax has to be syntactically correct
3. Basic Mermaid Processors like github or vscode should be able to parse it
4. Don't use fancy language
5. Keep it super simple
6. Nested parentheses should be written as follows:
   Example: If the syntax is like (x(x)x), replace with ['x(x)x'] format. don't forget to enclose
   all labels inside [] with single quotes.
7. Double Worded Nodes should be separated by underscore

It's very important that you follow these rules. 
Before providing output, please verify and provide the output based on above rules.

Explain each function in detail.


    participant Alice
    participant Bob
    Alice->>John: Hello John, how are you?
    loop Healthcheck
        John->>John: Fight against hypochondria
    Note right of John: Rational thoughts<br/>prevail...
    John-->>Alice: Great!
    John->>Bob: How about you?
    Bob-->>John: Jolly good!

Enclose all labels and annotations in Double Quotes.

The code block is as follows:"


# Solves convoluted escape issues:  spent 2 hours on this problem :(
STRING_NO_BREAKS=$(replace_double_quotes "$(replace_single_quotes "$STRING_NO_BREAKS")")

echo "No breaks $STRING_NO_BREAKS \n"

# URL Encode the string

STRING_URL_ENCODE=$(echo "$STRING_NO_BREAKS" | jq -sRr @uri)

echo "Url encode $STRING_URL_ENCODE \n"

if [ -z "$API_KEY" ]; then
  echo "ERROR: OPENAI_API_KEY environment variable is not set"
  exit 1

# Call the ChatGPT API to generate a commit message based on the diff
CURL_COMMAND="curl --location '' \
 --header 'Content-Type: application/json' \
 --header 'Authorization: Bearer $API_KEY' \
 --data-raw '{\"model\": \"gpt-3.5-turbo\", \"messages\": [{\"role\": \"user\", \"content\": \"$STRING_URL_ENCODE\" }]}'"

echo "Curl command is $CURL_COMMAND"

MSG=$(eval "$CURL_COMMAND" | jq -r ".choices[].message.content")

echo "Message: \n $MSG"

# Remove parentheses
# MSG=${MSG//[\(\)]/}

# Remove double quotes
# MSG=${MSG//\"/}

echo "$MSG" >

How to Run?

  1. Copy and paste the above bash code into a file, let’s call it for example

  2. Save the file

  3. Set the OPENAI_API_KEY environment variable from your terminal and ensure it contains the secret key. You can verify this using this command:

        echo $OPENAI_API_KEY
  4. Run the bash script using the following command in your bash terminal:

  5. Enter a piece of code you want to visualise and type END and click enter in the terminal

    A screenshot of adding a code block
    The script will create a file called
  6. Open and copy the code that looks like this,

        // ... 
            graph LR
                A[summarize_text] --> B{is text empty?}
                B -- Yes --> C[Error: No text to summarize]
                B -- No --> D[Print text length]
                D --> E{is website flag enabled?}
                E -- Yes --> F{Send message to OpenAI API}
                F --> G[Get summarized text from OpenAI API]
                G --> H[Append summarized text to summaries list]
                H -- Iterate over chunks --> A
                E -- No --> I{Send message to OpenAI API}
                I --> J[Get summarized text from OpenAI API]
                J --> K[Append summarized text to summaries list]
                K -- Summarize all chunks --> L[Combine all summaries]
                L -- Send combined summary to OpenAI API --> M[Get final summary from OpenAI API]
                M --> N[Return final summary]
        // ...
  7. Open the website and paste it to visualise the code

Mermaid Markdown Visualiser
You can also visualise it on GitHub or using the VSCode preview feature.

If you have any additional queries, hit me up on twitter.

πŸ‘‹ – @TnvMadhav