Cheatsheets

Quick reference guides for developers and anyone who needs information fast. Essential knowledge distilled to what matters most.

A Practical Guide to Building Agents

A Practical Guide to Building Agents - Summary

A_Practical_Guide_to_Building_Agents/
│
├── 01_What_is_an_Agent/
│   ├── Definition: Systems that independently accomplish tasks
│   ├── Core_Characteristics/
│   │   ├── Uses LLM to manage workflow execution
│   │   └── Has access to tools with defined guardrails
│   └── Not_Agents: Simple chatbots, single-turn LLMs, classifiers
│
├── 02_When_to_Build_an_Agent/
│   ├── Use_Cases/
│   │   ├── Complex decision-making (refund approvals)
│   │   ├── Difficult-to-maintain rules (vendor reviews)
│   │   └── Heavy unstructured data (insurance claims)
│   └── Validation: Must resist traditional automation
│
├── 03_Agent_Design_Foundations/
│   ├── Core_Components/
│   │   ├── Model: LLM for reasoning and decisions
│   │   ├── Tools: External functions/APIs
│   │   └── Instructions: Explicit guidelines and guardrails
│   │
│   ├── Model_Selection/
│   │   ├── Start with most capable model
│   │   ├── Establish performance baseline with evals
│   │   └── Optimize: Replace with smaller models where possible
│   │
│   ├── Tool_Types/
│   │   ├── Data: Retrieve context (query DBs, read PDFs, search web)
│   │   ├── Action: Take actions (send emails, update CRM)
│   │   └── Orchestration: Agents as tools for other agents
│   │
│   └── Instructions_Best_Practices/
│       ├── Use existing documents (SOPs, policies)
│       ├── Break down tasks into clear steps
│       ├── Define clear actions for each step
│       └── Capture edge cases
│
├── 04_Orchestration/
│   ├── Single_Agent_Systems/
│   │   ├── One agent with multiple tools
│   │   ├── Loop until exit condition (tool call, output, error, max turns)
│   │   ├── Use prompt templates with variables
│   │   └── When_to_Split: Complex logic or tool overload
│   │
│   └── Multi_Agent_Systems/
│       ├── Manager_Pattern/
│       │   ├── Central manager orchestrates specialized agents
│       │   ├── Agents as tools (tool calls)
│       │   ├── Manager maintains control and context
│       │   └── Use_Case: Single agent controls workflow and user access
│       │
│       └── Decentralized_Pattern/
│           ├── Agents hand off to each other (peers)
│           ├── One-way transfer with conversation state
│           ├── No central controller needed
│           └── Use_Case: Specialized agents fully take over tasks
│
├── 05_Guardrails/
│   ├── Philosophy: Layered defense mechanism
│   │
│   ├── Types/
│   │   ├── Relevance_Classifier: Keep responses on-topic
│   │   ├── Safety_Classifier: Detect jailbreaks/prompt injections
│   │   ├── PII_Filter: Prevent exposure of personal data
│   │   ├── Moderation: Flag harmful content
│   │   ├── Tool_Safeguards: Risk ratings (low/medium/high)
│   │   ├── Rules_Based: Blocklists, input limits, regex
│   │   └── Output_Validation: Brand alignment checks
│   │
│   ├── Building_Strategy/
│   │   ├── 1. Focus on data privacy and content safety
│   │   ├── 2. Add guardrails based on real failures
│   │   └── 3. Optimize for security AND user experience
│   │
│   └── Human_Intervention/
│       ├── Trigger_1: Exceeding failure thresholds
│       └── Trigger_2: High-risk actions (refunds, payments)
│
└── 06_Key_Principles/
    ├── Start simple: Single agent first
    ├── Iterate: Add complexity only when needed
    ├── Validate: Test with real users
    ├── Monitor: Track failures and edge cases
    └── Evolve: Grow capabilities over time

Key Takeaways

Agent = Model + Tools + Instructions + Guardrails

Tree Traversal Algorithms Cheat Sheet

Tree traversal algorithms

Goes deep first.

Goes wide first.

Depth-First Traversal (DFT)

Inorder traversal

Left -> Root -> Right = Visit root in the middle.

go left
[Visit]
go right

Preorder traversal

Root -> Left -> Right = Visit root first.

[Visit]
go left
go right

Postorder traversal

Left -> Right -> Root = Visit root last.

15 Essential LeetCode Patterns

15 Essential LeetCode Patterns

1. Prefix Sum

Concept: Precompute cumulative sums to answer range sum queries in O(1) time.

