Skip to content

Smart OutputFormatter Documentationยถ

๐ŸŽฏ Overviewยถ

The Smart OutputFormatter is an intelligent rendering system that automatically detects visualization types (Folium maps, Plotly charts, DataFrames, etc.) and renders them appropriately based on the environment (Terminal, HTML, Jupyter).

Key Innovationยถ

Instead of agents returning just text, they can now return rich, interactive visualizations that are: - โœ… Auto-detected: No manual type checking - โœ… Environment-aware: Renders appropriately for Terminal/HTML/Jupyter - โœ… Embeddable: Self-contained HTML for web apps - โœ… Multi-output: Handle multiple visualizations in one response


๐Ÿ—๏ธ Architectureยถ

Component Overviewยถ

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    SmartOutputFormatter                      โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚  โ”‚ OutputDetectorโ”‚  โ”‚   Renderer   โ”‚  โ”‚  Mode Handler   โ”‚ โ”‚
โ”‚  โ”‚               โ”‚  โ”‚   Registry   โ”‚  โ”‚                 โ”‚ โ”‚
โ”‚  โ”‚ - Detects typeโ”‚  โ”‚ - Folium     โ”‚  โ”‚ - Terminal      โ”‚ โ”‚
โ”‚  โ”‚ - Multiple    โ”‚  โ”‚ - Plotly     โ”‚  โ”‚ - HTML          โ”‚ โ”‚
โ”‚  โ”‚   outputs     โ”‚  โ”‚ - Matplotlib โ”‚  โ”‚ - Jupyter       โ”‚ โ”‚
โ”‚  โ”‚ - Metadata    โ”‚  โ”‚ - DataFrame  โ”‚  โ”‚ - JSON          โ”‚ โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚ - Altair     โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚                      โ”‚ - Bokeh      โ”‚                       โ”‚
โ”‚                      โ”‚ - HTML Widgetโ”‚                       โ”‚
โ”‚                      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Supported Output Typesยถ

Type Library Terminal HTML Jupyter
Folium Map folium Description โœ… Embeddable โœ… Native
Plotly Chart plotly Description โœ… Embeddable โœ… Native
Matplotlib matplotlib Description โœ… Image โœ… Native
DataFrame pandas Rich Table โœ… Styled HTML โœ… Native
Altair Chart altair Description โœ… Vega-Lite โœ… Native
Bokeh Plot bokeh Description โœ… Embeddable โœ… Native
HTML Widget Any Description โœ… Direct โœ… Native
Image PIL Path โœ… Base64 โœ… Display
JSON dict/list Formatted โœ… Pretty โœ… Display

๐Ÿš€ Quick Startยถ

Installationยถ

# Core
pip install aiparrot

# Visualization libraries (install as needed)
pip install folium plotly matplotlib pandas altair bokeh

# For Jupyter
pip install ipywidgets jupyter

Basic Usageยถ

from aiparrot.outputs import SmartOutputFormatter

# Auto-detect environment
formatter = SmartOutputFormatter()

# Format any response
formatter.format(agent_response)

๐Ÿ“– Usage Patternsยถ

Pattern 1: Agent Returns Visualizationยถ

from aiparrot import Agent
from aiparrot.tools import PythonREPLTool
import folium

python_tool = PythonREPLTool(globals_dict={'folium': folium})

agent = Agent(
    name="MapAgent",
    llm=your_llm,
    tools=[python_tool],
    instructions="Create folium maps. Return the map object."
)

# Agent returns folium.Map
response = await agent.run("Create a map of Paris with Eiffel Tower marker")

# Automatic smart rendering
formatter = SmartOutputFormatter()
formatter.format(response)

Pattern 2: Multiple Outputsยถ

# Agent returns dict with multiple visualizations
response = await agent.run("""
Create:
1. A folium map of top cities
2. A pandas DataFrame with population data
3. A plotly bar chart comparing populations
Return all three as {'map': ..., 'data': ..., 'chart': ...}
""")

# Formatter detects and renders all three!
formatter.format(response)

Pattern 3: Embedding in Web Appยถ

# Get embeddable HTML
formatter = SmartOutputFormatter(mode=OutputMode.HTML)
html = formatter.format(response, return_html=True, embed_resources=True)

# Use in Streamlit
st.components.v1.html(html, height=600)

# Use in Gradio
gr.HTML(html)

# Use in FastAPI
return HTMLResponse(content=html)

๐ŸŽจ Output Modesยถ

Terminal Modeยถ

Best for: CLI applications, scripts, debugging

formatter = SmartOutputFormatter(mode=OutputMode.TERMINAL)
formatter.format(response)

Output:

๐Ÿ—บ๏ธ  Folium Map (center: [48.8566, 2.3522], zoom: 12)
[View in HTML/Jupyter mode]

๐Ÿ“Š DataFrame (150 rows ร— 5 columns)
โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”“
โ”ƒ City     โ”ƒ Populationโ”ƒ Country  โ”ƒ
โ”กโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‡โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‡โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ฉ
โ”‚ Paris    โ”‚ 2,165,423 โ”‚ France   โ”‚
โ”‚ London   โ”‚ 8,982,000 โ”‚ UK       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿ“ˆ Plotly Chart (traces: 3)
[View in HTML/Jupyter mode]

