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
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
Features: - โ Native widget display - โ Interactive controls - โ Collapsible sections - โ Rich markdown - โ Inline rendering
JSON Modeยถ
Best for: APIs, logging, metadata
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
Issue: Plotly chart too largeยถ
Solution: Use CDN instead of embedding
Issue: DataFrame truncatedยถ
Solution: Increase max rows
Issue: Images not loading in embedded HTMLยถ
Solution: Ensure resources are embedded
๐ฎ 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ยถ
- Let agent return visualization objects directly
- Use auto-detection - let formatter figure out the type
- Embed resources for portability when creating standalone files
- Use appropriate modes for each environment
- Cache generated HTML for repeated queries
โ DON'Tยถ
- Don't convert to string before formatting
- Don't manually detect types - let the formatter do it
- Don't mix output modes inconsistently
- Don't ignore performance with large visualizations
- 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! ๐