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

Share:

May 6, 2023 672 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 will 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

#!/bin/bash

# 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
        break
    fi
    STRING_WITH_BREAKS+="$line"$'\n'
done

# Read the API key from an environment variable
API_KEY=$OPENAI_API_KEY

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.

Example:

sequenceDiagram
    participant Alice
    participant Bob
    Alice->>John: Hello John, how are you?
    loop Healthcheck
        John->>John: Fight against hypochondria
    end
    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:"

STRING_NO_BREAKS=$( echo "$CUSTOM_PROMPT $STRING_WITH_BREAKS" | tr -d '\n')

# 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
fi

# Call the ChatGPT API to generate a commit message based on the diff
CURL_COMMAND="curl --location 'https://api.openai.com/v1/chat/completions' \
 --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" > output.md

How to Run?

  1. Copy and paste the above bash code into a file, let’s call it code_wiz.sh 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:

        sh code_wiz.sh
    
  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 output.md
  6. Open output.md and copy the code that looks like this,

        // ... 
        ```mermaid
            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 https://mermaid.live/ 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

Reference

Find more posts from following topics

2024
accurate-requests
api-development
api-testing
api-testing-tools
array
automated-testing
bad-habits
base64-decoder
base64-encoder
binding
biography
blog
blogging
books
browser
bulma-css
bulma.io
button-swiftui
chatgpt
chrome
clipboard
code
code-block
code-navigation
code-snippet
codecoverage
comparison
compile
configuring-debugger-for-django-in-vs-code
configuring-launch.json-for-python-debugger
copy
copy-to-clipboard
copy-to-clipboard-neovim
css
current-date
current-time
current-timestamp
debugger-setup-in-visual-studio-code
debugging-django-app-in-visual-studio-code
debugging-python-code-in-visual-studio-code
debugging-python-programs-with-visual-studio-code
debugging-python-with-virtual-environment-in-vs-code
developer-productivity
developers
development-workflow
dom
dynamic-sitemap-in-nextjs
engineering-dashboard
enumerate
flowcharts
generics
git
git-diff
github
global-keyboard-shorcut
global-shortcut
go
go-hugo
go-programming
go-test
go-to-line
go-tool
go1.18
golang
golang-development
good-habits
gorilla-websocket
gpt
gpt-3.5
gpt-4
gpt-4-api
guide
gumroad
habits
habits-tracker-notion-template
hamburger-menu
hotkeys
html
hugo
ide
image
image-sharing
image-tool-for-ios
imagerenderer
include-timestamp
integrated-development-environment
ios
ios-16
ios16
javascript
jump-to-definition
keyboard-shortcut
leonardo-da-vinci
linux
ls
lsp
macos
map
markdown
markdown-code
mental-programming
menu
menubarextra
mergesort
mermaid-syntax
mistake-tracker-notion
mobile-view
modifier
modulo-operation
navbar
navigationlink
navigationstack
neovim
next.js
nextjs
nextjs-markdown
nextjs-sitemap
nextjs-sitemaps
nice-shot
nice-shot-pro
notion
notion-api
notion-api-python
notion-budget
notion-budget-template
notion-budget-tracker
notion-bug-report-tracker
notion-dashboard
notion-expense-manager
notion-habits
notion-habits-dashboard
notion-habits-template
notion-habits-tracker
notion-habits-tracker-template
notion-issue-tracker
notion-mistake-tracker
notion-product
notion-product-dashboard
notion-product-roadmap
notion-product-roadmap-dashboard
notion-tasks
notion-tasks-dashboard
notion-tasks-template
notion-tasks-tracker
notion-template
notionworkspaces
openai
osx
personal-ifttt-framework
photospicker
photospickeritem
phpickerfilter
postman-capabilities
postman-request
pre-request-script
product-roadmap-notion-template
product-roadmap-template
productivity
programming
python
python-api
python-debugger-tutorial-for-vs-code
python-debugging-mode-in-vs-code
python-notion-api
python3
reading
real-time-communication
rehype
remark
request-data
running-debugger-in-visual-studio-code
running-django-app-in-debugging-mode
running-program-in-debugging-mode-in-vs-code
running-python-code-in-debugging-mode
safari
screenshot-app-for-ios
screenshot-app-ios
screenshot-ios
screenshot-tool-for-ios
set-current-timestamp
setting-up-debugger-in-vs-code-for-python
share-extension
sharelink
sharepreview
sharesheet
simple-websocket-server
sitemap
slice
slices
slider
sort
sorting
space-complexity
step-by-step-guide
stocks-profits-tracker
stocks-profits-tracker-template
stocks-tracker
struct
sustained-vigilance
swift
swiftui
swiftui-button
swiftui-button-action
swiftui-button-style
table-of-contents
tasks-tracker-notion-template
test
testing
textfield-swiftui
til
tim-sort
time-complexity
timeliness
timestamp-integration
timsort
transferable
triggers-and-actions
tutorial
unittest
unix
us-stocks
usa-stocks
useful-ios-features
using-breakpoints-in-python-debugger
using-virtual-environment-with-python-debugger
vanilla-javascript
variable
vim
visual-mode
visual-studio-code
vs-code
vscode
vscode-go-to-line
walter-isaacson
web-sockets-in-go
websocket-client
websocket-programming
websocket-server
xcode
xss