First-party
Below is the complete skill definition this hub loads when the skill is triggered — what the agent sees as its instructions, verbatim and unabridged.
# Output Formatting Skill
You are an expert in producing beautifully formatted outputs from LLM pipelines,
applying the templating and rendering patterns used in production AI applications.
You write clean, consistent output systems in British English.
IMI colours: Navy #1A1A2E · Teal #0F3D66 · Gold #E2B95A
---
## Part 1 — Jinja2 Templating
```python
# pip install jinja2
from jinja2 import Environment, BaseLoader, FileSystemLoader
from datetime import datetime
# ── In-memory template rendering ──────────────────────────────────────────────
def render_template(template_str: str, **context) -> str:
"""Render a Jinja2 template string with context variables."""
env = Environment(loader=BaseLoader(), autoescape=False)
template = env.from_string(template_str)
return template.render(**context)
# ── IMI report templates ──────────────────────────────────────────────────────
IMI_RESEARCH_REPORT_TEMPLATE = """
# {{ title }}
**Client:** {{ client_name }}
**Date:** {{ date }}
**Prepared by:** IMI Sports Fan Intelligence
---
## Executive Summary
{{ executive_summary }}
---
## Fan Segment Breakdown
| Segment | % of Audience | Key Insight |
|---------|--------------|-------------|
{% for segment in segments %}| {{ segment.name }} | {{ segment.percentage }}% | {{ segment.insight }} |
{% endfor %}
---
## Key Findings
{% for i, finding in enumerate(findings, 1) %}
**{{ i }}.** {{ finding }}
{% endfor %}
---
## Recommendations
{% for rec in recommendations %}
- {{ rec }}
{% endfor %}
---
*Confidential — IMI Sports Fan Intelligence | {{ date }}*
"""
IMI_INSIGHT_CARD_TEMPLATE = """
┌─────────────────────────────────────────┐
│ {{ title | upper | truncate(40) }}
├─────────────────────────────────────────┤
│ Segment: {{ segment }}
│ Confidence: {{ confidence }}%
│ Sport: {{ sport }}
├─────────────────────────────────────────┤
│ {{ insight | wordwrap(40) }}
└─────────────────────────────────────────┘
"""
def generate_imi_report(
title: str,
client_name: str,
executive_summary: str,
segments: list[dict],
findings: list[str],
recommendations: list[str]
) -> str:
"""Generate a formatted IMI research report."""
env = Environment(loader=BaseLoader())
env.globals["enumerate"] = enumerate
template = env.from_string(IMI_RESEARCH_REPORT_TEMPLATE)
return template.render(
title=title,
client_name=client_name,
date=datetime.now().strftime("%d %B %Y"),
executive_summary=executive_summary,
segments=segments,
findings=findings,
recommendations=recommendations
)
def render_insight_card(title: str, segment: str, confidence: int,
sport: str, insight: str) -> str:
return render_template(
IMI_INSIGHT_CARD_TEMPLATE,
title=title, segment=segment, confidence=confidence,
sport=sport, insight=insight
)
```
---
## Part 2 — Rich Terminal Output
```python
# pip install rich
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn
from rich.markdown import Markdown
from rich.syntax import Syntax
from rich import print as rprint
import time
console = Console()
# IMI brand colours for Rich
IMI_NAVY = "#1A1A2E"
IMI_TEAL = "#0F3D66"
IMI_GOLD = "#E2B95A"
def print_imi_banner():
"""Print IMI branded banner in terminal."""
console.print(Panel(
"[bold #E2B95A]IMI Sports Fan Intelligence[/bold #E2B95A]\n"
"[#0F3D66]Powered by AI Research Engine[/#0F3D66]",
border_style="#1A1A2E",
expand=False
))
def print_segment_table(segments: list[dict]):
"""Print fan segment breakdown as a rich table."""
table = Table(title="Fan Segment Analysis", border_style=IMI_TEAL)
table.add_column("Segment", style=f"bold {IMI_GOLD}", width=12)
table.add_column("Share %", justify="right", width=10)
table.add_column("Key Driver", width=30)
table.add_column("Sponsor Value", justify="center", width=14)
for seg in segments:
table.add_row(
seg.get("name", ""),
str(seg.get("share", 0)),
seg.get("driver", ""),
seg.get("sponsor_value", "Medium")
)
console.print(table)
def print_insight_panel(insight: str, title: str = "Research Insight"):
"""Print a highlighted insight panel."""
console.print(Panel(
f"[italic]{insight}[/italic]",
title=f"[bold {IMI_GOLD}]{title}[/]",
border_style=IMI_TEAL,
padding=(1, 2)
))
def live_research_progress(steps: list[str], fn_per_step=None):
"""Show live progress bar during multi-step research."""
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(bar_width=40),
console=console
) as progress:
task = progress.add_task("[cyan]Researching...", total=len(steps))
for step in steps:
progress.update(task, description=f"[cyan]{step}")
if fn_per_step:
fn_per_step(step)
else:
time.sleep(0.5) # Demo only
progress.advance(task)
def print_llm_response(response: str, model: str = "claude"):
"""Print LLM response with model attribution."""
md = Markdown(response)
console.print(Panel(md, title=f"[dim]{model}[/dim]", border_style="dim"))
```
---
## Part 3 — Markdown & HTML Output
```python
# pip install markdown mistune
import re, html
def llm_to_markdown(text: str) -> str:
"""
Clean LLM output for markdown rendering.
Normalises line breaks, ensures proper heading levels.
"""
# Normalise multiple blank lines
text = re.sub(r'\n{3,}', '\n\n', text)
# Ensure headers have space after #
text = re.sub(r'^(#{1,3})([^#\s])', r'\1 \2', text, flags=re.MULTILINE)
return text.strip()
def markdown_to_html(markdown_text: str) -> str:
"""Convert markdown to HTML with IMI styling."""
try:
import mistune
md = mistune.create_markdown()
body = md(markdown_text)
except ImportError:
# Fallback: basic conversion
body = f"<pre>{html.escape(markdown_text)}</pre>"
return f"""<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="UTF-8">
<style>
body {{ font-family: 'Segoe UI', sans-serif; max-width: 900px; margin: 40px auto; padding: 0 20px; color: #333; }}
h1, h2, h3 {{ color: #1A1A2E; }}
h1 {{ border-bottom: 3px solid #E2B95A; padding-bottom: 8px; }}
table {{ border-collapse: collapse; width: 100%; }}
th {{ background: #1A1A2E; color: #E2B95A; padding: 10px; }}
td {{ border: 1px solid #ddd; padding: 8px; }}
tr:nth-child(even) {{ background: #f5f5f5; }}
blockquote {{ border-left: 4px solid #0F3D66; margin: 0; padding-left: 16px; color: #555; }}
code {{ background: #f0f0f0; padding: 2px 6px; border-radius: 3px; }}
pre {{ background: #1A1A2E; color: #E2B95A; padding: 16px; border-radius: 6px; overflow-x: auto; }}
.imi-footer {{ color: #888; font-size: 0.85em; margin-top: 40px; border-top: 1px solid #ddd; padding-top: 12px; }}
</style>
</head>
<body>
{body}
<div class="imi-footer">IMI Sports Fan Intelligence — Confidential</div>
</body>
</html>"""
def format_llm_output(text: str, output_format: str = "markdown") -> str:
"""
Format LLM output for a given delivery format.
Supported: markdown, html, plain, json_block
"""
if output_format == "markdown":
return llm_to_markdown(text)
elif output_format == "html":
return markdown_to_html(llm_to_markdown(text))
elif output_format == "plain":
# Strip all markdown
text = re.sub(r'#{1,6}\s', '', text)
text = re.sub(r'\*{1,2}(.+?)\*{1,2}', r'\1', text)
text = re.sub(r'`{1,3}(.+?)`{1,3}', r'\1', text, flags=re.DOTALL)
return text.strip()
elif output_format == "json_block":
match = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', text, re.DOTALL)
return match.group(1) if match else text
return text
```
---
## Part 4 — Structured Data Formatting
```python
def format_table_markdown(headers: list[str], rows: list[list]) -> str:
"""Format data as a clean markdown table."""
header_row = "| " + " | ".join(headers) + " |"
separator = "| " + " | ".join(["---"] * len(headers)) + " |"
data_rows = ["| " + " | ".join(str(cell) for cell in row) + " |" for row in rows]
return "\n".join([header_row, separator] + data_rows)
def format_key_value_section(data: dict, title: str = "") -> str:
"""Format a dict as a clean key-value section."""
lines = [f"## {title}" if title else ""]
for key, value in data.items():
label = key.replace("_", " ").title()
lines.append(f"**{label}:** {value}")
return "\n".join(filter(None, lines))
def format_numbered_list(items: list[str], title: str = "") -> str:
"""Format items as a numbered markdown list."""
lines = [f"## {title}" if title else ""]
for i, item in enumerate(items, 1):
lines.append(f"{i}. {item}")
return "\n".join(filter(None, lines))
def format_imi_executive_summary(data: dict) -> str:
"""
Standard IMI executive summary block.
data: {title, client, sport, key_finding, segments, recommendation}
"""
return f"""## Executive Summary
**{data.get('title', 'Research Report')}**
*Prepared for {data.get('client', 'Client')} | {datetime.now().strftime('%B %Y')}*
{data.get('key_finding', '')}
{format_table_markdown(
['Segment', 'Share', 'Sponsor Priority'],
[[s['name'], f"{s['share']}%", s.get('priority', 'Medium')] for s in data.get('segments', [])]
)}
**Recommendation:** {data.get('recommendation', '')}
"""
```
---
## Output Standards
- **Jinja2**: use for all report templates — keeps logic out of prompts
- **Rich**: use for interactive CLI tools and debugging output
- **HTML**: use `markdown_to_html()` for client-facing browser output with IMI styling
- **Tables**: always use `format_table_markdown()` for segment data
- **Consistent formatting**: all LLM outputs should pass through `format_llm_output()` before delivery
- **British English**: "colour" not "color", "analyse" not "analyze", "%d %B %Y" date format
### pip install
```bash
pip install jinja2 rich markdown mistune
```
## AXE MCP Server Integration
Every skill in the AXE Skills Hub runs with access to the **AXE MCP Server** — giving it the full fleet intelligence toolkit automatically. No setup required; tools are available in any AXE-powered session.
### Core Tools Available
| Category | Tools | Use Case |
|----------|-------|----------|
| **Memory** | `read_memory`, `write_memory`, `list_memory` | Persist context across sessions |
| **Web** | `web_search`, `web_fetch` | Live data, docs, research |
| **File Ops** | `read_file`, `write_file` | Read/write any local file |
| **Fleet** | `fleet_ssh`, `axe_push` | Run commands on JL2/JL3/JL4, send notifications |
| **AI Models** | `query_team_channel`, `get_partner_state` | Cross-agent coordination |
| **Data** | `qdrant_search`, `qdrant_store` | Semantic memory & vector search |
| **Pipeline** | `hydra_add` | Add high-quality outputs to Edge training |
| **Skills** | `hub_list_skills`, `hub_get_skill`, `hub_search_skills`, `hub_get_registry`, `hub_skill_metadata` | Chain skills together |
| **Secrets** | `get_secret` | Retrieve API keys securely |
### Quick Start
```python
# In any AXE session, tools are pre-loaded. Example chaining:
# 1. Search for context
results = qdrant_search("user query here", collection="axe_persistent_memory")
# 2. Fetch live data if needed
content = web_fetch("https://docs.example.com/api")
# 3. Write result to memory for next session
write_memory("shared/last_result.md", output)
# 4. Log quality output to Edge training pipeline
hydra_add(prompt=user_query, response=output, score=0.9, source="skill-name")
```
### Edge Training Integration
High-quality skill outputs are automatically eligible for Edge model training via `hydra_add`. When a response scores ≥0.85 in evals, pipe it to the Hydra pipeline to compound Edge's knowledge. This is how skills make Edge smarter over time.
```python
# After generating a high-quality response:
hydra_add(
prompt=user_input,
response=final_output,
score=0.9, # eval score
source="skill-name" # tracks provenance
)
```You are an expert in producing beautifully formatted outputs from LLM pipelines,
applying the templating and rendering patterns used in production AI applications.
You write clean, consistent output systems in British English.
IMI colours: Navy #1A1A2E · Teal #0F3D66 · Gold #E2B95A
# pip install jinja2
from jinja2 import Environment, BaseLoader, FileSystemLoader
from datetime import datetime
# ── In-memory template rendering ──────────────────────────────────────────────
def render_template(template_str: str, **context) -> str:
"""Render a Jinja2 template string with context variables."""
env = Environment(loader=BaseLoader(), autoescape=False)
template = env.from_string(template_str)
return template.render(**context)
# ── IMI report templates ──────────────────────────────────────────────────────
IMI_RESEARCH_REPORT_TEMPLATE = """
# {{ title }}
**Client:** {{ client_name }}
**Date:** {{ date }}
**Prepared by:** IMI Sports Fan Intelligence
---
## Executive Summary
{{ executive_summary }}
---
## Fan Segment Breakdown
| Segment | % of Audience | Key Insight |
|---------|--------------|-------------|
{% for segment in segments %}| {{ segment.name }} | {{ segment.percentage }}% | {{ segment.insight }} |
{% endfor %}
---
## Key Findings
{% for i, finding in enumerate(findings, 1) %}
**{{ i }}.** {{ finding }}
{% endfor %}
---
## Recommendations
{% for rec in recommendations %}
- {{ rec }}
{% endfor %}
---
*Confidential — IMI Sports Fan Intelligence | {{ date }}*
"""
IMI_INSIGHT_CARD_TEMPLATE = """
┌─────────────────────────────────────────┐
│ {{ title | upper | truncate(40) }}
├─────────────────────────────────────────┤
│ Segment: {{ segment }}
│ Confidence: {{ confidence }}%
│ Sport: {{ sport }}
├─────────────────────────────────────────┤
│ {{ insight | wordwrap(40) }}
└─────────────────────────────────────────┘
"""
def generate_imi_report(
title: str,
client_name: str,
executive_summary: str,
segments: list[dict],
findings: list[str],
recommendations: list[str]
) -> str:
"""Generate a formatted IMI research report."""
env = Environment(loader=BaseLoader())
env.globals["enumerate"] = enumerate
template = env.from_string(IMI_RESEARCH_REPORT_TEMPLATE)
return template.render(
title=title,
client_name=client_name,
date=datetime.now().strftime("%d %B %Y"),
executive_summary=executive_summary,
segments=segments,
findings=findings,
recommendations=recommendations
)
def render_insight_card(title: str, segment: str, confidence: int,
sport: str, insight: str) -> str:
return render_template(
IMI_INSIGHT_CARD_TEMPLATE,
title=title, segment=segment, confidence=confidence,
sport=sport, insight=insight
)
# pip install rich
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn
from rich.markdown import Markdown
from rich.syntax import Syntax
from rich import print as rprint
import time
console = Console()
# IMI brand colours for Rich
IMI_NAVY = "#1A1A2E"
IMI_TEAL = "#0F3D66"
IMI_GOLD = "#E2B95A"
def print_imi_banner():
"""Print IMI branded banner in terminal."""
console.print(Panel(
"[bold #E2B95A]IMI Sports Fan Intelligence[/bold #E2B95A]\n"
"[#0F3D66]Powered by AI Research Engine[/#0F3D66]",
border_style="#1A1A2E",
expand=False
))
def print_segment_table(segments: list[dict]):
"""Print fan segment breakdown as a rich table."""
table = Table(title="Fan Segment Analysis", border_style=IMI_TEAL)
table.add_column("Segment", style=f"bold {IMI_GOLD}", width=12)
table.add_column("Share %", justify="right", width=10)
table.add_column("Key Driver", width=30)
table.add_column("Sponsor Value", justify="center", width=14)
for seg in segments:
table.add_row(
seg.get("name", ""),
str(seg.get("share", 0)),
seg.get("driver", ""),
seg.get("sponsor_value", "Medium")
)
console.print(table)
def print_insight_panel(insight: str, title: str = "Research Insight"):
"""Print a highlighted insight panel."""
console.print(Panel(
f"[italic]{insight}[/italic]",
title=f"[bold {IMI_GOLD}]{title}[/]",
border_style=IMI_TEAL,
padding=(1, 2)
))
def live_research_progress(steps: list[str], fn_per_step=None):
"""Show live progress bar during multi-step research."""
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(bar_width=40),
console=console
) as progress:
task = progress.add_task("[cyan]Researching...", total=len(steps))
for step in steps:
progress.update(task, description=f"[cyan]{step}")
if fn_per_step:
fn_per_step(step)
else:
time.sleep(0.5) # Demo only
progress.advance(task)
def print_llm_response(response: str, model: str = "claude"):
"""Print LLM response with model attribution."""
md = Markdown(response)
console.print(Panel(md, title=f"[dim]{model}[/dim]", border_style="dim"))
# pip install markdown mistune
import re, html
def llm_to_markdown(text: str) -> str:
"""
Clean LLM output for markdown rendering.
Normalises line breaks, ensures proper heading levels.
"""
# Normalise multiple blank lines
text = re.sub(r'\n{3,}', '\n\n', text)
# Ensure headers have space after #
text = re.sub(r'^(#{1,3})([^#\s])', r'\1 \2', text, flags=re.MULTILINE)
return text.strip()
def markdown_to_html(markdown_text: str) -> str:
"""Convert markdown to HTML with IMI styling."""
try:
import mistune
md = mistune.create_markdown()
body = md(markdown_text)
except ImportError:
# Fallback: basic conversion
body = f"<pre>{html.escape(markdown_text)}</pre>"
return f"""<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="UTF-8">
<style>
body {{ font-family: 'Segoe UI', sans-serif; max-width: 900px; margin: 40px auto; padding: 0 20px; color: #333; }}
h1, h2, h3 {{ color: #1A1A2E; }}
h1 {{ border-bottom: 3px solid #E2B95A; padding-bottom: 8px; }}
table {{ border-collapse: collapse; width: 100%; }}
th {{ background: #1A1A2E; color: #E2B95A; padding: 10px; }}
td {{ border: 1px solid #ddd; padding: 8px; }}
tr:nth-child(even) {{ background: #f5f5f5; }}
blockquote {{ border-left: 4px solid #0F3D66; margin: 0; padding-left: 16px; color: #555; }}
code {{ background: #f0f0f0; padding: 2px 6px; border-radius: 3px; }}
pre {{ background: #1A1A2E; color: #E2B95A; padding: 16px; border-radius: 6px; overflow-x: auto; }}
.imi-footer {{ color: #888; font-size: 0.85em; margin-top: 40px; border-top: 1px solid #ddd; padding-top: 12px; }}
</style>
</head>
<body>
{body}
<div class="imi-footer">IMI Sports Fan Intelligence — Confidential</div>
</body>
</html>"""
def format_llm_output(text: str, output_format: str = "markdown") -> str:
"""
Format LLM output for a given delivery format.
Supported: markdown, html, plain, json_block
"""
if output_format == "markdown":
return llm_to_markdown(text)
elif output_format == "html":
return markdown_to_html(llm_to_markdown(text))
elif output_format == "plain":
# Strip all markdown
text = re.sub(r'#{1,6}\s', '', text)
text = re.sub(r'\*{1,2}(.+?)\*{1,2}', r'\1', text)
text = re.sub(r'`{1,3}(.+?)`{1,3}', r'\1', text, flags=re.DOTALL)
return text.strip()
elif output_format == "json_block":
match = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', text, re.DOTALL)
return match.group(1) if match else text
return text
def format_table_markdown(headers: list[str], rows: list[list]) -> str:
"""Format data as a clean markdown table."""
header_row = "| " + " | ".join(headers) + " |"
separator = "| " + " | ".join(["---"] * len(headers)) + " |"
data_rows = ["| " + " | ".join(str(cell) for cell in row) + " |" for row in rows]
return "\n".join([header_row, separator] + data_rows)
def format_key_value_section(data: dict, title: str = "") -> str:
"""Format a dict as a clean key-value section."""
lines = [f"## {title}" if title else ""]
for key, value in data.items():
label = key.replace("_", " ").title()
lines.append(f"**{label}:** {value}")
return "\n".join(filter(None, lines))
def format_numbered_list(items: list[str], title: str = "") -> str:
"""Format items as a numbered markdown list."""
lines = [f"## {title}" if title else ""]
for i, item in enumerate(items, 1):
lines.append(f"{i}. {item}")
return "\n".join(filter(None, lines))
def format_imi_executive_summary(data: dict) -> str:
"""
Standard IMI executive summary block.
data: {title, client, sport, key_finding, segments, recommendation}
"""
return f"""## Executive Summary
**{data.get('title', 'Research Report')}**
*Prepared for {data.get('client', 'Client')} | {datetime.now().strftime('%B %Y')}*
{data.get('key_finding', '')}
{format_table_markdown(
['Segment', 'Share', 'Sponsor Priority'],
[[s['name'], f"{s['share']}%", s.get('priority', 'Medium')] for s in data.get('segments', [])]
)}
**Recommendation:** {data.get('recommendation', '')}
"""
markdown_to_html() for client-facing browser output with IMI stylingformat_table_markdown() for segment dataformat_llm_output() before deliverypip install jinja2 rich markdown mistune
Every skill in the AXE Skills Hub runs with access to the AXE MCP Server — giving it the full fleet intelligence toolkit automatically. No setup required; tools are available in any AXE-powered session.
| Category | Tools | Use Case |
|---|---|---|
| Memory | read_memory, write_memory, list_memory | Persist context across sessions |
| Web | web_search, web_fetch | Live data, docs, research |
| File Ops | read_file, write_file | Read/write any local file |
| Fleet | fleet_ssh, axe_push | Run commands on JL2/JL3/JL4, send notifications |
| AI Models | query_team_channel, get_partner_state | Cross-agent coordination |
| Data | qdrant_search, qdrant_store | Semantic memory & vector search |
| Pipeline | hydra_add | Add high-quality outputs to Edge training |
| Skills | hub_list_skills, hub_get_skill, hub_search_skills, hub_get_registry, hub_skill_metadata | Chain skills together |
| Secrets | get_secret | Retrieve API keys securely |
# In any AXE session, tools are pre-loaded. Example chaining:
# 1. Search for context
results = qdrant_search("user query here", collection="axe_persistent_memory")
# 2. Fetch live data if needed
content = web_fetch("https://docs.example.com/api")
# 3. Write result to memory for next session
write_memory("shared/last_result.md", output)
# 4. Log quality output to Edge training pipeline
hydra_add(prompt=user_query, response=output, score=0.9, source="skill-name")
High-quality skill outputs are automatically eligible for Edge model training via hydra_add. When a response scores ≥0.85 in evals, pipe it to the Hydra pipeline to compound Edge's knowledge. This is how skills make Edge smarter over time.
# After generating a high-quality response:
hydra_add(
prompt=user_input,
response=final_output,
score=0.9, # eval score
source="skill-name" # tracks provenance
)
Fetch this skill’s definition over the open API — no key required.
curl -s /v1/skills/output-formatting