When to use:

How it works:

Array:      [1, 2, 3, 4, 5, 6]
Prefix Sum: [1, 3, 6, 10, 15, 21]

Sum of range [i, j] = prefix[j] - prefix[i-1]

Code:

 1def build_prefix_sum(nums):
 2    prefix = [0] * len(nums)
 3    prefix[0] = nums[0]
 4    for i in range(1, len(nums)):
 5        prefix[i] = prefix[i-1] + nums[i]
 6    return prefix
 7
 8def range_sum(prefix, left, right):
 9    if left == 0:
10        return prefix[right]
11    return prefix[right] - prefix[left - 1]

Complexity: O(n) preprocessing, O(1) query

Web Components Cheat Sheet

Web Components Cheat Sheet

A practical reference for building native Web Components based on real-world patterns.


Core Structure

Basic Component Template

 1class MyComponent extends HTMLElement {
 2  constructor() {
 3    super(); // Always call super() first
 4    this.attachShadow({ mode: "open" }); // Shadow DOM encapsulation
 5    // Initialize state here
 6    this.isActive = false;
 7  }
 8
 9  // Lifecycle: element added to DOM
10  connectedCallback() {
11    this.render();
12    this.setupEventListeners();
13  }
14
15  // Lifecycle: element removed from DOM
16  disconnectedCallback() {
17    // Clean up event listeners, timers, etc.
18  }
19
20  // Lifecycle: element moved to new document
21  adoptedCallback() {
22    // Called when moved to a new document (e.g., iframe)
23  }
24
25  // Lifecycle: observed attributes changed
26  attributeChangedCallback(name, oldValue, newValue) {
27    if (oldValue !== newValue) {
28      this.render();
29    }
30  }
31
32  // Declare which attributes to observe
33  static get observedAttributes() {
34    return ["active", "size"];
35  }
36}
37
38// Register the component
39customElements.define("my-component", MyComponent);

Key Gotcha: Constructor Restrictions

 1// WRONG - Cannot access attributes in constructor
 2constructor() {
 3  super();
 4  this.value = this.getAttribute('value'); // Returns null!
 5  // Cannot access parentElement, children, or most DOM features
 6}
 7
 8// CORRECT - Access attributes in connectedCallback
 9connectedCallback() {
10  this.value = this.getAttribute('value'); // Works correctly
11  this.render();
12}

Why? The constructor runs before the element is added to the DOM and before attributes are set. Use connectedCallback() for DOM interactions and attribute access.

DSPy Few-Shot Optimization Cheat Sheet

Optimizing RAG Systems with DSPy

What is DSPy?

DSPy is a framework that treats prompting as a programming paradigm rather than an art form. Instead of manually crafting and tweaking prompts, you define the structure of your task, and DSPy automatically optimizes the prompts and few-shot examples for you.

The framework introduces “signatures” that declare what your LM should do, and “teleprompters” that compile your program by optimizing these components against a metric.

GCP Terraform Cheat Sheet

Prerequisites

Before starting, ensure you have:

  1. GCP Account - Sign up at cloud.google.com
  2. Billing Account - Credit card required (even for free tier)
  3. gcloud CLI - Install: brew install google-cloud-sdk (macOS) or download
  4. Terraform - Install: brew install terraform (macOS) or download

Finding Your Billing Account ID

  1. Go to GCP Billing Console
  2. Select your billing account
  3. Copy the ID from the page (format: XXXXXX-XXXXXX-XXXXXX)

You need this ID for linking projects to billing.

Project Structure Basics

Essential Files

project/
├── main.tf           # Main infrastructure definitions
├── variables.tf      # Input variables
├── outputs.tf        # Output values
├── terraform.tfvars  # Variable values (add to .gitignore!)
└── .gitignore        # Exclude sensitive files

Critical: Always add terraform.tfvars and *.tfstate to .gitignore to avoid committing credentials.

Racket Cheat Sheet

Lang Declaration

Every Racket file must start with a #lang directive specifying the language variant:

1#lang racket/base    ; Minimal core
2#lang racket         ; Standard library
3#lang at-exp racket  ; @ notation for string interpolation

Exports & Contracts

Contracts with exports (preferred pattern for library code):

1(provide (contract-out
2  [function-name (-> string? number? boolean?)]
3  [process-data (->* (string?) (number?) list?)]))  ; optional params

Simple exports (for internal code):

1(provide function-name
2         another-function)

Submodules

Test submodule - code only runs during raco test:

1(module+ test
2  (require rackunit)
3  (test-case "description"
4    (check-equal? (add 2 3) 5)))

Main submodule - entry point when file runs as script:

Racket Cryptography Cheat Sheet

Prerequisites

Required Initialization

 1(require crypto
 2         crypto/all
 3         crypto/pem
 4         crypto/pkcs8)
 5
 6; CRITICAL: Must initialize before ANY crypto operations
 7(use-all-factories!)
 8
 9; Without this initialization:
10; Error: "datum->pk-key: unable to read key\n  format: 'PrivateKeyInfo"

Rule: Always call (use-all-factories!) at module initialization, not inside functions.

Loading RSA Keys from PEM Files

Reading PEM Files

 1; Read PEM file and extract DER-encoded data
 2(define (read-pem-file path)
 3  (define in (open-input-file path))
 4  (define result (read-pem in))
 5  (close-input-port in)
 6
 7  (if (eof-object? result)
 8      (error 'read-pem-file "no PEM data found")
 9      (values (bytes->string/utf-8 (car result))  ; PEM type (e.g., "PRIVATE KEY")
10              (cdr result))))                      ; DER-encoded bytes

Parsing Private Keys with Format Fallback

PEM files can contain PKCS#1 (legacy) or PKCS#8 (modern) format keys:

Racket Web Applications Cheat Sheet

Setting Up a Racket Web Server

Basic Server Configuration

 1(require (prefix-in servlet: web-server/servlet-env))
 2
 3(servlet:serve/servlet
 4  dispatcher-function
 5  #:listen-ip "0.0.0.0"
 6  #:port 8080
 7  #:launch-browser? #f
 8  #:quit? #f
 9  #:servlet-path "/"
10  #:servlet-regexp #rx""
11  #:stateless? #t)

Pattern: Use #:stateless? #t for REST APIs that don’t need session continuations.

Main Module Entry Point

 1(module+ main
 2  (servlet:serve/servlet
 3    route-dispatch/with-middleware
 4    #:listen-ip "0.0.0.0"
 5    #:port 8080
 6    #:launch-browser? #f
 7    #:quit? #f
 8    #:servlet-path "/"
 9    #:servlet-regexp #rx""
10    #:stateless? #t))

URL Routing and Dispatching

Dispatch Rules

1(require (prefix-in dispatch: web-server/dispatch))
2
3(define-values (route-dispatch request-parser)
4  (dispatch:dispatch-rules
5    [("") homepage-handler]
6    [("api" "users") #:method "post" create-user-handler]
7    [("api" "users" (string-arg)) get-user-handler]
8    [("api" "data" (integer-arg)) #:method "delete" delete-data-handler]
9    [else not-found-handler]))

Gotcha: The dispatch-rules macro returns two values - the dispatcher and a request parser. Use define-values.

InterSystems IRIS Cheat Sheet

Notes from an Intersystems IRIS course that I attended in 2024.

Core Concepts

IRIS Data Platform

Process Types

Storage Model

Web Components Cheat Sheet

Core Structure

 1class MyComponent extends HTMLElement {
 2  private abortController = new AbortController();
 3
 4  static get observedAttributes(): string[] {
 5    return ['attribute-name'];
 6  }
 7
 8  constructor() {
 9    super();
10    this.attachShadow({ mode: 'open' });
11    // State only - never access attributes here
12  }
13
14  connectedCallback(): void {
15    this.render();
16    this.setupEventListeners();
17  }
18
19  disconnectedCallback(): void {
20    this.abortController.abort();
21  }
22
23  attributeChangedCallback(
24    name: string,
25    oldValue: string | null,
26    newValue: string | null
27  ): void {
28    if (oldValue !== newValue && this.shadowRoot?.children.length) {
29      this.render();
30    }
31  }
32
33  private render(): void {
34    const sheet = new CSSStyleSheet();
35    sheet.replaceSync(this.getStyles());
36
37    const template = document.createElement('template');
38    template.innerHTML = this.getTemplate();
39
40    if (this.shadowRoot) {
41      this.shadowRoot.innerHTML = '';
42      this.shadowRoot.adoptedStyleSheets = [sheet];
43      this.shadowRoot.appendChild(template.content.cloneNode(true));
44    }
45  }
46
47  private getStyles(): string {
48    return `:host { display: block; }`;
49  }
50
51  private getTemplate(): string {
52    return `<slot></slot>`;
53  }
54
55  private setupEventListeners(): void {
56    const signal = this.abortController.signal;
57    // Add listeners with { signal }
58  }
59}
60
61if (!customElements.get('my-component')) {
62  customElements.define('my-component', MyComponent);
63}

Lifecycle

MethodWhen CalledUse For
constructor()Element createdAttach shadow DOM, init state
connectedCallback()Added to DOMRender, add listeners, fetch data
disconnectedCallback()Removed from DOMCleanup (abort listeners)
attributeChangedCallback()Observed attr changesReact to attribute updates

Attributes & Properties

 1// String attribute with default
 2get variant(): string {
 3  return this.getAttribute('variant') || 'default';
 4}
 5
 6// Boolean attribute
 7get disabled(): boolean {
 8  return this.hasAttribute('disabled');
 9}
10
11set disabled(value: boolean) {
12  value ? this.setAttribute('disabled', '') : this.removeAttribute('disabled');
13}

Event Cleanup with AbortController

 1private abortController = new AbortController();
 2
 3connectedCallback(): void {
 4  this.setupEventListeners();
 5}
 6
 7disconnectedCallback(): void {
 8  this.abortController.abort();
 9}
10
11private setupEventListeners(): void {
12  this.abortController.abort();
13  this.abortController = new AbortController();
14  const signal = this.abortController.signal;
15
16  this.shadowRoot?.querySelector('button')?.addEventListener(
17    'click',
18    () => this.handleClick(),
19    { signal }
20  );
21}

Custom Events

 1// Dispatch with bubbling through shadow DOM
 2this.dispatchEvent(new CustomEvent('event-name', {
 3  bubbles: true,
 4  composed: true,  // crosses shadow boundary
 5  detail: { key: value }
 6}));
 7
 8// Listen
 9element.addEventListener('event-name', (e) => {
10  console.log(e.detail.key);
11});

CSS Custom Properties for Theming

 1private getStyles(): string {
 2  return `
 3    :host {
 4      --component-bg: var(--bg, #ffffff);
 5      --component-text: var(--text, #1c1c1e);
 6    }
 7
 8    @media (prefers-color-scheme: dark) {
 9      :host {
10        --component-bg: var(--bg, #1f2937);
11        --component-text: var(--text, #f3f4f6);
12      }
13    }
14
15    .container {
16      background: var(--component-bg);
17      color: var(--component-text);
18    }
19  `;
20}

Override from outside:

Web Components Cheat Sheet

Foundations

Core Structure

 1class MyComponent extends HTMLElement {
 2  constructor() {
 3    super();
 4    this.attachShadow({ mode: 'open' });
 5  }
 6
 7  connectedCallback(): void {
 8    this.render();
 9  }
10
11  private render(): void {
12    const sheet = new CSSStyleSheet();
13    sheet.replaceSync(this.getStyles());
14
15    const template = document.createElement('template');
16    template.innerHTML = this.getTemplate();
17
18    if (this.shadowRoot) {
19      this.shadowRoot.innerHTML = '';
20      this.shadowRoot.adoptedStyleSheets = [sheet];
21      this.shadowRoot.appendChild(template.content.cloneNode(true));
22    }
23  }
24
25  private getStyles(): string {
26    return `:host { display: block; }`;
27  }
28
29  private getTemplate(): string {
30    return `<slot></slot>`;
31  }
32}

Lifecycle Methods

MethodWhen CalledUse For
constructor()Element createdAttach shadow DOM, initialize state
connectedCallback()Added to DOMRender, add event listeners, fetch data
disconnectedCallback()Removed from DOMCleanup listeners, abort requests
attributeChangedCallback()Observed attribute changesRe-render or update specific parts

Registration

1// Always guard against duplicate registration
2if (!customElements.get('my-component')) {
3  customElements.define('my-component', MyComponent);
4}

Element names must contain a hyphen: my-component, app-button, data-table.

Cloudflare Cheat Sheet

wrangler.toml

 1name = "my-site"
 2compatibility_date = "2025-09-24"
 3
 4[site]
 5bucket = "./public"
 6
 7[triggers]
 8crons = ["0 0 * * *"]   # daily at midnight UTC
 9
10# Bind the Rust Worker under /api/rust
11[[routes]]
12pattern = "example.com/api/rust/*"
13zone_name = "example.com"
14service = "rust-worker"

Build Section (esbuild Integration)

For projects with client-side TypeScript/JavaScript that needs bundling:

1[build]
2command = "node scripts/build.js --dev"
3watch_dir = "src/client"
OptionDescription
commandBuild command to run before starting/deploying
watch_dirDirectory to watch; triggers rebuild on changes

How it works: