code: def display_messages(
      msgs: List[Dict[str, Any]],
      prettify: bool = False,
      ignore_agent_reply: bool = False,
      add_fields: str = "",
      max_len: int = 1000,
      verbose: bool = False,
  ) -> Optional[str]:
      """
      Return a string describing the set of messages provided.
  
      If prettify is true, candidates are displayed using prettytable. add_fields provides
      a list of fields in the msgs which should be displayed if verbose is off.
      """
  
      def _token_losses_line(
          msg: Dict[str, Any], fields_to_show: List[str], space: str
      ) -> Optional[str]:
          """
          Displays the loss associated with each token. Can be used for debugging
          generative models.
  
          See TorchGeneratorAgent._construct_token_losses for an example implementation.
          """
          key = "token_losses"
          token_losses = msg.get(key, None)
          if key not in fields_to_show or not token_losses:
              return None
          # Reduce losses to 4 significant figures
          formatted_tl = " | ".join(
              [
                  f"{tl[0]} {float('{:.4g}'.format(tl[1]))}"
                  for tl in token_losses
              ]
          )
          return _pretty_lines(space, key, formatted_tl, "text2")
  
      def _pretty_lines(indent_space, field, value, style):
          line = "{}{} {}".format(
              indent_space,
              colorize("[" + field + "]:", "field"),
              colorize(value, style),
          )
          return line
  
      lines = []
      episode_done = False
      extra_add_fields_ = add_fields.split(",")
      for index, msg in enumerate(msgs):
          if msg is None or (index == 1 and ignore_agent_reply):
              # We only display the first agent (typically the teacher) if we
              # are ignoring the agent reply.
              continue
  
          if msg.get("episode_done"):
              episode_done = True
          # Possibly indent the text (for the second speaker, if two).
          space = ""
          if len(msgs) == 2 and index == 1:
              space = "   "
  
          agent_id = msg.get("id", "[no id field]")
          if verbose:
              line = _pretty_lines(
                  indent_space=space,
                  field="id",
                  value=agent_id,
                  style="id",
              )
              lines.append(line)
  
          # Only display rewards !=0 as they are confusing in non-RL tasks.
          if msg.get("reward", 0) != 0:
              lines.append(
                  space + "[reward: {r}]".format(r=msg["reward"])
              )
  
          fields_to_show = []
          if verbose:
              fields_to_show = [field for field in msg]
          else:
              fields_to_show = [
                  field
                  for field in msg
                  if field
                  in list(MUST_SHOW_MESSAGE_FIELDS) + extra_add_fields_
              ]
          fields_to_show.sort()
  
          # Display fields without special format
          for field in fields_to_show:
              if field not in SPECIAL_FORMATED_DISPLAY_MESSAGE_FIELDS:
                  if type(msg[field]) is list:
                      value = _ellipse(msg[field], sep="\n  ")
                  else:
                      value = clip_text(str(msg.get(field)), max_len)
                  line = _pretty_lines(
                      indent_space=space,
                      field=field,
                      value=value,
                      style="text2",
                  )
                  lines.append(line)
  
          # Display fields WITH special format requirements
          # Display Image
          if type(msg.get("image")) in [str, torch.Tensor]:
              lines.append(f'[ image ]: {msg["image"]}')
          # Display Text
          if msg.get("text", ""):
              value = clip_text(msg["text"], max_len)
              style = "bold_text" if index == 0 else "labels"
              field = "text" if verbose else agent_id
              line = _pretty_lines(
                  indent_space=space,
                  field=field,
                  value=value,
                  style=style,
              )
              lines.append(line)
          # Display Label Fields
          for field in {
              "labels",
              "eval_labels",
              "label_candidates",
              "text_candidates",
          }:
              if msg.get(field) and field in fields_to_show:
                  line = _pretty_lines(
                      indent_space=space,
                      field=field,
                      value=_ellipse(msg[field]),
                      style=field,
                  )
                  lines.append(line)
          if msg.get("metrics") and verbose:
              lines.append(
                  _pretty_lines(
                      indent_space=space,
                      field="metrics",
                      value="\n" + nice_report(msg["metrics"]),
                      style="text",
                  )
              )
  
          # Handling this separately since we need to clean up the raw output before displaying.
          token_loss_line = _token_losses_line(
              msg, fields_to_show, space
          )
          if token_loss_line:
              lines.append(token_loss_line)
  
      if episode_done:
          lines.append(
              colorize(
                  "- - - - - - - END OF EPISODE - - - - - - - - - -",
                  "highlight",
              )
          )
  
      return "\n".join(lines)
  
imports: from collections import deque, OrderedDict
  from typing import Union, Optional, Set, Any, Dict, List, Tuple
  from datetime import timedelta
  import functools
  import math
  import time
  import re
  import shutil
  import json
  import os
  from parlai.core.message import Message
  from parlai.utils.strings import colorize
  from parlai.utils.io import PathManager
  import parlai.utils.logging
label_desc: Use image node_id 10 for calling a global function with example usage: display_messages(msgs, prettify, ignore_agent_reply, add_fields, max_len, verbose) and returns: str, _pretty_lines, line, None