### Infrastructure Setup Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/docs/patterns/isolated-vm-per-rl-rollout.md Illustrates the initial infrastructure setup for managing isolated VMs per rollout using Modal. This code is part of the setup for provisioning and managing the isolated environments. ```python from modal import Image, App, method import uuid ``` -------------------------------- ### Initial Project Setup Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/CLAUDE.md Commands to set up the project environment, including creating and activating a virtual environment, and installing dependencies. ```bash # Initial setup (run once) python -m venv venv # Create virtual environment source venv/bin/activate # Activate virtual environment (Linux/Mac) # venv\Scripts\activate # Activate virtual environment (Windows) make site_install # Install Python dependencies npm install # Install Node.js dependencies ``` -------------------------------- ### Agent VM Interaction Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/virtual-machine-operator-agent/card.html Demonstrates how an agent can interact with a virtual machine environment to install packages, execute Python scripts, read files, and manage code repositories. ```python vm.execute("pip install pandas matplotlib") vm.execute("python analyze_data.py") vm.read_file("/output/report.pdf") vm.execute("git add . && git commit -m 'Add report'") ``` -------------------------------- ### Dynamic Context Injection Examples Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/index.html Examples showing how to inject context dynamically using @mentions for files and slash commands for reusable prompts. ```text # File injection via @mention @src/components/Button.tsx # Slash command injection /user:deployment # Loads ~/.claude/commands/deployment.md # Both inject into agent context ``` -------------------------------- ### Prompt Template Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/docs/patterns/patch-steering-via-prompted-tool-selection.md Create reusable prompt templates with placeholders for task descriptions, preferred tools, and usage examples to standardize agent instructions. ```text "Task: {task_description}. Preferred tool: {tool_name}. Usage example: {tool_usage_snippet}." ``` -------------------------------- ### Serve Docs Locally Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/AGENT.md Starts a local web server to preview the documentation site at http://localhost:8000. ```bash make site_preview ``` -------------------------------- ### Example Output of 'make show_labels' Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/DEPLOYMENT.md This is an example of the output you can expect when running 'make show_labels', illustrating how new and updated patterns are identified and listed with their respective labels. ```bash # Example output from make show_labels 🆕 NEW patterns (2): - context-window-anxiety-management.md - proactive-agent-state-externalization.md 🔄 UPDATED patterns (4): - context-minimization-pattern.md - parallel-tool-execution.md - rich-feedback-loops.md - sub-agent-spawning.md ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/HELP.md Install or upgrade pip and then install all project dependencies listed in the requirements.txt file. This ensures all necessary libraries like mkdocs and mkdocs-material are available. ```bash pip install --upgrade pip pip install -r requirements.txt ``` -------------------------------- ### Teaching Tool Usage Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/tool-use-steering-via-prompting/card.html Use this prompt to teach the agent how to use a specific tool, including its command-line arguments or help options. ```text "Use our barley CLI to check logs. -h for help" ``` -------------------------------- ### File Injection Syntax Examples Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/dynamic-code-injection-on-demand-file-fetch/card.html Demonstrates the syntax for injecting entire files, specific line ranges, or summaries into the agent's context. ```shell "@path/to/file.ext" # Full file "/load file.ext:10-50" # Line range "/summarize test_spec.py" # Extract summary ``` -------------------------------- ### Context Minimization Pattern Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/index.html This example demonstrates a basic prompt structure for context minimization. It aims to reduce prompt injection risks by simplifying the prompt. ```python prompt = """ CONTEXT GUIDANCE: You have 200k+ tokens. Do NOT rush or summarize prematurely. """ + user_input + """ Remember: Context is NOT a constraint. """ ``` -------------------------------- ### System Prompt Evolution Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/progressive-autonomy-with-model-evolution/card.html Illustrates the reduction in system prompt complexity as models become more capable and internalize previous instructions. ```python # Before: 2000 tokens of instructions system_prompt_v1 = """Check file exists, read contents, plan changes, make minimal edits, verify syntax...""" # After: Model internalized the steps system_prompt_v2 = "Write clean, tested code." ``` -------------------------------- ### Example Shell Command Execution Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/shell-command-contextualization/card.html Demonstrates how a user might type a shell command prefixed with '!' and how the agent receives both the command and its output in the context. ```shell !git status ``` ```text # Command: git status # Output: On branch main, 2 files changed... ``` -------------------------------- ### Makefile Example for Claude CLI Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/docs/patterns/cli-native-agent-orchestration.md Demonstrates how to integrate Claude CLI commands into a Makefile for automating code generation and testing. ```bash # In your project Makefile generate-from-spec: claude spec run --input api.yaml --output src/ test-spec-compliance: claude spec test --spec api.yaml --codebase src/ ``` -------------------------------- ### Fallback Handling Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/docs/patterns/patch-steering-via-prompted-tool-selection.md Include a directive in the prompt to specify a fallback tool in case the primary tool fails or is not suitable. ```text If ASTRefactor fails, fallback to apply_patch. ``` -------------------------------- ### Implicit Tool Shortcut Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/tool-use-steering-via-prompting/card.html Use this prompt for learned associations where the agent can infer the correct tool usage from a common workflow or set of commands. ```text "commit, push, pr" # agent knows git workflow ``` -------------------------------- ### Direct Tool Invocation Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/docs/patterns/patch-steering-via-prompted-tool-selection.md Prepend instructions to directly specify the desired tool and its action. The agent recognizes the tool name for selection. ```text Use the `apply_patch` tool to insert a new function `validate_input` in `auth_service.py`. ``` -------------------------------- ### Example Configuration Options Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/docs/patterns/continuous-autonomous-task-loop-pattern.md Set iteration limits, CLI tool choice, rate limit backoff, and enable JSON streaming for progress tracking. ```bash # Example configuration MAX_ITERATIONS=50 # Safety limit CLAUDE_CLI="claude" # CLI tool choice RATE_LIMIT_BACKOFF=300 # Seconds to wait on rate limit STREAM_JSON=true # Real-time progress tracking ``` -------------------------------- ### Absolute Path for Assets Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/CLAUDE.md Example of correcting an image reference to use an absolute path starting with '/', ensuring assets load correctly on both local development and production deployments. ```markdown ![Image](/image.jpeg) ``` -------------------------------- ### Sequential Tool Call Bottleneck Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/docs/patterns/parallel-tool-call-learning.md Illustrates a scenario where sequential tool calls lead to significant latency. This pattern is slow because each tool must complete before the next one starts. ```text Sequential (slow): 1. search("Intel financial data") → 2s 2. read_file("2023_report.pdf") → 1.5s 3. search("return metrics") → 2s 4. read_file("returns_table.csv") → 1.5s Total: 7 seconds ``` -------------------------------- ### Verify MkDocs Installation Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/HELP.md Check if MkDocs has been installed correctly by running the version command. This confirms that the installation was successful and the command is accessible. ```bash mkdocs --version ``` -------------------------------- ### Virtual Machine Operator Agent Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/index.html This snippet illustrates an agent operating within a dedicated VM environment. It demonstrates executing shell commands for package installation, running Python scripts for analysis, reading output files, and performing Git operations. This pattern grants agents full computer operator capabilities for complex tasks requiring OS interaction. ```python # Agent operating in VM environment vm.execute("pip install pandas matplotlib") vm.execute("python analyze_data.py") vm.read_file("/output/report.pdf") vm.execute("git add . && git commit -m 'Add report'") # Agent has full computer operator capability ``` -------------------------------- ### Agent Run Example with Goal and Tools Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/inversion-of-control/card.html Initiates an agent task by providing a high-level goal, a list of available tools, and specific guardrails. The agent then determines the execution steps. ```python agent.run( goal="Refactor UploadService to async", tools=[grep, edit_file, run_tests, git], guardrails=["no prod DB access", "tests must pass"] ) ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/AGENT.md Installs the necessary Python packages for the project. ```bash make site_install ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/DEPLOYMENT.md Installs all necessary Python packages listed in the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/DEPLOYMENT.md Installs Node.js packages required for local testing with Cloudflare Wrangler. ```bash npm install ``` -------------------------------- ### Example Feature Branch Naming Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/HELP.md This is an example of how to name a feature branch when adding multiple patterns or scripts. ```bash git checkout -b add-inversion-of-control-pattern ``` -------------------------------- ### Activate Virtual Environment and Preview Site Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/DEPLOYMENT.md Locally serve the site for development and testing. Changes are automatically reloaded. Press Ctrl+C to stop the server. Ensure the virtual environment is activated first. ```bash source venv/bin/activate make site_preview ``` -------------------------------- ### Standard Agent RFT Training Setup Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/docs/patterns/parallel-tool-call-learning.md Shows a typical Reinforcement Learning from Human Feedback (RFT) training job creation using the OpenAI client. No specific flags are needed to enable parallelization; it emerges naturally. ```python # Standard Agent RFT setup job = client.fine_tuning.jobs.create( training_file="file-abc123", model="gpt-4o", method="rft", rft={ "tools": tools, "grader": grader, "hyperparameters": { "n_epochs": 3, "batch_size": 16, "compute_multiplier": 1 } } ) # No special "parallelization" flag needed! ``` -------------------------------- ### Project Structure and Session Ritual Example (Shell) Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/initializer-maintainer-dual-agent/card.html Shows the typical project file structure created by the Initializer and the command ritual for a Maintainer session. ```shell # Initializer creates foundation project/ feature-list.json # All features, passes=false progress.txt # Running log init.sh # One-command bootstrap # Maintainer session ritual $ ./init.sh && read_progress && implement_next ``` -------------------------------- ### Agent Code Generation Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/democratization-of-tooling-via-agents/card.html Illustrates the output from the AI agent, which is a Python script for creating a dashboard. This is followed by an example of user iteration. ```plaintext # Agent generates: dashboard.py # User iterates: "Add export to CSV" ``` -------------------------------- ### Deploy with New System Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/MIGRATION-TO-GIT-LABELS.md Run this make command to deploy the project using the new automated git-based labeling system. ```bash make deploy_auto ``` -------------------------------- ### Agent RFT Training Setup Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/docs/patterns/agent-reinforcement-fine-tuning.md This snippet demonstrates how to set up and initiate an Agent Reinforcement Fine-Tuning job using the OpenAI client. It includes defining tools with hosted endpoints, configuring a grader (model-based or endpoint-based), and creating the fine-tuning job with specified hyperparameters. ```python from openai import OpenAI client = OpenAI() # 1. Define your tools with hosted endpoints tools = [ { "name": "search", "url": "https://your-tools.modal.run/search", "headers": {"Authorization": "Bearer YOUR_TOKEN"} }, { "name": "read_file", "url": "https://your-tools.modal.run/read_file", "headers": {"Authorization": "Bearer YOUR_TOKEN"} } ] # 2. Define your grader (model-based or endpoint-based) grader = { "type": "model", # or "endpoint" for custom grading logic "model": "gpt-4o", "response_format": { "type": "json_schema", "json_schema": { "name": "grader_response", "schema": { "type": "object", "properties": { "score": {"type": "number"}, # 0.0 to 1.0 "reasoning": {"type": "string"} } } } }, "prompt": """ Evaluate the agent's answer based on: 1. Correctness vs ground truth 2. Completeness of reasoning Ground truth: {ground_truth} Agent answer: {final_answer} Provide score (0-1) and reasoning. """ } # 3. Start fine-tuning job job = client.fine_tuning.jobs.create( training_file="file-abc123", model="gpt-4o-2024-08-06", method="rft", rft={ "tools": tools, "grader": grader, "hyperparameters": { "n_epochs": 3, "batch_size": 16, "compute_multiplier": 1 # Exploration factor } } ) ``` -------------------------------- ### DSL Example for Code-Then-Execute Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/code-then-execute-pattern/card.html This DSL example demonstrates reading data, formatting it, and writing an email. It includes a comment indicating a static check for tainted variables. ```plaintext x = calendar.read(today) y = QuarantineLLM.format(x) email.write(to="john@acme.com", body=y) # Static check: tainted var can't reach recipient ``` -------------------------------- ### Quick Context Compressor Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/disposable-scaffolding-over-durable-features/card.html Illustrates building a temporary, simple solution expected to become obsolete. This function is intended to be replaced by more advanced model capabilities in the future. ```python def quick_context_compressor(text): """Expect this to be obsolete by Q2""" return simple_summarize(text) ``` -------------------------------- ### Building and Deployment Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/CLAUDE.md Commands for building the static site and deploying it to GitHub Pages or Cloudflare Workers. ```bash # Building and deployment make site_build # Build static site to site/ directory make site_deploy # Deploy to GitHub Pages npx wrangler deploy # Deploy to Cloudflare Workers (recommended) ``` -------------------------------- ### Example Shell Command for File Search Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/docs/patterns/curated-file-context-window.md Use ripgrep to search for specific symbols or keywords within Java files. This is an example of how a sub-agent might initiate a search. ```shell rg "signup" -tjava ``` -------------------------------- ### Tool Usage Teaching Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/docs/patterns/patch-steering-via-prompted-tool-selection.md Provide a mini-manual within the prompt to educate the agent on specific tool usage and preferred scenarios. This encourages the use of safer, higher-level tools. ```text "Our `ASTRefactor` tool takes JSON describing node edits: {"file": string, "pattern": string, "replacement": string}. Use it for safe refactors rather than raw `sed` commands." ``` -------------------------------- ### Progressive Tool Discovery Workflow Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/progressive-tool-discovery/card.html Demonstrates the progressive discovery workflow, starting with listing directories, searching for tools with specific details, and then fetching the full tool schema when required. ```python # Progressive discovery workflow servers = list_directory("./servers/") # names only tools = search_tools("google-drive/*", detail="name+description") schema = get_tool_definition( "servers/google-drive/getDocument" ) # full JSON schema when needed ``` -------------------------------- ### Synthesis Agent Prompt Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/memory-synthesis-from-execution-logs/card.html This is an example prompt for a synthesis agent. It instructs the agent to review task diaries, identify frequent patterns, and output rules, commands, and tests. ```python # Synthesis prompt synthesis_agent(""" Review 50 task diaries. Find patterns appearing 3+ times. Output: rules, commands, tests """) ``` -------------------------------- ### Agent RFT Training Setup Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/patterns/agent-reinforcement-fine-tuning.md Set up an Agent RFT training job by defining tools with hosted endpoints, a grader for evaluating agent performance, and initiating the fine-tuning job with specified hyperparameters. ```python # Agent RFT Training Setup from openai import OpenAI client = OpenAI() # 1. Define your tools with hosted endpoints tools = [ { "name": "search", "url": "https://your-tools.modal.run/search", "headers": {"Authorization": "Bearer YOUR_TOKEN"} }, { "name": "read_file", "url": "https://your-tools.modal.run/read_file", "headers": {"Authorization": "Bearer YOUR_TOKEN"} } ] # 2. Define your grader (model-based or endpoint-based) grader = { "type": "model", # or "endpoint" for custom grading logic "model": "gpt-4o", "response_format": { "type": "json_schema", "json_schema": { "name": "grader_response", "schema": { "type": "object", "properties": { "score": {"type": "number"}, # 0.0 to 1.0 "reasoning": {"type": "string"} } } } }, "prompt": """ Evaluate the agent's answer based on: 1. Correctness vs ground truth 2. Completeness of reasoning Ground truth: {ground_truth} Agent answer: {final_answer} Provide score (0-1) and reasoning. """ } # 3. Start fine-tuning job job = client.fine_tuning.jobs.create( training_file="file-abc123", model="gpt-4o-2024-08-06", method="rft", rft={ "tools": tools, "grader": grader, "hyperparameters": { "n_epochs": 3, "batch_size": 16, "compute_multiplier": 1 # Exploration factor } } ) ``` -------------------------------- ### Sales Team Prompt Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/pattern-snippets/patterns/democratization-of-tooling-via-agents/card.html Example of a natural language prompt from a sales team member requesting a dashboard with specific filters. This illustrates the input expected by the AI agent. ```plaintext "Create a dashboard that shows my weekly pipeline from Salesforce, with filters by deal stage" ``` -------------------------------- ### Synthesis Agent Prompt Example Source: https://github.com/esc5221/awesome-agentic-patterns/blob/main/patterns/memory-synthesis-from-execution-logs.md A pseudo-code example of a prompt for a synthesis agent, instructing it to review task diaries and extract recurring patterns. It specifies the desired output format for each identified pattern. ```pseudo synthesis_agent.prompt = """ Review these 50 task diaries. Identify patterns that appear in 3+ tasks. For each pattern, suggest: - A general rule to add to CLAUDE.md - A potential slash command - A test case to prevent regression """ ```