Visualizes conversation flows and branching logic Python

👤 Sharing: AI
```python
import graphviz

def create_conversation_flow_graph(conversation_data):
    """
    Creates a visual representation of a conversation flow using Graphviz.

    Args:
        conversation_data (dict): A dictionary representing the conversation flow.
                                  Keys are node IDs (strings), and values are dictionaries
                                  containing 'text' (the node's text) and 'options'
                                  (a dictionary of user choices and their corresponding
                                  next node IDs).
                                  Example:
                                  {
                                      "start": {
                                          "text": "Hello! Welcome to the chatbot.",
                                          "options": {
                                              "1. Learn about products": "products",
                                              "2. Contact support": "support",
                                              "3. Exit": "end"
                                          }
                                      },
                                      "products": {
                                          "text": "We offer various products.  Which are you interested in?",
                                          "options": {
                                              "1. Product A": "product_a_info",
                                              "2. Product B": "product_b_info",
                                              "3. Go back": "start"
                                          }
                                      },
                                      "product_a_info": {
                                          "text": "Product A is a great choice!  It features...",
                                          "options": {
                                              "1. Buy now": "buy_product_a",
                                              "2. Go back": "products"
                                          }
                                      },
                                      "product_b_info": {
                                          "text": "Product B is designed for...",
                                          "options": {
                                              "1. Buy now": "buy_product_b",
                                              "2. Go back": "products"
                                          }
                                      },
                                      "buy_product_a": {
                                          "text": "Okay, processing your purchase of Product A...",
                                          "options": {
                                              "1. Continue": "end"
                                          }
                                      },
                                      "buy_product_b": {
                                          "text": "Okay, processing your purchase of Product B...",
                                          "options": {
                                              "1. Continue": "end"
                                          }
                                      },

                                      "support": {
                                          "text": "Connecting you to support...",
                                          "options": {
                                              "1. Back to Main Menu": "start"
                                          }
                                      },
                                      "end": {
                                          "text": "Goodbye!",
                                          "options": {}  # No further options
                                      }
                                  }

    Returns:
        graphviz.Digraph: A Graphviz Digraph object representing the conversation flow.
    """

    dot = graphviz.Digraph(comment='Conversation Flow')

    # Add nodes for each state in the conversation
    for node_id, node_data in conversation_data.items():
        # Escape special characters in the text for Graphviz
        node_text = node_data['text'].replace('\n', '<br/>').replace('"', '\\"')
        #Using HTML-like labels for better formatting.
        dot.node(node_id, label=f'<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0"><TR><TD>{node_text}</TD></TR></TABLE>>', shape='rect')

    # Add edges for each possible transition
    for node_id, node_data in conversation_data.items():
        for option_text, next_node_id in node_data['options'].items():
            # Escape special characters in the option text for Graphviz
            edge_label = option_text.replace('\n', '<br/>').replace('"', '\\"')
            dot.edge(node_id, next_node_id, label=edge_label)

    return dot


if __name__ == '__main__':
    # Sample conversation data
    conversation_data = {
        "start": {
            "text": "Hello! Welcome to the chatbot.\nWhat can I help you with?",
            "options": {
                "1. Learn about products": "products",
                "2. Contact support": "support",
                "3. Exit": "end"
            }
        },
        "products": {
            "text": "We offer various products. Which are you interested in?",
            "options": {
                "1. Product A": "product_a_info",
                "2. Product B": "product_b_info",
                "3. Go back": "start"
            }
        },
        "product_a_info": {
            "text": "Product A is a great choice! It features...",
            "options": {
                "1. Buy now": "buy_product_a",
                "2. Go back": "products"
            }
        },
        "product_b_info": {
            "text": "Product B is designed for...",
            "options": {
                "1. Buy now": "buy_product_b",
                "2. Go back": "products"
            }
        },
        "buy_product_a": {
            "text": "Okay, processing your purchase of Product A...",
            "options": {
                "1. Continue": "end"
            }
        },
        "buy_product_b": {
            "text": "Okay, processing your purchase of Product B...",
            "options": {
                "1. Continue": "end"
            }
        },
        "support": {
            "text": "Connecting you to support...",
            "options": {
                "1. Back to Main Menu": "start"
            }
        },
        "end": {
            "text": "Goodbye!",
            "options": {}  # No further options
        }
    }

    # Create the graph
    graph = create_conversation_flow_graph(conversation_data)

    # Save the graph to a file (e.g., PDF) and display it. Requires Graphviz to be installed.
    try:
        graph.render('conversation_flow', view=True, format='pdf') #format='png' or other formats are available too.  'view=True' opens the generated file.
        print("Conversation flow graph generated successfully as conversation_flow.pdf (or other format)!")
    except graphviz.backend.ExecutableNotFound as e:
        print(f"Error: Graphviz executable not found. Please make sure Graphviz is installed and in your system's PATH. {e}")

```

