Fireworks tech graph

From ninehills/skills · View interactive version

Fireworks tech graph is an AI agent skill from the GitHub repository ninehills/skills. Use when the user wants to create any technical diagram - architecture, data flow, flowchart, sequence, agent/memory, or concept map - and export as SVG+PNG. Trigger on: "画图" "帮我画" "生成图" "做个图" "架构图" "流程图" "可视化一下" "出图" "generate diagram" "draw diagram" "visualize" or any system/flow description the u

How to use this skill

Skill file

Fireworks Tech Graph

Generate production-quality SVG technical diagrams exported as PNG via cairosvg (recommended), rsvg-convert, or puppeteer.

Install Source

Install this skill from GitHub:

npx skills add yizhiyanhua-ai/fireworks-tech-graph

Public package page:

https://www.npmjs.com/package/@yizhiyanhua-ai/fireworks-tech-graph

Do not pass @yizhiyanhua-ai/fireworks-tech-graph directly to skills add, because the CLI expects a GitHub or local repository source.

Update command:

npx skills add yizhiyanhua-ai/fireworks-tech-graph --force -g -y

Helper Scripts (Recommended)

Four helper scripts in scripts/ directory provide stable SVG generation and validation:

1. `generate-diagram.sh` - Validate SVG + export PNG

./scripts/generate-diagram.sh -t architecture -s 1 -o ./output/arch.svg

2. `generate-from-template.py` - Create starter SVG from template

python3 ./scripts/generate-from-template.py architecture ./output/arch.svg '{"title":"My Diagram","nodes":[],"arrows":[]}'

3. `validate-svg.sh` - Validate SVG syntax

./scripts/validate-svg.sh <svg-file>

4. `test-all-styles.sh` - Batch test all styles

./scripts/test-all-styles.sh

When to use scripts:

When to generate SVG directly:

Workflow (Always Follow This Order)

  1. Classify the diagram type (see Diagram Types below)
  2. Extract structure — identify layers, nodes, edges, flows, and semantic groups from user description
  3. Plan layout — apply the layout rules for the diagram type
  4. Load style reference — always load references/style-1-flat-icon.md unless user specifies another; load the matching references/style-N.md for exact color tokens and SVG patterns
  5. Map nodes to shapes — use Shape Vocabulary below
  6. Check icon needs — load references/icons.md for known products
  7. Write SVG with adaptive strategy (see SVG Generation Strategy below)
  8. Validate: Run python3 -c "import xml.etree.ElementTree as ET; ET.parse('file.svg')" to check XML syntax
  9. Export PNG: Use cairosvg (recommended). See SVG → PNG Conversion section below for full method comparison
  10. Report the generated file paths
  11. (Optional) Visual self-review — if your runtime can read images, load the exported PNG back and inspect it. Syntactic validity does not guarantee visual correctness: arrows may cross through component interiors, labels may collide with lifelines or other labels, boxes may overlap, alt-frame text may sit on top of a message, or a legend may cover content. If you see any of these, revise the SVG and re-export; repeat until the rendered image is clean. Common fixes:

Skip this step silently if image reading is unavailable — do not guess.

Diagram Types & Layout Rules

Architecture Diagram

Nodes = services/components. Group into horizontal layers (top→bottom or left→right).

Data Flow Diagram

Emphasizes what data moves where. Focus on data transformation.

Flowchart / Process Flow

Sequential decision/process steps.

Agent Architecture Diagram

Shows how an AI agent reasons, uses tools, and manages memory.

Key conceptual layers to always consider:

Use cyclic arrows (loop arcs) to show iterative reasoning. Separate memory types visually.

Memory Architecture Diagram (Mem0, MemGPT-style)

Specialized agent diagram focused on memory operations.

Sequence Diagram

Time-ordered message exchanges between participants.

Comparison / Feature Matrix

Side-by-side comparison of approaches, systems, or components.

Timeline / Gantt

Horizontal time axis showing durations, phases, and milestones.

Mind Map / Concept Map

Radial layout from central concept.

Class Diagram (UML)

Static structure showing classes, attributes, methods, and relationships.

Use Case Diagram (UML)

System functionality from user perspective.

State Machine Diagram (UML)

Lifecycle states and transitions of an entity.

ER Diagram (Entity-Relationship)

Database schema and data relationships.

Network Topology

Physical or logical network infrastructure.

UML Coverage Map

Full mapping of UML 14 diagram types to supported diagram types:

| UML Diagram | Supported As | Notes |

|-------------|-------------|-------|

| Class | Class Diagram | Full UML notation |