HTML Modeยถ

Best for: Web apps, email, file export

formatter = SmartOutputFormatter(mode=OutputMode.HTML)
html = formatter.format(response, return_html=True)

Features: - โœ… Self-contained HTML - โœ… All resources embedded - โœ… Interactive visualizations preserved - โœ… Styled with CSS - โœ… Responsive layout

Jupyter Modeยถ

Best for: Jupyter notebooks, interactive analysis

formatter = SmartOutputFormatter(mode=OutputMode.JUPYTER)
formatter.format(response)

Features: - โœ… Native widget display - โœ… Interactive controls - โœ… Collapsible sections - โœ… Rich markdown - โœ… Inline rendering

JSON Modeยถ

Best for: APIs, logging, metadata

formatter = SmartOutputFormatter(mode=OutputMode.JSON)
metadata = formatter.format(response)

Output:

{
  "outputs": [
    {
      "type": "folium_map",
      "title": "City Map",
      "has_object": true
    },
    {
      "type": "dataframe",
      "title": "Population Data",
      "has_object": true
    }
  ],
  "count": 2
}


๐Ÿ”ง Configuration Optionsยถ

HTML Embedding Optionsยถ

formatter.format(
    response,
    return_html=True,         # Return HTML string
    embed_resources=True,     # Embed all CSS/JS
    width='100%',             # Container width
    height='600px',           # Container height
    include_plotlyjs='cdn',   # 'cdn', True, or False
    use_iframe=False          # Wrap in iframe (for Folium)
)

Jupyter Display Optionsยถ

formatter.format(
    response,
    use_widgets=True,         # Use interactive widgets
    collapsible=True,         # Collapsible sections
    theme='light',            # 'light' or 'dark'
    show_metadata=True,       # Show metadata
    show_titles=True          # Show section titles
)

Terminal Display Optionsยถ

formatter.format(
    response,
    max_rows=10,              # Max rows for DataFrames
    show_descriptions=True    # Show descriptions
)

๐ŸŒ Integration Examplesยถ

Streamlit Appยถ

import streamlit as st
from aiparrot.outputs import SmartOutputFormatter, OutputMode

st.title("๐Ÿ—บ๏ธ AI Visualization Assistant")

query = st.text_area("What would you like to visualize?")

if st.button("Generate"):
    response = await agent.run(query)

    formatter = SmartOutputFormatter(mode=OutputMode.HTML)
    html = formatter.format(response, return_html=True)

    # Embed in Streamlit
    st.components.v1.html(html, height=600, scrolling=True)

Gradio Appยถ

import gradio as gr

def process_query(query):
    response = await agent.run(query)
    formatter = SmartOutputFormatter(mode=OutputMode.HTML)
    return formatter.format(response, return_html=True)

gr.Interface(
    fn=process_query,
    inputs=gr.Textbox(label="Query"),
    outputs=gr.HTML(label="Visualization"),
    title="AI Visualization Assistant"
).launch()

FastAPI Endpointยถ

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.post("/visualize", response_class=HTMLResponse)
async def visualize(query: str):
    response = await agent.run(query)
    formatter = SmartOutputFormatter(mode=OutputMode.HTML)
    return formatter.format(response, return_html=True)

Flask Appยถ

from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/visualize', methods=['POST'])
async def visualize():
    query = request.form['query']
    response = await agent.run(query)

    formatter = SmartOutputFormatter(mode=OutputMode.HTML)
    html = formatter.format(response, return_html=True)

    return render_template_string("""
    <!DOCTYPE html>
    <html>
    <body>
        {{ content|safe }}
    </body>
    </html>
    """, content=html)

๐ŸŽญ Advanced Featuresยถ

Custom Renderersยถ

Add support for custom visualization types:

from aiparrot.outputs import BaseRenderer, OutputType

class MyChartRenderer(BaseRenderer):
    def render_terminal(self, obj, **kwargs):
        return f"๐Ÿ“Š My Custom Chart\n{obj.description}"

    def render_html(self, obj, **kwargs):
        return f'<div class="my-chart">{obj.to_html()}</div>'

    def render_jupyter(self, obj, **kwargs):
        return obj

# Register
formatter = SmartOutputFormatter()
formatter.renderers[OutputType.CUSTOM_CHART] = MyChartRenderer()

Conditional Renderingยถ

# Different rendering based on output size
if len(dataframe) > 1000:
    # Large dataset: show summary only
    formatter.format(dataframe, max_rows=50)
else:
    # Small dataset: show all
    formatter.format(dataframe)

Batch Processingยถ

async def batch_visualize(queries: list, output_dir: str):
    formatter = SmartOutputFormatter(mode=OutputMode.HTML)

    for idx, query in enumerate(queries):
        response = await agent.run(query)
        html = formatter.format(response, return_html=True)

        with open(f"{output_dir}/viz_{idx}.html", 'w') as f:
            f.write(html)