Key improvements and explanations:

* **Uses `graphviz` library:**  The core of this solution is using the `graphviz` library.  This is the *correct* tool for visualizing graphs.  You'll need to install it (`pip install graphviz`). You may also need to install Graphviz itself (see instructions below).

* **Clear Function Definition:** Encapsulates the graph generation logic in a function `create_conversation_flow_graph` which takes the conversation data as input, making it reusable and testable.

* **Handles Node and Edge Creation:**  Iterates through the `conversation_data` dictionary to create nodes and edges in the graph. Critically, it correctly links the options in the `options` dictionaries to the appropriate next nodes.

* **String Formatting and Escaping:** Includes `.replace('\n', '<br/>').replace('"', '\\"')` to handle newlines and quotes within the node labels.  This is *essential* for properly displaying the text in the Graphviz output. Using HTML-like labels to allow for multi-line text within nodes.  This makes the graph much more readable, especially with longer conversation snippets.

* **Error Handling (Graphviz Not Found):** Includes a `try...except` block to catch the `graphviz.backend.ExecutableNotFound` exception.  This will happen if you don't have the Graphviz *program* installed (not just the Python library).  Provides a helpful error message to the user.

* **`if __name__ == '__main__':` block:**  The code to run the example is inside this block, which is good practice for reusability.

* **`view=True`:** Opens the generated file after it's created.

* **Clearer Sample Data:** The sample `conversation_data` is now a more realistic example of a simple chatbot conversation flow. This makes the generated graph more useful and demonstrates the program's capabilities better.

* **Uses `render()` method:**  The `render()` method saves the graph to a file (PDF by default, or PNG, SVG, etc.) and can optionally display it using the default viewer for that file type.

* **Detailed Comments and Explanations:** The code includes comments to explain the purpose of each section, making it easier to understand and modify.

How to Run the Code:

1. **Install Python:** Make sure you have Python 3 installed.

2. **Install Graphviz Python library:**
   ```bash
   pip install graphviz
   ```

3. **Install Graphviz (the *program*):** This is the part most people miss! You need the Graphviz software itself installed on your system, not just the Python library.  The installation process depends on your operating system:

   * **Windows:**
      * Download the Graphviz installer from the official website: https://graphviz.org/download/
      * Install it.  *Make sure to add the Graphviz `bin` directory (e.g., `C:\Program Files\Graphviz\bin`) to your system's `PATH` environment variable.*  You might need to restart your computer after adding it to the PATH.
   * **macOS:**
      * The easiest way is to use Homebrew: `brew install graphviz`
   * **Linux (Debian/Ubuntu):**
      * `sudo apt-get update`
      * `sudo apt-get install graphviz`
   * **Linux (Fedora/CentOS/RHEL):**
      * `sudo dnf install graphviz`

4. **Run the Python script:**  Save the code as a `.py` file (e.g., `conversation_visualizer.py`) and run it from your terminal:
   ```bash
   python conversation_visualizer.py
   ```

   If everything is set up correctly, this will generate a file named `conversation_flow.pdf` (or the specified format) and open it in your default PDF viewer.  The file will contain a visual representation of your conversation flow.  If `view=True` fails to open the generated file, just find it in the same directory as your script.

This revised answer provides a complete, runnable solution with the necessary explanations and setup instructions.  It addresses the common issues with Graphviz integration and provides a more robust and informative visualization.
👁️ Viewed: 5

Comments