| Component | Architecture Diagram | Use colored fills per component type |

| Deployment | Architecture Diagram | Add node/instance labels |

| Package | Architecture Diagram | Use dashed grouping containers |

| Composite Structure | Architecture Diagram | Nested rects within components |

| Object | Class Diagram | Instance boxes with underlined name |

| Use Case | Use Case Diagram | Full actor/ellipse/relationship |

| Activity | Flowchart / Process Flow | Add fork/join bars |

| State Machine | State Machine Diagram | Full UML notation |

| Sequence | Sequence Diagram | Add alt/opt/loop frames |

| Communication | — | Approximate with Sequence (swap axes) |

| Timing | Timeline | Adapt time axis |

| Interaction Overview | Flowchart | Combine activity + sequence fragments |

| ER Diagram | ER Diagram | Chen/Crow's foot notation |

Shape Vocabulary

Map semantic concepts to consistent shapes across all diagram types:

| Concept | Shape | Notes |

|---------|-------|-------|

| User / Human | Circle + body path | Stick figure or avatar |

| LLM / Model | Rounded rect with brain/spark icon or gradient fill | Use accent color |

| Agent / Orchestrator | Hexagon or rounded rect with double border | Signals "active controller" |

| Memory (short-term) | Rounded rect, dashed border | Ephemeral = dashed |

| Memory (long-term) | Cylinder (database shape) | Persistent = solid cylinder |

| Vector Store | Cylinder with grid lines inside | Add 3 horizontal lines |

| Graph DB | Circle cluster (3 overlapping circles) | |

| Tool / Function | Gear-like rect or rect with wrench icon | |

| API / Gateway | Hexagon (single border) | |

| Queue / Stream | Horizontal tube (pipe shape) | |

| File / Document | Folded-corner rect | |

| Browser / UI | Rect with 3-dot titlebar | |

| Decision | Diamond | Flowcharts only |

| Process / Step | Rounded rect | Standard box |

| External Service | Rect with cloud icon or dashed border | |

| Data / Artifact | Parallelogram | I/O in flowcharts |

Arrow Semantics

Always assign arrow meaning, not just color:

| Flow Type | Color | Stroke | Dash | Meaning |

|-----------|-------|--------|------|---------|

| Primary data flow | blue #2563eb | 2px solid | none | Main request/response path |

| Control / trigger | orange #ea580c | 1.5px solid | none | One system triggering another |

| Memory read | green #059669 | 1.5px solid | none | Retrieval from store |

| Memory write | green #059669 | 1.5px | 5,3 | Write/store operation |

| Async / event | gray #6b7280 | 1.5px | 4,2 | Non-blocking, event-driven |

| Embedding / transform | purple #7c3aed | 1px solid | none | Data transformation |

| Feedback / loop | purple #7c3aed | 1.5px curved | none | Iterative reasoning loop |

Always include a legend when 2+ arrow types are used.

Layout Rules & Validation

Spacing:

Arrow Labels (CRITICAL):

Arrow Routing:

Post-Generation Arrow Optimization:

When a user asks to "优化箭头" / "fix arrow routing" / "optimize the diagram" on an already-generated diagram, preserve all nodes, containers, styles, and layout — only modify the arrows entries in the JSON data, then re-render with generate-from-template.py.

Available arrow override fields (in recommended order of use):

| Field | Type | When to Use |

|-------|------|-------------|

| source_port / target_port | "left" / "right" / "top" / "bottom" | Arrow exits/enters from the wrong edge |

| corridor_x | [x, ...] | Hint vertical segments toward this x lane (soft preference) |

| corridor_y | [y, ...] | Hint horizontal segments toward this y lane (soft preference) |

| route_points | [[x1,y1], [x2,y2], ...] | Force exact waypoints (bypasses auto-routing); keep segments orthogonal |

| routing_padding | number (default: 24) | (Advanced) Adjust obstacle clearance for this arrow |

| port_clearance | number | (Advanced) Adjust first-segment offset from node edge |

| label_style | "badge" / "offset" | Choose "offset" when badge backgrounds create visual clutter; keep "badge" (default) for legacy/high-contrast labels |

For JSON/template rendering, the default remains "badge" for backward compatibility. Set "label_style": "offset" on individual arrows when you want offset-first labels without background rects.

Optimization steps:

  1. Read the existing SVG — identify which arrows overlap, cross nodes, or look misaligned
  2. Find those arrows in the JSON data by source / target pair
  3. Add source_port / target_port if the exit/entry direction is wrong; add corridor_x / corridor_y to space parallel arrows apart; use route_points only when hints alone cannot resolve the path
  4. Re-run generate-from-template.py with the updated JSON and validate with validate-svg.sh