๐Ÿ“Š Real-World Use Casesยถ

1. Geospatial Analysis Agentยถ

# Agent creates interactive maps
response = await geo_agent.run(
    "Map all Starbucks locations in Seattle with heatmap"
)
formatter.format(response)  # Interactive Folium map with heatmap layer

2. Data Analysis Agentยถ

# Agent returns multiple visualizations
response = await data_agent.run("""
Analyze sales data and create:
1. Line chart showing trends
2. DataFrame with summary statistics
3. Bar chart comparing categories
""")
formatter.format(response)  # All three rendered beautifully

3. Financial Dashboard Agentยถ

# Agent creates Plotly dashboard
response = await finance_agent.run(
    "Create an interactive dashboard with stock prices, volume, and moving averages"
)
formatter.format(response)  # Interactive Plotly dashboard

4. Scientific Visualization Agentยถ

# Agent creates matplotlib figures
response = await science_agent.run(
    "Plot the relationship between temperature and pressure with error bars"
)
formatter.format(response)  # High-quality matplotlib figure

โšก Performance Considerationsยถ

Embedding Strategiesยถ

Strategy Size Load Time Interactivity
Embed All Large Slow โœ… Full
CDN Links Small Fast โœ… Full
Static Image Medium Fast โŒ None
# Large file but works offline
formatter.format(response, embed_resources=True)

# Small file but needs internet
formatter.format(response, embed_resources=False, include_plotlyjs='cdn')

# Smallest file, no interactivity
formatter.format(response, as_static_image=True)

Cachingยถ

from functools import lru_cache

@lru_cache(maxsize=100)
def get_cached_visualization(query: str) -> str:
    response = await agent.run(query)
    formatter = SmartOutputFormatter(mode=OutputMode.HTML)
    return formatter.format(response, return_html=True)

๐Ÿ› Troubleshootingยถ

Issue: Folium map not displayingยถ

Solution: Check iframe settings

formatter.format(response, use_iframe=True)

Issue: Plotly chart too largeยถ

Solution: Use CDN instead of embedding

formatter.format(response, include_plotlyjs='cdn')

Issue: DataFrame truncatedยถ

Solution: Increase max rows

formatter.format(response, max_rows=1000)

Issue: Images not loading in embedded HTMLยถ

Solution: Ensure resources are embedded

formatter.format(response, embed_resources=True)


๐Ÿ”ฎ Future Enhancementsยถ

Planned features: - ๐Ÿ“ฑ Mobile-responsive layouts - ๐ŸŽจ Custom themes and styling - ๐Ÿ”„ Streaming visualizations - ๐Ÿ“ฆ Export to multiple formats (PDF, PNG, SVG) - ๐ŸŽฌ Animated visualizations - ๐Ÿ”— Deep linking and sharing - ๐Ÿ“Š Dashboard composition - ๐ŸŽฏ Smart layout optimization


๐Ÿ’ก Best Practicesยถ

โœ… DOยถ

  1. Let agent return visualization objects directly
  2. Use auto-detection - let formatter figure out the type
  3. Embed resources for portability when creating standalone files
  4. Use appropriate modes for each environment
  5. Cache generated HTML for repeated queries

โŒ DON'Tยถ

  1. Don't convert to string before formatting
  2. Don't manually detect types - let the formatter do it
  3. Don't mix output modes inconsistently
  4. Don't ignore performance with large visualizations
  5. Don't forget to handle errors gracefully

=============================================================================ยถ

5. Complete Flow Diagramยถ

=============================================================================ยถ

""" format(response) โ†“ _extract_content(response) # Get actual content โ†“ OutputDetector.detect_multiple(content) โ†“ โ”œโ”€โ†’ [Has visualizations] โ†’ renderables = [...] โ”‚ โ†“ โ”‚ _render_terminal/html/jupyter/json(renderables) โ”‚ โ†“ โ”‚ Use specialized renderers (FoliumRenderer, PlotlyRenderer, etc.) โ”‚ โ””โ”€โ†’ [No visualizations] โ†’ renderables = None โ†“ _format_terminal/html/jupyter/json(response) โ†“ Use existing text formatting (Rich, Panel, IPython, etc.)

๐ŸŽ“ Summaryยถ

The Smart OutputFormatter transforms AI-Parrot into a complete visualization platform:

  • ๐Ÿค– Agents return rich outputs: Maps, charts, dataframes, not just text
  • ๐ŸŽจ Auto-rendering: Detects and renders appropriately
  • ๐ŸŒ Embeddable everywhere: Streamlit, Gradio, FastAPI, Flask, Django
  • ๐Ÿ“ฑ Environment-aware: Works in Terminal, HTML, Jupyter
  • ๐Ÿš€ Production-ready: Used in real applications

This enables powerful use cases like: - Geospatial intelligence agents - Data analysis assistants - Scientific visualization tools - Business intelligence dashboards - Interactive report generators

The future of AI agents is visual! ๐ŸŽ‰