### Run App Locally with Docker Compose Source: https://github.com/appdotbuild/agent/blob/main/agent/nicegui_agent/template/README.md This snippet demonstrates how to start the application locally using Docker Compose. It assumes the Dockerfile and docker-compose.yml are set up correctly in the project root. ```bash docker compose up ``` -------------------------------- ### Bash Ollama Setup and Model Pull Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Provides bash commands to install Ollama, pull recommended models like Ministral, Codestral, and LLaMA 3.2 Vision, and optionally pull advanced models such as Qwen3-Coder and Qwen3. ```Bash # Install Ollama curl -fsSL https://ollama.ai/install.sh | sh # Pull recommended models ollama pull ministral # Fast tasks ollama pull codestral:22b # Code generation ollama pull llama3.2-vision # Vision tasks # Optional: Advanced models ollama pull qwen3-coder:7b # Excellent coding ollama pull qwen3:30b # Advanced reasoning ``` -------------------------------- ### Run Docker Container Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Starts a Docker container from the 'agent:latest' image and maps port 8000 from the container to the host machine. This allows interaction with the running agent. ```Shell docker run --rm -p 8000:8000 agent:latest ``` -------------------------------- ### Generating Apps with Specific Templates Source: https://github.com/appdotbuild/agent/blob/main/CONTRIBUTING.md Demonstrates how to generate applications using specific templates by providing a description and a template ID to the 'uv run generate' command. Examples include creating a stock portfolio dashboard and a presentation website. ```bash uv run generate "make a dashboard showing my current stock portfolio value using up to date prices from yfinance" --template_id "nicegui_agent" ``` ```bash uv run generate "make a presentation-like website with multiple pages with content and next buttons on each. last page mush show a counter that increments each time this presentation has been shown" --template_id "laravel_agent" ``` -------------------------------- ### Interactive Debugging with Local Server Source: https://github.com/appdotbuild/agent/blob/main/CONTRIBUTING.md Instructions for running the interactive debug client with a local server. This involves starting the client with specified host and port, interacting with the app, and then applying changes and setting up a Docker environment for the database. ```bash uv run interactive --host yourhostname --port 80 ``` -------------------------------- ### Run App Locally with Docker Compose Source: https://github.com/appdotbuild/agent/blob/main/agent/trpc_agent/template/README.md This command initiates the local development environment for the application using Docker Compose. Ensure Docker is installed and running before executing this command. ```bash docker compose up ``` -------------------------------- ### Bash Environment Configuration for LLM Models Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Demonstrates how to configure LLM models and API keys using a .env file. It includes examples for setting default models, alternative models, and API keys for cloud services like Anthropic and Google Gemini. ```Bash # Recommended: Latest non-Chinese models (2025) LLM_FAST_MODEL=ministral # Mistral 3B LLM_CODEGEN_MODEL=codestral # Mistral 22B LLM_VISION_MODEL=llama3.2-vision # Meta Vision # Alternative: All-American models # LLM_FAST_MODEL=phi4 # Microsoft 14B # LLM_CODEGEN_MODEL=granite-code # IBM 20B # LLM_VISION_MODEL=llama3.2-vision # Meta Vision # For highest performance (includes Chinese models) # LLM_CODEGEN_MODEL=qwen3-coder # Best for coding # LLM_VISION_MODEL=qwen3 # Advanced vision + thinking # API Keys (if using cloud models) ANTHROPIC_API_KEY=your_key_here GEMINI_API_KEY=your_key_here OLLAMA_HOST=http://localhost:11434 ``` -------------------------------- ### Quick Start: Docker Production Deployment Source: https://github.com/appdotbuild/agent/blob/main/agent/laravel_agent/template/DOCKER_README.md This snippet outlines the initial steps to set up and run the Dockerized Laravel application. It includes creating an environment file, generating an application key, setting environment variables, building the Docker images, and running the application in detached mode. ```bash cp .env.example .env php artisan key:generate # Set your environment variables APP_KEY=your-generated-key-here DB_PASSWORD=your-secure-database-password REDIS_PASSWORD=your-secure-redis-password docker-compose up -d --build docker-compose exec app php artisan migrate --force ``` -------------------------------- ### Python Pytest Fixture and Test Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Provides an example of writing tests using `pytest`, including defining a fixture for reusable test data (`sample_data`) and a test function (`test_process_request_with_valid_data`) that asserts expected behavior. ```python import pytest from your_module import process_request # Assuming process_request is defined elsewhere @pytest.fixture def sample_data(): return {"key": "value"} def test_process_request_with_valid_data(sample_data): result = process_request(sample_data) assert result["status"] == "success" ``` -------------------------------- ### TypeScript: Zod Schemas and Interfaces for User Data Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Demonstrates defining Zod schemas for runtime validation and inferring TypeScript interfaces from them. Includes best practices for type exports and an example of a function to update user data. ```typescript import { z } from 'zod'; // Define Zod schema for runtime validation export const userPreferencesSchema = z.object({ theme: z.enum(['light', 'dark']), notifications: z.boolean(), }); // Define interface using inferred type from Zod export type UserPreferences = z.infer; // Define main interface export interface User { id: string; name: string; email: string; preferences?: UserPreferences; } // Define Zod schema for User export const userSchema = z.object({ id: z.string().uuid(), name: z.string().min(1), email: z.string().email(), preferences: userPreferencesSchema.optional(), }); // Type for function arguments function updateUser(user: User, updates: Partial): User { // Zod validation can be added here if needed // const validatedUpdates = userSchema.partial().parse(updates); return { ...user, ...updates }; } ``` -------------------------------- ### React: Functional Component with Props and Styling Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Provides an example of a functional React component (`Button`) that accepts props, including a label, an onClick handler, and an optional disabled state. It demonstrates prop destructuring and type definition using an interface. ```typescript import React from 'react'; // Assuming React is used // import styles from './styles.module.css'; // Example CSS Modules interface ButtonProps { label: string; onClick: () => void; disabled?: boolean; } function Button({ label, onClick, disabled = false }: ButtonProps): JSX.Element { return ( ); } ``` -------------------------------- ### React: State Management with `useReducer` Hook Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Shows a basic example of using the `useReducer` hook in React for state management. It outlines how to dispatch actions to update the state, following best practices for managing complex global state. ```javascript // Assume reducer, initialState are defined // const [state, dispatch] = useReducer(reducer, initialState); // // Later in component // dispatch({ type: 'UPDATE_USER', payload: { id, data } }); ``` -------------------------------- ### TypeScript React Component Testing with Jest Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Provides an example of testing React components using Jest and React Testing Library. It covers rendering components, asserting the presence of text, and simulating user interactions like button clicks. ```TypeScript // import { render, screen, fireEvent } from '@testing-library/react'; // import { UserProfile } from './UserProfile'; // Example component // const mockUser = { id: '1', name: 'Test User', email: 'test@example.com' }; // test('displays user information correctly', () => { // render(); // expect(screen.getByText(mockUser.name)).toBeInTheDocument(); // expect(screen.getByText(mockUser.email)).toBeInTheDocument(); // // Example interaction // // fireEvent.click(screen.getByRole('button', { name: /Edit Profile/i })); // // expect(screen.getByTestId('edit-form')).toBeInTheDocument(); // }); ``` -------------------------------- ### Integrate React-X and React-DOM ESLint Plugins (JavaScript) Source: https://github.com/appdotbuild/agent/blob/main/agent/trpc_agent/template/client/README.md This code demonstrates how to integrate the `eslint-plugin-react-x` and `eslint-plugin-react-dom` plugins into your ESLint configuration. It includes adding the plugins and enabling their recommended TypeScript and general rules for enhanced React linting. ```JavaScript // eslint.config.js import reactX from 'eslint-plugin-react-x' import reactDom from 'eslint-plugin-react-dom' export default tseslint.config({ plugins: { // Add the react-x and react-dom plugins 'react-x': reactX, 'react-dom': reactDom, }, rules: { // other rules... // Enable its recommended typescript rules ...reactX.configs['recommended-typescript'].rules, ...reactDom.configs.recommended.rules, }, }) ``` -------------------------------- ### Production Environment Variables Configuration Source: https://github.com/appdotbuild/agent/blob/main/agent/laravel_agent/template/DOCKER_README.md This snippet details the essential environment variables required for a production setup of the Laravel application. It covers application settings, database credentials, cache/session drivers, and Redis configuration. ```env # Application APP_NAME="Your App Name" APP_ENV=production APP_KEY=base64:your-32-character-key-here APP_DEBUG=false APP_URL=https://yourdomain.com # Database DB_CONNECTION=pgsql DB_HOST=postgres DB_PORT=5432 DB_DATABASE=laravel DB_USERNAME=laravel DB_PASSWORD=your-secure-password # Cache & Sessions CACHE_STORE=redis SESSION_DRIVER=redis QUEUE_CONNECTION=redis # Redis REDIS_HOST=redis REDIS_PASSWORD=your-redis-password REDIS_PORT=6379 ``` -------------------------------- ### Expand ESLint with Type-Checked Rules (TypeScript) Source: https://github.com/appdotbuild/agent/blob/main/agent/trpc_agent/template/client/README.md This snippet shows how to configure ESLint to enable type-aware lint rules for a TypeScript project. It involves extending the ESLint configuration with recommended, stricter, or stylistic type-checked rules and specifying project configuration files. ```JavaScript export default tseslint.config({ extends: [ // Remove ...tseslint.configs.recommended and replace with this ...tseslint.configs.recommendedTypeChecked, // Alternatively, use this for stricter rules ...tseslint.configs.strictTypeChecked, // Optionally, add this for stylistic rules ...tseslint.configs.stylisticTypeChecked, ], languageOptions: { // other options... parserOptions: { project: ['./tsconfig.node.json', './tsconfig.app.json'], tsconfigRootDir: import.meta.dirname, }, }, }) ``` -------------------------------- ### Python LLM Client Initialization Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Shows how to initialize clients for different LLM categories (Fast Text, Code Generation, Vision) using utility functions provided by the llm library. It highlights the recommended usage for accessing default clients. ```Python from llm.utils import get_fast_text_client, get_best_codegen_client, get_vision_client from llm.models_config import ModelCategory # Recommended usage - these use current defaults fast_client = get_fast_text_client() # Uses Ministral 3B codegen_client = get_best_codegen_client() # Uses Codestral 22B vision_client = get_vision_client() # Uses LLaMA 3.2 Vision ``` -------------------------------- ### Python LLM Client Imports Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Demonstrates how to import LLM client functions from the `llm.utils` module in Python. It shows both legacy and new recommended import names, as well as a category-based approach for fetching clients. ```Python from llm.utils import get_fast_llm_client, get_codegen_llm_client, get_vision_llm_client # New recommended names (same functionality) from llm.utils import get_fast_text_client, get_best_codegen_client, get_vision_client # Or use the category-based approach from llm.utils import get_llm_client_by_category from llm.models_config import ModelCategory client = get_llm_client_by_category(ModelCategory.BEST_CODEGEN) ``` -------------------------------- ### Format Code (Python) Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Applies code formatting rules to the project using the Ruff formatter. Assumes the 'uv' package management tool is used for running commands. ```Shell uv run ruff format ``` -------------------------------- ### Python Imports Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Demonstrates the recommended order for Python imports: standard library, third-party libraries, and then local project imports. This promotes readability and maintainability. ```python import json import os from typing import Dict, List, Optional import anyio import pytest from agent.core import BaseClass from agent.log import get_logger ``` -------------------------------- ### Python Type Annotations and TypedDict Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Shows how to use Python's type hinting features, including `TypedDict` for structured data and union types (`|`) for optional parameters. This enhances code clarity and enables static analysis. ```python from typing import TypedDict, Any class Result(TypedDict): status: str data: Any def process_request(data: Dict[str, Any], timeout: float | None = None) -> Result: """ Process the incoming request data. Args: data: The request data to process timeout: Optional timeout in seconds Returns: Result object containing processed data """ # ... implementation ... return {"status": "success", "data": {}} ``` -------------------------------- ### Build Docker Image Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Creates a Docker image tagged as 'agent:latest' from the current project directory. This image is used for deploying or running the agent. ```Shell docker build -t agent:latest . ``` -------------------------------- ### Agent Commands with uv Source: https://github.com/appdotbuild/agent/blob/main/CONTRIBUTING.md This section details various commands that can be executed using the 'uv run' command from the agent directory. These commands cover running tests, linting code, updating caches, generating applications, and launching an interactive debug client. ```bash uv run test ``` ```bash uv run test_e2e ``` ```bash uv run lint ``` ```bash uv run update_cache ``` ```bash uv run generate "my app description" ``` ```bash uv run interactive ``` -------------------------------- ### Run All Tests (Python) Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Executes all tests within the agent project using the pytest framework. Assumes the 'uv' package management tool is used for running commands. ```Shell uv run pytest -v . ``` -------------------------------- ### Shell Commands for Running Provider-Agnostic Tests Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Demonstrates how to execute pytest tests with different LLM providers by setting environment variables like `PREFER_OLLAMA`, `GEMINI_API_KEY`, or `ANTHROPIC_API_KEY`. It also shows the expected behavior when no provider is configured (tests are skipped). ```Shell # Run tests with Ollama PREFER_OLLAMA=1 uv run pytest tests/test_e2e.py # Run tests with Gemini GEMINI_API_KEY=your_key uv run pytest tests/test_e2e.py # Run tests with Anthropic ANTHROPIC_API_KEY=your_key uv run pytest tests/test_e2e.py # Tests are skipped when no provider is configured uv run pytest tests/test_e2e.py # SKIPPED ``` -------------------------------- ### Configure LLM Models (Bash) Source: https://github.com/appdotbuild/agent/blob/main/README.md Demonstrates how to configure different Large Language Models (LLMs) for the app.build agent using environment variables. Supports local models via Ollama/LMStudio and cloud providers like OpenAI, Anthropic, Gemini, and OpenRouter. ```Bash # Local (Ollama and LMStudio supported) LLM_BEST_CODING_MODEL=ollama:devstral LLM_UNIVERSAL_MODEL=lmstudio:[host] # just lmstudio: works too # Cloud providers OPENROUTER_API_KEY=your-key LLM_BEST_CODING_MODEL=openrouter:deepseek/deepseek-coder # Defaults: LLM_BEST_CODING_MODEL=anthropic:claude-sonnet-4-20250514 # code generation LLM_UNIVERSAL_MODEL=gemini:gemini-2.5-flash-preview-05-20 # universal model, chat with user LLM_ULTRA_FAST_MODEL=gemini:gemini-2.5-flash-lite-preview-06-17 # commit generation etc. LLM_VISION_MODEL=gemini:gemini-2.5-flash-lite-preview-06-17 # vision model for UI validation ``` -------------------------------- ### Lint Code (Python) Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Checks the codebase for style violations and potential errors using the Ruff linter. Assumes the 'uv' package management tool is used for running commands. ```Shell uv run ruff check ``` -------------------------------- ### Run Tests in Isolated Environment (Docker) Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Builds a Docker image specifically for testing the agent and then runs a container from that image. This ensures tests are executed in a clean, isolated environment. ```Shell docker build --target test -t agent-test:latest . docker run --rm agent-test:latest ``` -------------------------------- ### tRPC: API Integration with Zod Input Validation Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Illustrates integrating with tRPC, focusing on defining router schemas with Zod for input validation and implementing a query procedure for fetching user data. Includes error handling best practices. ```typescript import { z } from 'zod'; // Assume setup for router, procedure, TRPCError, and ctx (context) exists // import { router, procedure, TRPCError } from '../trpc'; // import { db } from '../db'; // Example database context export const userRouter = router({ getUser: procedure .input(z.object({ id: z.string() })) .query(async ({ input, ctx }) => { try { // Replace with actual data fetching logic // return await ctx.db.user.findUnique({ where: { id: input.id } }); return { id: input.id, name: 'Dummy User' }; // Example return } catch (error) { console.error("Failed to fetch user:", error); // Use proper logging throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Failed to fetch user', // cause: error, // Optional: include original error }); } }), }); ``` -------------------------------- ### Shell Environment Variable for Ollama Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Shows how to set the `OLLAMA_HOST` environment variable in a `.env` file to configure the agent to use a local Ollama instance. ```Shell OLLAMA_HOST=http://localhost:11434 ``` -------------------------------- ### TypeScript Imports and Schema Validation Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Shows a typical import order for a TypeScript project, including potential React imports, third-party libraries like `zod`, utility functions, and type definitions. It highlights the use of `zod` for schema validation. ```typescript // import React, { useState, useEffect } from 'react'; // If using React import { z } from 'zod'; // import { trpc } from 'trpc'; // If using tRPC client // import { Button } from '../components/Button'; // If using React components import { formatData } from '../utils/formatter'; import type { User, UserPreferences } from '../types'; // import styles from './styles.module.css'; // If using CSS Modules ``` -------------------------------- ### SSE Message Handling Enhancement (Python) Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Addresses a double-JSON-encoding issue in Server-Sent Events (SSE) by updating data models and message handling logic. It introduces structured message fields and enhances display formatting for interactive clients. ```Python # Model Changes: Updated AgentMessage to use structured messages field # from typing import List, Literal # from datetime import datetime # # class ExternalContentBlock: # content: str # timestamp: datetime # role: Literal["assistant"] # # class AgentMessage: # messages: List[ExternalContentBlock] # content: str # Deprecated for legacy clients # Agent Session: Modified send_event() to populate both fields # async def send_event(self, ...): # # ... existing logic ... # structured_messages = [...] # Populate from new data # json_string_messages = json.dumps([m.__dict__ for m in structured_messages]) # For legacy # self.response.add_event(data={'messages': structured_messages, 'content': json_string_messages}) # Interactive Client: Enhanced print_event() function # def print_event(event): # if 'messages' in event and event['messages']: # for msg in event['messages']: # timestamp = msg['timestamp'].strftime('%H:%M:%S') # print(f"[{timestamp}] {msg['content']}") # elif 'content' in event: # print(event['content']) # Fallback for legacy ``` -------------------------------- ### Python Custom Exception and Error Handling Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Demonstrates defining custom exceptions (e.g., `InvalidDataError`) and implementing robust error handling using `try...except` blocks with specific exception types and logging. It emphasizes logging exceptions with context. ```python from agent.log import get_logger logger = get_logger(__name__) class InvalidDataError(ValueError): pass async def process_data(input_data): # ... processing ... if not valid: raise InvalidDataError("Input data failed validation") return processed_data async def handle_request(input_data): try: result = await process_data(input_data) except InvalidDataError as e: logger.exception("Invalid data format received") # Re-raise or handle specific error raise except Exception as e: logger.exception("An unexpected error occurred during processing") # Handle generic error raise ``` -------------------------------- ### Troubleshooting: Permission Issues Source: https://github.com/appdotbuild/agent/blob/main/agent/laravel_agent/template/DOCKER_README.md This snippet addresses a common troubleshooting step for Dockerized applications, specifically focusing on resolving permission issues. It highlights the need to ensure that storage directories within the application container are writable. ```bash # Ensure storage directories are writable # (This is a conceptual step, actual commands depend on container setup) ``` -------------------------------- ### Deployment Commands: Docker Source: https://github.com/appdotbuild/agent/blob/main/agent/laravel_agent/template/DOCKER_README.md This snippet provides essential Docker commands for managing the production deployment. It includes building the application image, running with a custom environment file, viewing logs, executing Artisan commands within the container, and scaling the application. ```bash # Build only the application image docker build -t your-app . # Run with custom environment file docker-compose --env-file .env.production up -d # View logs docker-compose logs -f app # Run artisan commands docker-compose exec app php artisan migrate docker-compose exec app php artisan config:cache docker-compose exec app php artisan route:cache docker-compose exec app php artisan view:cache # Scale the application docker-compose up -d --scale app=3 ``` -------------------------------- ### Python Async Task Group Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Illustrates the use of `anyio.create_task_group` for managing concurrent asynchronous operations. This is the preferred method for grouping related async tasks in the project. ```python async with anyio.create_task_group() as tg: tg.start_soon(task_1) tg.start_soon(task_2) ``` -------------------------------- ### VCR Testing with Replay Mode Source: https://github.com/appdotbuild/agent/blob/main/CONTRIBUTING.md This command executes tests using pytest with the LLM_VCR_CACHE_MODE set to 'replay'. This mode utilizes cached LLM responses for testing, avoiding actual API calls. ```bash LLM_VCR_CACHE_MODE=replay uv run pytest . ``` -------------------------------- ### VCR Testing with Record Mode Source: https://github.com/appdotbuild/agent/blob/main/CONTRIBUTING.md This command executes tests using pytest with the LLM_VCR_CACHE_MODE set to 'record'. This mode makes real API calls and saves the LLM responses to a cache file, which is useful for updating test data after prompt or logic changes. ```bash LLM_VCR_CACHE_MODE=record uv run pytest . ``` -------------------------------- ### TypeScript Error Handling with Custom Errors Source: https://github.com/appdotbuild/agent/blob/main/PROJECT_GUIDELINES.md Demonstrates robust error handling in TypeScript using try-catch blocks, custom error classes like ApiError, and checks for different error types. It includes logging for unexpected errors and handling for unknown error types. ```TypeScript class ApiError extends Error { constructor(message: string) { super(message); this.name = 'ApiError'; } } async function fetchData() { // ... fetch logic that might throw ... } async function process() { let data; let error = null; try { data = await fetchData(); } catch (err) { if (err instanceof ApiError) { error = `API Error: ${err.message}`; } else if (err instanceof Error) { error = `An unexpected error occurred: ${err.message}`; console.error(err); // Use proper logging } else { error = 'An unknown error occurred'; console.error(err); } } // ... handle data or error ... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.