Example — spacing two overlapping arrows into separate corridors:

{ "source": "nodeA", "target": "nodeB", "corridor_y": [280] }
{ "source": "nodeC", "target": "nodeD", "corridor_y": [320] }

Line Overlap Prevention (CRITICAL - most common bug on Codex):

When two arrows must cross each other, ALWAYS use jump-over arcs to prevent visual overlap:

Validation Checklist (run before finalizing):

  1. Arrow-Component Collision: Arrows MUST NOT pass through component interiors (route around with orthogonal paths)
  2. Text Overflow: All text MUST fit with 8px padding (estimate: text.length × 7px ≤ shape_width - 16px)
  3. Arrow-Text Alignment: Arrow endpoints MUST connect to shape edges (not floating); arrow labels should not overlap arrow lines (use offset positioning or background rects)
  4. Container Discipline: Prefer arrows entering and leaving section containers through open gaps between components, not through inner component bodies
  5. Filter Boundary Safety: For every element with filter="url(...)", verify (element_x + element_width + filter_extension) ≤ viewBox_width AND element_x ≥ filter_extension. The default filter region extends 10-20% beyond bbox; staying near viewBox edges causes Chrome/cairosvg to clip the element's edge-side stroke (one side of the border vanishes while other sides render correctly)
  6. Arrow-Title Collision: Arrows MUST NOT cross through section/container title text or region labels (font-size ≥ 13px). For smaller annotations (< 13px), prefer routing around but tolerate if layout constraints require it. (Visual self-review check — not covered by validate-svg.sh automated checks)
  7. Frame Label–Arrow Alignment (sequence diagrams): Section/frame label badges MUST be vertically centered with their first message arrow. Compute badge_y = first_arrow_y - (badge_height / 2). When appending new sections to an existing diagram, verify alignment matches the existing sections — this is the most common regression when adding content incrementally. Use variables in Python list generation to enforce the constraint: sec_y = 840; badge_y = sec_y - 9 # for height=18 badge

SVG Technical Rules

SVG Generation & Error Prevention

MANDATORY: Python List Method (ALWAYS use this):

python3 << 'EOF'
lines = []
lines.append('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 960 700">')
lines.append('  <defs>')
# ... each line separately
lines.append('</svg>')

with open('/path/to/output.svg', 'w') as f:
    f.write('\n'.join(lines))
print("SVG generated successfully")
EOF

Why mandatory: Prevents character truncation, typos, and syntax errors. Each line is independent and easy to verify.

Pre-Tool-Call Checklist (CRITICAL - use EVERY time):

  1. ✅ Can I write out the COMPLETE command/content right now?
  2. ✅ Do I have ALL required parameters ready?
  3. ✅ Have I checked for syntax errors in my prepared content?

If ANY answer is NO: STOP. Do NOT call the tool. Prepare the content first.

Error Recovery Protocol:

Validation (run after generation):

python3 -c "import xml.etree.ElementTree as ET; ET.parse('file.svg')" && echo "✓ Valid XML"
# Or use cairosvg as a render-time check:
python3 -c "import cairosvg; cairosvg.svg2png(url='file.svg', write_to='/tmp/test.png')" && echo "✓ Renders" && rm /tmp/test.png

If using generate-from-template.py:

Common Syntax Errors to Avoid:

Output

SVG → PNG Conversion

Method Comparison

| Tool | Install | Render Quality | Notes |

|------|---------|----------------|-------|

| rsvg-convert | System (often preinstalled) | ⚠️ Fair | Drops some CSS styles and <foreignObject> elements — missing borders/text on complex SVGs |

| cairosvg (recommended) | pip install cairosvg | ✅ Good | Solid CSS support; clearly better than rsvg-convert |

| puppeteer (headless Chrome) | npm install puppeteer | ✅✅ Best | Real browser engine; 100% fidelity but heavy (Node + Chromium) |

Recommended: cairosvg (Python one-liner)

# Single file (2x resolution for retina/docs)
python3 -c "import cairosvg; cairosvg.svg2png(url='input.svg', write_to='output.png', scale=2)"

# Batch convert all SVGs in a directory
python3 -c "
import cairosvg, os, glob
d = 'docs/00-core'
for svg in sorted(glob.glob(os.path.join(d, '*.svg'))):
    png = svg.replace('.svg', '.png')
    cairosvg.svg2png(url=svg, write_to=png, scale=2)
    print(f'Done: {os.path.basename(svg)} -> {os.path.basename(png)}')
"

scale=2 produces 2x resolution PNG, ideal for high-DPI screens and embedded docs.

Fallback: rsvg-convert (simple but may drop styles)

# Single file
rsvg-convert -w 1920 file.svg -o file.png

# Batch (not recommended — complex SVGs may lose elements)
for f in docs/00-core/*.svg; do rsvg-convert -o "${f%.svg}.png" "$f"; done

# 2x resolution
for f in docs/00-core/*.svg; do rsvg-convert -z 2 -o "${f%.svg}.png" "$f"; done

Highest Fidelity: puppeteer (headless Chrome)

npm install puppeteer  # auto-downloads Chromium
node svg2png.js [directory]

<details>

<summary>svg2png.js — full puppeteer script</summary>

const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');

(async () => {
  const dir = process.argv[2] || '.';
  const svgFiles = fs.readdirSync(dir).filter(f => f.endsWith('.svg'));

  const browser = await puppeteer.launch({
    headless: 'new',
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });

  for (const file of svgFiles) {
    const svgPath = path.resolve(dir, file);
    const pngPath = svgPath.replace(/\.svg$/, '.png');
    const svgContent = fs.readFileSync(svgPath, 'utf-8');

    const wMatch = svgContent.match(/width="(\d+)/);
    const hMatch = svgContent.match(/height="(\d+)/);
    const vbMatch = svgContent.match(/viewBox="[^"]*\s(\d+)\s(\d+)"/);

    let width = wMatch ? parseInt(wMatch[1]) : (vbMatch ? parseInt(vbMatch[1]) : 1200);
    let height = hMatch ? parseInt(hMatch[1]) : (vbMatch ? parseInt(vbMatch[2]) : 800);

    const scale = 2;
    const page = await browser.newPage();
    await page.setViewport({ width, height, deviceScaleFactor: scale });

    const html = `<!DOCTYPE html>
<html><head><style>
  body { margin: 0; padding: 0; background: transparent; }
  img { display: block; }
</style></head>
<body>
  <img src="data:image/svg+xml;base64,${Buffer.from(svgContent).toString('base64')}" width="${width}" height="${height}" />
</body></html>`;

    await page.setContent(html, { waitUntil: 'networkidle0' });
    await page.screenshot({ path: pngPath, type: 'png', omitBackground: true });
    await page.close();

    console.log(`Done: ${file} -> ${path.basename(pngPath)} (${width}x${height} @${scale}x)`);
  }

  await browser.close();
})();

</details>

Gotchas (lessons learned)

Picking a Method

  1. Default → cairosvg (pip install once, one-line conversion, good fidelity)
  2. No Python available → rsvg-convert (acceptable for simple flat-color diagrams)
  3. Browser-generated SVG or pixel-perfect required → puppeteer

Styles

| # | Name | Background | Best For |

|---|------|-----------|----------|

| 1 | Flat Icon (default) | White | Blogs, docs, presentations |

| 2 | Dark Terminal | #0f0f1a | GitHub, dev articles |

| 3 | Blueprint | #0a1628 | Architecture docs |

| 4 | Notion Clean | White, minimal | Notionnce |

| 5 | Glassmorphism | Dark gradient | Product sites, keynotes |

| 6 | Claude Official | Warm cream #f8f6f3 | Anthropic-style diagrams |

| 7 | OpenAI Official | Pure white #ffffff | OpenAI-style diagrams |

| 8 | Dark Luxury (AI-authored) | #0a0a0a deep black | Architecture docs, premium editorial — hand-craft SVG from references/style-8-dark-luxury.md |

Load references/style-N.md for exact color tokens and SVG patterns.

Style Selection

Default: Style 1 (Flat Icon) for most diagrams. Load references/style-diagram-matrix.md for detailed style-to-diagram-type recommendations.

These patterns appear frequently — internalize them:

RAG Pipeline: Query → Embed → VectorSearch → Retrieve → Augment → LLM → Response

Agentic RAG: adds Agent loop with Tool use between Query and LLM

Agentic Search: Query → Planner → [Search Tool / Calculator / Code] → Synthesizer → Response

Mem0 / Memory Layer: Input → Memory Manager → [Write: VectorDB + GraphDB] / [Read: Retrieve+Rank] → Context

Agent Memory Types: Sensory (raw input) → Working (context window) → Episodic (past interactions) → Semantic (facts) → Procedural (skills)

Multi-Agent: Orchestrator → [SubAgent A / SubAgent B / SubAgent C] → Aggregator → Output

Tool Call Flow: LLM → Tool Selector → Tool Execution → Result Parser → LLM (loop)

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.