Home

Cheatsheets

Cheatsheets

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

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"

Folder structure

.
├── wrangler.toml                # main site config
├── public/
│   └── index.html               # static site root
├── functions/                   # best for small APIs tied to the site
│   ├── api/
│   │   └── hello.ts             # /api/hello
│   ├── auth/
│   │   └── login.ts             # /auth/login
│   └── health.ts                # /health
├── worker.ts                    # cron job handler (JS/TS)
└── rust-worker/                 # separate Worker (best for heavier/isolated services)
    ├── Cargo.toml
    ├── wrangler.toml
    └── src/
        └── lib.rs

Pages Functions routing