# zo > A blazing fast CLI tool for AI interaction ## Code Review Examples Learn how to use zo for effective code reviews. ### Basic Code Review #### Review Current Changes ```bash git diff | zo 'Review these changes for: - Bugs - Performance issues - Security concerns - Best practices' ``` #### Review Specific File ```bash zo @src/main.rs 'Code review with focus on: - Error handling - Memory safety - Performance - Code clarity' ``` #### Review Multiple Files ```bash zo @header.h @impl.c 'Review these files and check: - Header/implementation consistency - Memory leaks - Buffer overflows - API design' ``` ### Using Custom Reviewer Model #### Setup ```toml # ~/.config/zo/config.toml [[custom_models]] name = "reviewer" model = "anthropic/claude-sonnet-4.5" system_prompt = """You are a senior code reviewer with 15 years of experience. Focus on: 1. Bugs and logical errors 2. Performance and optimization opportunities 3. Security vulnerabilities 4. Code readability and maintainability 5. Best practices and design patterns 6. Test coverage Provide: - Severity level (Critical/High/Medium/Low) - Specific line references when possible - Concrete suggestions with code examples - Positive feedback for good practices """ ``` #### Usage ```bash # Quick review zo /reviewer @src/auth.rs # Detailed review git diff | zo /reviewer 'Thorough code review' # PR review git diff main...feature | zo /reviewer 'Review this pull request' ``` ### Review by Language #### Rust Code Review ```bash zo @lib.rs "Review this Rust code for: - Lifetime issues - Unsafe code usage - Error handling patterns - Idiomatic Rust - Performance (unnecessary clones, allocations) - Documentation quality" ``` #### Python Code Review ```bash zo @app.py "Review this Python code for: - PEP 8 compliance - Type hints usage - Error handling - Security (SQL injection, XSS) - Performance (list comprehensions vs loops) - Documentation and docstrings" ``` #### JavaScript/TypeScript Review ```bash zo @component.tsx "Review this React component for: - TypeScript type safety - React best practices - Performance (unnecessary re-renders) - Accessibility - Error boundaries - Testing considerations" ``` #### Go Code Review ```bash zo @handler.go "Review this Go code for: - Error handling patterns - Goroutine safety - Resource cleanup (defer usage) - Context usage - Package design - Testing approach" ``` ### Specific Review Focus #### Security Review ```bash zo @api.js "Security review focusing on: - Input validation - SQL injection risks - XSS vulnerabilities - Authentication/authorization - Sensitive data exposure - CSRF protection - Rate limiting" ``` #### Performance Review ```bash zo @query.sql "Performance review: - Query optimization - Index usage - N+1 query problems - Expensive operations - Caching opportunities - Scalability concerns" ``` #### Architecture Review ```bash zo @main.rs @lib.rs @types.rs "Architecture review: - Separation of concerns - Dependency management - Interface design - Scalability - Maintainability - Testing strategy" ``` ### Git Integration #### Staged Changes Review ```bash git diff --cached | zo /reviewer "Review my staged changes before commit" ``` #### Commit Review ```bash git show HEAD | zo 'Review this commit and suggest improvements' ``` #### Branch Comparison ```bash git diff main...feature | zo /reviewer "Compare feature branch with main" ``` #### PR Review with Context ```bash git diff main...feature > changes.diff git log main...feature --oneline > commits.txt zo @changes.diff @commits.txt "Review this PR: - Are the changes cohesive? - Is this ready to merge? - Any concerns or suggestions?" ``` ### Interactive Review with Chat #### Full Review Session ```bash zo --chat @src/complex.rs "Let's do a detailed code review" > What are the main issues? > How can I improve the error handling? > Are there any edge cases I'm missing? > What about testing? > exit ``` #### Refactoring Discussion ```bash zo --chat @legacy.py "Let's refactor this code" > What are the biggest problems? > How should I restructure this? > Show me the refactored version > What tests should I add? > exit ``` ### Automated Review Workflows #### CI/CD Integration ```bash #!/bin/bash # In your CI pipeline # Review changed files git diff origin/main...HEAD | zo /reviewer "Review for merge" > review.txt # Create comment with review cat review.txt ``` ### Review Checklists #### Backend API Review ```bash zo @api.rs "Review this API endpoint for: □ Input validation □ Authentication/authorization □ Error handling □ Logging □ Rate limiting □ Database transaction handling □ Response format consistency □ API documentation □ Testing" ``` #### Frontend Component Review ```bash zo @Button.tsx "Review this component for: □ TypeScript types □ Props validation □ Accessibility (ARIA labels, keyboard nav) □ Responsive design □ Error states □ Loading states □ Performance (memo, callback) □ Testing □ Documentation" ``` #### Database Migration Review ```bash zo @migration.sql "Review this migration for: □ Backward compatibility □ Index creation strategy □ Data integrity constraints □ Performance impact □ Rollback plan □ Default values □ NULL handling" ``` ### Advanced Review Techniques #### Diff with Context ```bash # Show more context in diff git diff -U10 | zo /reviewer "Review with extended context" ``` #### Review Specific Commits ```bash # Review last 3 commits git log -3 -p | zo 'Review these commits for consistency' ``` #### Review with File History ```bash git log -p --follow src/auth.rs | zo 'Review the evolution of this file. Any technical debt?' ``` #### Compare Implementations ```bash zo @old_impl.py @new_impl.py "Compare these implementations: - Which is better and why? - Performance implications? - Maintainability? - Edge cases handled?" ``` ### Language-Specific Patterns #### Rust Patterns ```bash zo @code.rs "Check for: - Unnecessary .clone() calls - Missing #[must_use] annotations - Potential panic! in production code - Unsafe code without justification - Missing error context - Unoptimized string handling" ``` #### Python Patterns ```bash zo @code.py "Check for: - Mutable default arguments - Broad exception catching - Missing type hints - f-string vs % vs .format() - List comprehension opportunities - Generator usage for large data" ``` #### JavaScript Patterns ```bash zo @code.js "Check for: - var vs let/const - Promise handling - Async/await patterns - Memory leaks (event listeners) - Console.log statements" ``` ### Review Output Formats #### Concise Review ```bash git diff | zo /reviewer "Brief review: list only high/critical issues" ``` #### Detailed Review ```bash zo @complex.rs "Detailed review with: - Code snippets showing problems - Suggested fixes with code - Explanation of issues - Priority ranking" ``` #### Markdown Format ```bash git diff | zo /reviewer "Review in markdown format with: - Summary section - Issues by category - Suggested improvements - Code examples" > REVIEW.md ``` ### Tips for Effective Reviews #### Be Specific ```bash # ❌ Too vague zo @code.rs "Review this" # ✅ Specific zo @code.rs "Review for memory leaks and unnecessary allocations" ``` #### Provide Context ```bash # ❌ No context zo @handler.go "Review this" # ✅ With context zo @handler.go "This is a high-traffic API endpoint. Review for performance and security" ``` #### Use Appropriate Models ```bash # Quick review - fast model zo /flash @small_change.js "Quick review" # Deep review - smart model zo /opus @critical_auth.rs "Thorough security review" ``` #### Iterate in Chat ```bash # Start in chat mode for back-and-forth zo --chat @code.rs "Let's review this together" > Focus on the authentication logic > How can I make it more secure? > Show me the improved version > exit ``` ### Next Steps * [Shell Integration →](/examples/shell-integration) * [Git Workflows →](/examples/git-workflows) * [Custom Models →](/docs/custom-models) ## Data Analysis Examples Use zo for quick data analysis, processing, and insights from the command line. ### CSV Analysis #### Basic Statistics ```bash cat sales.csv | zo 'Calculate summary statistics: - Total revenue - Average order value - Number of transactions - Revenue by category' ``` #### Find Patterns ```bash cat customer_data.csv | zo 'Analyze this customer data: - Find patterns in purchase behavior - Identify high-value customers - Suggest segmentation strategy' ``` #### Data Quality Check ```bash cat data.csv | zo 'Check data quality: - Missing values per column - Outliers - Duplicate records - Data type issues' ``` #### Compare Datasets ```bash zo @dataset1.csv @dataset2.csv 'Compare these datasets: - Schema differences - Value distribution changes - New/removed records' ``` ### JSON Processing #### Extract Data ```bash curl -s https://1.0.0.1/cdn-cgi/trace | zo 'Extract: - IP - Location - TLS Version' ``` #### Transform Format ```bash cat data.json | zo 'Convert to CSV with columns: id, name, email, created_at' ``` #### Query Data ```bash cat large_api_response.json | zo 'Find all users with: - More than 100 followers - Created in 2024 - Located in California' ``` #### Generate jq Command ```bash cat sample.json | zo 'Generate jq command to extract all email addresses from nested user objects' ``` ### Log Analysis #### Error Summary ```bash tail -1000 app.log | zo 'Summarize errors: - Most common error types - Error frequency - Affected components - Suggested fixes' ``` #### Pattern Detection ```bash grep ERROR /var/log/nginx/error.log | zo 'Find patterns: - Time of day with most errors - Common error causes - Suspicious IP addresses - Recommended actions' ``` #### Performance Analysis ```bash cat slow_queries.log | zo 'Analyze slow queries: - Slowest queries - Common patterns in slow queries - Optimization suggestions - Index recommendations' ``` #### Security Analysis ```bash cat access.log | zo 'Security analysis: - Suspicious request patterns - Potential attack attempts - Unusual user agents - Recommended security measures' ``` ### SQL Generation #### Simple Query ```bash zo @schema.sql 'Generate query to: - Find top 10 customers by total purchases - Include customer name, email, purchase count, and total spent - Order by total spent descending' ``` #### Complex Query ```bash zo @schema.sql 'Generate query with: - Join customers, orders, and products - Filter for 2024 purchases - Group by product category - Calculate revenue per category - Include percentage of total' ``` #### Schema Design ```bash zo 'Generate SQL schema for: - E-commerce platform - Users, products, orders, reviews - Include foreign keys, indexes - Add constraints and defaults' ``` ### Data Transformation #### Format Conversion ```bash # CSV to JSON cat data.csv | zo 'Convert to JSON array' # JSON to CSV cat data.json | zo 'Convert to CSV' # XML to JSON cat data.xml | zo 'Convert to JSON' ``` #### Data Cleaning ```bash cat messy_data.csv | zo 'Clean this data: - Remove duplicates - Fix date formats to YYYY-MM-DD - Standardize phone numbers - Fill missing values with median' ``` ### System Diagnostics #### Memory Analysis ```bash ps aux --sort=-%mem | head -20 | zo 'Memory analysis: - Highest memory consumers - Potential memory leaks - Processes to investigate - Recommended actions' ``` #### Disk Usage ```bash du -sh * | sort -hr | head -20 | zo 'Disk usage analysis: - Largest directories - What can be cleaned - Suggested optimizations' ``` #### Network Analysis ```bash netstat -tuln | zo 'Network analysis: - Active connections - Listening ports - Security concerns - Recommendations' ``` #### Process Analysis ```bash ps aux | zo 'Analyze running processes: - Resource-intensive processes - Zombie processes - Unusual processes - Recommendations' ``` ### API Data Analysis #### Rate Limit Analysis ```bash cat api_logs.txt | zo 'Analyze API usage: - Requests per endpoint - Peak usage times - Users hitting rate limits - Capacity recommendations' ``` #### Response Time Analysis ```bash cat api_metrics.json | zo 'Analyze response times: - Slowest endpoints - P95, P99 latencies - Performance trends - Optimization targets' ``` #### Error Rate Analysis ```bash cat api_errors.log | zo 'Error rate analysis: - Error frequency by endpoint - Most common error types - Client vs server errors - Suggested fixes' ``` ### Data Visualization Suggestions #### Chart Recommendations ```bash cat sales_data.csv | zo 'Recommend visualizations: - Best chart types for this data - Key metrics to highlight - Interactive features to include - Color scheme suggestions' ``` #### Python Plotting Code ```bash cat data.csv | zo /coder 'Generate Python code to: - Load this CSV - Create 3 meaningful visualizations - Use matplotlib or seaborn - Include titles and labels' ``` #### Dashboard Design ```bash cat metrics.json | zo 'Design dashboard: - Key metrics to display - Layout suggestions - Chart types - Real-time vs historical views' ``` ### Statistical Analysis #### Descriptive Statistics ```bash cat survey_results.csv | zo 'Calculate: - Mean, median, mode for each numeric column - Standard deviation - Quartiles - Correlation matrix' ``` #### Hypothesis Testing ```bash cat experiment_data.csv | zo 'Statistical analysis: - Compare control vs treatment groups - Calculate p-value - Determine statistical significance - Interpret results' ``` #### Regression Analysis ```bash cat sales_data.csv | zo 'Regression analysis: - Predict sales based on marketing spend - Calculate R-squared - Identify significant variables - Interpret coefficients' ``` ### Data Pipeline Examples #### ETL Pipeline ```bash #!/bin/bash # Extract curl -s https://api.example.com/data > raw_data.json # Transform cat raw_data.json | zo 'Transform to CSV with columns: id, name, amount, date' > clean_data.csv # Load (generate SQL) zo @schema.sql @clean_data.csv 'Generate INSERT statements' ``` #### Data Quality Pipeline ```bash #!/bin/bash # Check quality issues=$(cat data.csv | zo 'List data quality issues as JSON') # Fix issues echo "$issues" | zo 'Generate Python script to fix these data quality issues' ``` ### Advanced Analysis #### Time Series Analysis ```bash cat time_series.csv | zo 'Time series analysis: - Identify trends - Detect seasonality - Find anomalies - Forecast next 30 days - Confidence intervals' ``` #### Cohort Analysis ```bash cat user_cohorts.csv | zo 'Cohort analysis: - Retention rates by cohort - Cohort size trends - Revenue per cohort - Churn patterns - Recommendations' ``` ### Shell Functions for Data Analysis Add to `~/.bashrc` or `~/.zshrc`: ```bash # Quick CSV stats csvstats() { cat "$1" | zo 'Summary statistics for all numeric columns' } # Find correlations csvcorr() { cat "$1" | zo 'Correlation matrix for numeric columns. Highlight strong correlations.' } # Data quality check datacheck() { cat "$1" | zo 'Data quality report: - Missing values - Outliers - Duplicates - Type mismatches' } # Generate SQL sqlgen() { zo @schema.sql "$*" } # API analysis apistat() { cat "$1" | zo 'API usage statistics: - Request distribution - Error rates - Response times - Top consumers' } ``` ### Tips for Data Analysis #### Provide Context ```bash # ❌ Too vague cat data.csv | zo 'Analyze this' # ✅ Specific cat sales_data.csv | zo 'Analyze 2024 sales data: - Monthly revenue trends - Top performing products - Regional performance - YoY growth rate' ``` #### Sample Large Datasets ```bash # First 1000 rows for quick analysis head -1000 large_file.csv | zo 'Quick analysis' # Random sample shuf -n 1000 large_file.csv | zo 'Sample analysis' ``` #### Iterate with Chat Mode ```bash zo --chat @data.csv 'Let us analyze this sales data' > What are the top 10 products? > Show me revenue trends > Any seasonal patterns? > exit ``` #### Use Appropriate Models ```bash # Quick analysis - fast model cat data.csv | zo /flash 'Quick summary' # Deep analysis - smart model cat data.csv | zo /opus 'Comprehensive statistical analysis' ``` ### Next Steps * [Shell Integration →](/examples/shell-integration) * [Examples →](/examples) * [Quick Start →](/docs/quick-start) ## Git Workflows Integrate zo into your Git workflow for better commit messages, PR descriptions, and code reviews. ### Commit Message Generation #### Basic Commit Message ```bash # Generate commit message from staged changes git diff --cached | zo 'Generate a concise commit message following conventional commits format' ``` **Example Output:** ``` feat: add user authentication with JWT tokens - Implement login and registration endpoints - Add password hashing with bcrypt - Create JWT middleware for protected routes ``` #### Detailed Commit Message ```bash git diff --cached | zo 'Generate a detailed commit message with: - Brief summary (50 chars) - Detailed explanation - List of changes - Breaking changes if any' ``` #### Commit Message by Type ```bash # Feature git diff --cached | zo 'Generate a "feat:" commit message' # Bug fix git diff --cached | zo 'Generate a "fix:" commit message explaining the bug and solution' # Refactor git diff --cached | zo 'Generate a "refactor:" commit message' # Documentation git diff --cached | zo 'Generate a "docs:" commit message' ``` ### PR Description Generation #### Basic PR Description ```bash git diff main...feature | zo 'Generate a pull request description with: - Summary - Changes made - Testing approach' ``` #### Detailed PR Description ```bash git diff main...feature | zo 'Generate a comprehensive PR description in markdown: ## Summary Brief overview ## Changes - Bullet list of changes ## Testing How this was tested ## Breaking Changes Any breaking changes ## Screenshots (if applicable) Mention if UI changes exist' ``` #### PR Template Format ```bash git diff main...feature | zo 'Generate PR description following this template: **What does this PR do?** Brief description **Why are these changes needed?** Motivation **How were these changes implemented?** Technical approach **How was this tested?** Testing strategy **Checklist:** - [ ] Tests added/updated - [ ] Documentation updated - [ ] No breaking changes - [ ] Reviewed own code' ``` ### Code Review with Git #### Review Staged Changes ```bash git diff --cached | zo /reviewer 'Review my staged changes before I commit' ``` #### Review Recent Commit ```bash git show HEAD | zo /reviewer 'Review my last commit' ``` #### Review Multiple Commits ```bash git log -3 -p | zo /reviewer 'Review my last 3 commits for consistency' ``` #### Review PR Changes ```bash git diff main...feature | zo /reviewer 'Thorough code review for this PR' ``` ### Analyzing Git History #### Summarize Recent Activity ```bash git log --oneline -20 | zo 'Summarize recent development activity and identify themes' ``` #### Explain Specific Commit ```bash git show | zo 'Explain what this commit does and why these changes were made' ``` #### Find Bug Introduction ```bash git log -p --all -S "buggy_function" | zo 'When was this bug likely introduced and what was the context?' ``` #### Analyze File Evolution ```bash git log -p --follow src/auth.rs | zo 'Trace the evolution of this file and identify any technical debt' ``` ### Branch Comparison #### Compare Branches ```bash git diff main...develop | zo 'Compare main and develop branches. What are the key differences?' ``` #### Find Divergence Point ```bash git log --oneline --graph --all | head -50 | zo 'Explain the branch structure and divergence points' ``` ### Release Notes Generation #### Generate Release Notes ```bash git log v1.0.0...v2.0.0 --oneline | zo 'Generate release notes for version 2.0.0' ``` #### Categorized Release Notes ```bash git log --oneline --since="2024-01-01" | zo 'Generate release notes categorized by: - New Features - Bug Fixes - Improvements - Breaking Changes - Documentation' ``` #### Changelog Format ```bash git log --oneline --since="last month" | zo 'Generate CHANGELOG.md entry in Keep a Changelog format' ``` ### Shell Functions for Git Add these to `~/.bashrc` or `~/.zshrc`: #### Auto Commit Message ```bash gcm() { # Generate and use commit message local msg=$(git diff --cached | zo 'Generate concise conventional commit message') echo "Commit message: $msg" echo "Use this message? [Y/n]" read -r response if [[ ! "$response" =~ ^[Nn]$ ]]; then git commit -m "$msg" fi } ``` #### Smart PR Description ```bash pr-desc() { local branch=${1:-main} git diff "$branch"...HEAD | zo 'Generate PR description in markdown' > pr-description.md cat pr-description.md } ``` #### Commit Review ```bash review-commit() { local commit=${1:-HEAD} git show "$commit" | zo /reviewer 'Review this commit' } ``` #### Git Explain ```bash git-explain() { git log --oneline -10 | zo 'Explain what is been happening in this repository recently' } ``` ### Troubleshooting #### Large Diffs ```bash # Limit diff size git diff main...feature -- src/ | head -1000 | zo 'Review (partial diff)' # Review by file for file in $(git diff main...feature --name-only); do git diff main...feature -- "$file" | zo "Review $file" done ``` #### Binary Files ```bash # Exclude binary files git diff --diff-filter=d --no-binary | zo 'Review code changes only' ``` ### Next Steps * [Code Review Examples →](/examples/code-review) * [Shell Integration →](/examples/shell-integration) * [Configuration →](/docs/configuration) ## Examples Real-world examples of using zo in your daily workflow. ### Quick Examples #### Basic Usage ```bash # Simple question zo 'What is the difference between TCP and UDP?' # With model selection zo /sonnet 'Explain Rust lifetimes' # Using CLI flag zo --model opus 'Complex reasoning task' ``` #### Code Review ```bash # Review current changes git diff | zo 'Review these changes for bugs' # Review specific file zo @src/main.rs 'Code review with focus on performance' # Multiple files zo @header.h @impl.c 'Are these in sync?' ``` #### Error Debugging ```bash # Build errors cargo build 2>&1 | zo /sonnet 'Explain these errors and how to fix' # Test failures npm test 2>&1 | zo 'Why are these tests failing?' # Log analysis tail -100 error.log | zo 'Find the root cause' ``` #### Data Analysis ```bash # CSV analysis cat sales.csv | zo 'Calculate total revenue by region' # System diagnostics df -h | zo 'Do I have disk space issues?' ``` #### Documentation ```bash # Generate docs zo @api.rs 'Generate API documentation in markdown' # Explain code zo @algorithm.py 'Explain this algorithm step by step' # Create README zo @main.go @types.go 'Generate README with usage examples' ``` #### File Output ```bash # Create new files zo 'Create a Python hello world in !hello.py' zo 'Write a Rust HTTP server in !server.rs' # Update existing files with diff approval zo 'Add error handling to @!main.rs' zo 'Refactor @!utils.py to use async' # Multiple files at once zo 'Create !README.md and !LICENSE with MIT license' # Auto-approve with --yes flag zo --yes 'Add type hints to @!script.py' ``` ### Featured Examples Explore detailed examples for specific use cases: * [Code Review →](/examples/code-review) * [Shell Integration →](/examples/shell-integration) * [Git Workflows →](/examples/git-workflows) * [Data Analysis →](/examples/data-analysis) ### Custom Model Examples #### Code Reviewer Persona ```toml # ~/.config/zo/config.toml [[custom_models]] name = "reviewer" model = "anthropic/claude-sonnet-4.5" system_prompt = "You are a senior code reviewer. Focus on bugs, performance, security, and best practices." ``` ```bash zo /reviewer @pull_request.diff 'Review this PR' ``` #### Teacher Persona ```toml [[custom_models]] name = "teacher" model = "anthropic/claude-opus-4.5" system_prompt = "You are a patient teacher. Explain from first principles with analogies and examples." ``` ```bash zo /teacher 'Explain how compilers work' ``` #### DevOps Expert ```toml [[custom_models]] name = "devops" model = "anthropic/claude-sonnet-4.5" system_prompt = "You are a DevOps expert. Focus on infrastructure as code, CI/CD, monitoring, and security." ``` ```bash zo /devops 'Design a CI/CD pipeline for a Node.js app' ``` ### Advanced Workflows #### Git Commit Messages ```bash # Generate commit message git diff --cached | zo 'Generate a concise commit message' # With custom model git diff --cached | zo /writer 'Generate commit message' ``` #### PR Descriptions ```bash git diff main...feature | zo 'Generate PR description with: - Summary - Changes made - Testing done - Breaking changes' ``` #### Code Refactoring ```bash zo --chat 'Let us refactor @!legacy.js to modern JavaScript' > Use async/await instead of callbacks > Add TypeScript types > Improve error handling > exit ``` #### File Output Workflows ```bash # Create files directly zo 'Create a complete FastAPI app with !main.py, !models.py, and !requirements.txt' # Update with interactive approval zo 'Modernize @!old_code.py to Python 3 with type hints' # Incremental refactoring in chat mode zo --chat '@!legacy_code.py Let us modernize this' > Add type hints > Convert to async > Add error handling > exit # Generate documentation files zo '@src/main.rs @src/lib.rs "Generate API docs in !API.md' # Create tests from implementation zo '@app.py Generate comprehensive unit tests in !test_app.py' ``` #### Test Generation ```bash zo @src/calculator.rs 'Generate comprehensive unit tests with edge cases' # With file output zo '@!lib.rs Create unit tests in !tests/lib_test.rs' ``` #### SQL Query Generation ```bash zo @schema.sql 'Generate a query to find: - Top 10 customers by lifetime value - Include customer name, email, total orders, and revenue - Order by revenue descending' ``` #### Dockerfile Optimization ```bash zo @Dockerfile 'Optimize this for: - Smaller image size - Better layer caching - Security best practices - Multi-stage build' ``` #### Configuration Generation ```bash zo 'Generate nginx config for: - Reverse proxy to localhost:3000 - Gzip compression - Static file caching - Rate limiting' ``` ### Shell Function Examples Add these to `~/.bashrc` or `~/.zshrc`: #### Explain Command ```bash explain() { echo "$*" | zo 'Explain this command and what it does' } # Usage explain tar -xzf archive.tar.gz explain find . -name '*.log' -mtime +7 -delete ``` #### Get Command Suggestions ```bash howto() { zo 'How do I $* in bash/zsh? Give me the exact command' } # Usage howto find all python files modified today howto compress a directory with tar ``` #### Error Fixer ```bash fix() { "$@" 2>&1 | zo 'Why did this command fail and how do I fix it?' } # Usage fix cargo build fix npm install ``` #### Code Generator ```bash gen() { zo /coder "$*" | tee generated.txt } # Usage gen implement binary search in Rust with tests gen create Python script to parse JSON logs ``` ### Pipeline Examples #### Log Analysis ```bash # Error patterns grep ERROR app.log | zo 'Summarize these errors and suggest fixes' # Rate limiting tail -1000 access.log | zo 'Are we getting attacked? Look for suspicious patterns' # Performance issues cat slow_query.log | zo 'Which queries need optimization?' ``` #### System Monitoring ```bash # Memory usage ps aux --sort=-%mem | head -20 | zo 'Which processes should I investigate?' # Disk usage du -sh * | sort -hr | head -20 | zo 'What is using my disk space?' # Network connections netstat -tuln | zo 'Are these ports properly secured?' ``` #### Data Processing ```bash # CSV to JSON cat data.csv | zo 'Convert to JSON format' # Extract emails cat document.txt | zo 'Extract all email addresses as a list' # Parse logs cat nginx.log | zo 'Extract unique IP addresses making POST requests' ``` ### Next Steps * [Code Review Examples →](/examples/code-review) * [Shell Integration →](/examples/shell-integration) * [Git Workflows →](/examples/git-workflows) * [Data Analysis →](/examples/data-analysis) ## Shell Integration Integrate zo into your shell for seamless AI assistance in your terminal workflow. ### Quick Functions Add these to `~/.bashrc` or `~/.zshrc`: #### Explain Command ```bash explain() { echo "$*" | zo 'Explain this command and what it does' } ``` Usage: ```bash explain tar -xzf archive.tar.gz explain find . -name '*.log' -mtime +7 -delete explain awk '{print $1}' file.txt | sort | uniq -c ``` #### How-To Helper ```bash howto() { zo 'How do I $* in bash/zsh? Give me the exact command' } ``` Usage: ```bash howto find all python files modified today howto compress a directory excluding node_modules howto count lines of code in all js files ``` #### Error Fixer ```bash fix() { "$@" 2>&1 | zo 'Why did this command fail and how do I fix it?' } ``` Usage: ```bash fix cargo build fix npm install fix git push ``` ### Advanced Functions #### Git Helper ```bash # Generate commit message gcm() { local msg=$(git diff --cached | zo 'Generate concise conventional commit message') echo "Commit message: $msg" echo "Use this message? [Y/n]" read -r response if [[ ! "$response" =~ ^[Nn]$ ]]; then git commit -m "$msg" fi } # Review before commit grc() { git diff --cached | zo /reviewer 'Quick review of staged changes' } # PR description prdesc() { local branch=${1:-main} git diff "$branch"...HEAD | zo 'Generate PR description' > pr.md cat pr.md } ``` #### Log Analysis ```bash # Analyze recent logs logs() { local lines=${1:-100} tail -n "$lines" /var/log/syslog | zo 'Summarize errors and issues' } # Find patterns logpattern() { tail -n 1000 "$1" | zo 'Find patterns and anomalies in these logs' } ``` #### System Diagnostics ```bash # Memory check memcheck() { ps aux --sort=-%mem | head -20 | zo 'Which processes should I investigate?' } # Disk usage diskcheck() { du -sh * | sort -hr | head -20 | zo 'What is using my disk space?' } # Network check netcheck() { netstat -tuln | zo 'Any suspicious network connections?' } ``` ### Aliases #### Basic Aliases ```bash # ~/.bashrc or ~/.zshrc alias chat='zo --chat' alias review='zo /reviewer' alias code='zo /coder' alias debug='zo /debugger' alias explain-code='zo /teacher' ``` Usage: ```bash chat 'Let us discuss system design' chat-code @main.rs 'Refactor this' chat-review @pr.diff 'Review this PR' ``` ### Interactive Prompts #### Multi-line Input ```bash multiask() { echo "Enter your question (Ctrl+D when done):" local input=$(cat) zo "$input" } ``` Usage: ```bash multiask # Type multiple lines # Press Ctrl+D ``` #### File Selection ```bash reviewfile() { local file=$(find . -name '*.rs' | fzf) if [ -n "$file" ]; then zo /reviewer @"$file" 'Review this code' fi } ``` Requires `fzf` installed. ### Workflow Integration #### Development Workflow ```bash # ~/.bashrc # Before committing pre-commit-check() { git diff --cached | zo /reviewer 'Quick sanity check. Flag critical issues only.' } # After error fix-last() { fc -ln -1 | zo 'This command failed. Why and how to fix?' } # Explain recent commands history-explain() { history | tail -5 | zo 'Explain what these commands do' } ``` #### Documentation Workflow ```bash # README generator readme() { zo /writer @*.js 'Generate comprehensive !README.md with: - Overview - Installation - Usage examples - API documentation - Contributing guidelines' } ``` #### Data Analysis Workflow ```bash # Quick CSV stats csvstats() { head -100 "$1" | zo 'Calculate basic statistics for each column' } # JSON query helper jqhelp() { echo "$1" | zo 'Generate jq command to: $2' } # SQL generator sqlgen() { zo @schema.sql 'Generate SQL query: $*' } ``` ### Advanced Pipelines #### Multi-stage Analysis ```bash # Code → Review → Fix → Test pipeline-fix() { local file="$1" # Review local issues=$(zo /reviewer @"$file" 'List critical issues as JSON') # Fix echo "$issues" | zo /coder 'Fix these issues in the code' # Verify zo /reviewer @"$file" 'Verify fixes' } ``` #### Data Processing Pipeline ```bash # Fetch → Parse → Analyze → Visualize api-analyze() { curl -s "$1" \ | zo 'Extract key data as CSV' \ | zo 'Generate summary statistics' \ | zo 'Suggest visualization approach' } ``` ### Shell Scripting #### Error Handling Script ```bash #!/bin/bash run_with_ai_help() { local cmd="$*" local output local exit_code # Run command output=$($cmd 2>&1) exit_code=$? if [ $exit_code -ne 0 ]; then echo "Command failed:" echo "$output" echo "" echo "AI Analysis:" echo "$output" | zo /debugger 'Diagnose and suggest fix' else echo "$output" fi return $exit_code } ``` #### Automated Code Review ```bash #!/bin/bash # review-pr.sh branch="${1:-main}" echo "🔍 Reviewing changes..." # Get diff diff=$(git diff "$branch"...HEAD) # AI review review=$(echo "$diff" | zo /reviewer 'Comprehensive PR review') # Save and display echo "$review" > review.md cat review.md echo "✅ Review complete" ``` ### Productivity Shortcuts #### Quick Reference ```bash # Man page summaries mans() { man "$1" | zo 'Summarize the most useful options' } # Command cheatsheet cheat() { zo 'Give me a cheatsheet for $1 with common usage examples' } # Language syntax syntax() { zo 'Show me $1 syntax for: $2' } ``` Usage: ```bash mans grep cheat docker syntax python 'list comprehension' ``` #### Learning Helper ```bash # Explain with examples learn() { zo /teacher "$*" } # Code walkthrough walkthrough() { zo @"$1" /teacher 'Explain this code step by step' } # Concept comparison compare() { zo /teacher 'Compare and contrast: $1 vs $2' } ``` ### Installation Add to your shell configuration: ```bash # ~/.bashrc or ~/.zshrc # Source zo helper functions if [ -f ~/.zo_functions.sh ]; then source ~/.zo_functions.sh fi ``` Create `~/.zo_functions.sh` with your favorite functions. ### Next Steps * [Git Workflows →](/examples/git-workflows) * [Code Review →](/examples/code-review) * [Configuration →](/docs/configuration) ## Chat Mode Have multi-turn conversations with AI models where every response builds on previous context. Perfect for iterative problem-solving, pair programming, and in-depth discussions. ### Overview Chat mode enables: * **Context preservation** - AI remembers the entire conversation * **Iterative refinement** - Build on previous responses * **File references** - Use `@filename` syntax in any message * **Model persistence** - Same model throughout the session * **System prompts** - Custom model personas applied to all messages * **Error recovery** - Retry on failures without losing history ### Basic Usage #### Starting a Chat Session ```bash # Basic chat zo --chat 'Let us discuss Rust lifetimes' > Can you give me an example? > What happens if I violate the rules? > exit # With model selection (slash command) zo --chat /sonnet 'Explain async/await' > Show me a practical example > How does it compare to threads? > exit # With model selection (CLI flag) zo --chat --model opus 'Let us design a system' > What about scalability? > How would you handle failures? > exit ``` #### Exiting Chat Multiple ways to exit: * Type `exit` * Type `quit` * Type `q` * Press `Ctrl+D` (EOF) ```bash zo --chat 'Hello' > Let us talk about databases > exit # ← Exits the chat session ``` #### Multiline Input For entering multiline messages, use one of these key combinations: * **Alt-Enter** - Works in most modern terminals (recommended) * **Ctrl-O** - Fallback for terminals where Alt-Enter doesn't work * **Ctrl-J** - Alternative binding Press Enter normally to submit your message. ```bash zo --chat 'Help me write a function' > def process_data(items): # Alt-Enter to continue > for item in items: # Alt-Enter to continue > yield item * 2 # Enter to submit ``` ### Chat with Initial Context #### File References Start the chat with file context using `@filename` syntax: ```bash # Single file zo --chat @code.rs 'Let us refactor this together' > Make it more functional > Add error handling > Now add tests > exit # Multiple files zo --chat @v1.py @v2.py 'Help me merge these versions' > Focus on the database code > What about the API changes? > exit # With model selection zo --chat /sonnet @main.rs 'Code review session' > Check the error handling > What about performance? > exit ``` #### Piped Input (STDIN) Start the chat with piped content: ```bash # From git diff git diff | zo --chat 'Let us review these changes' > What about the tests? > Should I refactor anything? > exit # From error log cat error.log | zo --chat /debugger 'Help me debug this' > What should I check first? > I tried that, still failing > exit # From command output cargo build 2>&1 | zo --chat 'Let us fix these errors' > Start with the most critical > Explain that error in detail > exit ``` #### Combining File References and STDIN ```bash # Git diff + README context git diff | zo --chat @README.md 'Do these changes need documentation updates?' > Should I update the examples? > Write the updated section > exit ``` ### Interactive File References You can use `@filename` syntax in any message during the chat, not just the initial prompt: ```bash zo --chat 'I need help with my project' > @src/main.rs Review this file > @tests/test.rs Do the tests cover the main logic? > @Cargo.toml Should I add any dependencies? > exit ``` **File Error Handling**: If a file doesn't exist or can't be read during chat, zo displays an error and prompts you again without exiting the session. ### Use Cases #### Pair Programming ```bash zo --chat /coder @app.rs 'Let us implement authentication' > Add password hashing with bcrypt > Now add JWT token generation > Add refresh token logic > Write unit tests for the auth flow > exit ``` **Why it works**: Each response builds on the previous code. The AI remembers what you've already implemented. #### Iterative Debugging ```bash cat stacktrace.log | zo --chat /debugger 'Let us debug this crash' > What is the most likely cause? > I checked that, the variable is initialized > Could it be a race condition? > How do I verify that? > exit ``` **Why it works**: The AI maintains context about what you've already tried, making suggestions more targeted. #### Learning Sessions ```bash zo --chat /teacher 'Teach me about Redis internals' > How does it achieve such high performance? > Explain the data structures it uses > How does persistence work? > What about replication? > Give me a practical example > exit ``` **Why it works**: Each explanation builds on previous ones, creating a coherent learning path. #### Architecture Design ```bash zo --chat /architect 'Design a real-time notification system' > It needs to handle 100k concurrent users > What about message persistence? > How do we handle failures? > What is the deployment strategy? > Estimate the costs > exit ``` **Why it works**: Design decisions compound. Later questions can reference earlier architectural choices. #### Code Review Conversations ```bash zo --chat /reviewer @pull_request.diff 'Comprehensive PR review' > What are the security concerns? > I fixed the SQL injection. What else? > Is the error handling sufficient? > Any performance issues? > exit ``` **Why it works**: Iterative review where you can ask for clarification and address feedback incrementally. #### Documentation Writing ```bash zo --chat /writer @lib.rs @examples/ 'Help me write comprehensive docs' > Start with an overview > Now document the main API functions > Add usage examples for each function > Include common pitfalls section > exit ``` **Why it works**: Documentation sections build on each other. Later sections can reference earlier explanations. ### Technical Details #### Context Preservation zo maintains a complete message history: ```rust pub struct ChatSession { messages: Vec, // Full conversation history model_entry: ModelEntry, client: OpenRouterClient, } ``` **Every message includes**: 1. System prompt (if defined for custom model) 2. All previous user messages 3. All previous assistant responses 4. Current user message **Token implications**: Long conversations consume more tokens. Most models have context limits (8K-200K tokens). #### Input Handling ##### Interactive Input with Piped STDIN When you start chat with piped STDIN, zo uses a special technique: ```bash cat file.txt | zo --chat 'Analyze this' # STDIN consumed for first message > Follow-up question # ← This reads from keyboard (TTY) > exit ``` **How it works**: On Unix systems, zo reads subsequent messages from `/dev/tty` instead of stdin. This allows interactive input even when initial stdin was piped. **Non-Unix systems**: Falls back to regular stdin (may not work with piped initial input). ##### File References in Chat File references are parsed fresh in each message: ```bash zo --chat 'Hello' > @file1.txt Analyze this # File read and sent with this message > @file2.txt Now analyze this one # Different file read and sent with this message > exit ``` Each `@filename` reference is independent and read at the time of the message. #### Error Recovery If an API call fails during chat: ```bash zo --chat 'Test' > This is a long question... # Network error occurs Error: Network request failed Retry? [y/N]: y # Re-sends the same message with full history ``` **History preservation**: Your message history is NOT modified on error. You can retry with the same context. #### Model Selection The model is selected at chat session start and used for all messages: ```bash # Model selected here ↓ zo --chat /sonnet 'Question 1' > Question 2 # Uses sonnet > Question 3 # Uses sonnet > exit # Cannot change mid-chat zo --chat /sonnet 'Question' > /opus 'Question' # ← This doesn't switch models! # Treats "/opus" as part of the message text ``` **To change models**: Exit and start a new chat session. #### System Prompts If using a custom model with a system prompt, it applies to the entire conversation: ```toml # ~/.config/zo/config.toml [[custom_models]] name = "coder" model = "anthropic/claude-sonnet-4.5" system_prompt = "You are an expert programmer. Provide concise, tested code." ``` ```bash zo --chat /coder 'Write a function' > Make it faster # System prompt still applies > Add tests # System prompt still applies > exit ``` The system prompt is sent with every request, ensuring consistent behavior. ### Best Practices #### ✅ Do This ```bash # Start with clear context zo --chat @project.rs 'Let us review and improve this code' # Ask follow-up questions > Focus on the error handling > Can you explain that pattern? # Build iteratively zo --chat 'Design a URL shortener' > Add analytics tracking > Now add rate limiting > How do we scale it? # Use appropriate models zo --chat /opus 'Complex system design discussion' zo --chat /flash 'Quick questions' # Exit cleanly > exit ``` #### ❌ Avoid This ```bash # Don't repeat context unnecessarily > Here is my code again: [paste entire code] # The AI already has it from earlier messages # Don't try to change models mid-chat > /gpt4 'switch to GPT-4' # Doesn't work # Don't ignore context limits # Very long chat sessions may hit model context limits # Don't use for single questions zo --chat 'What is 2+2?' # Just use: zo 'What is 2+2?' > exit ``` ### Advanced Patterns #### Multi-File Workflow ```bash zo --chat 'Help me build a web API' > @schema.sql Start with database schema > @models.py Generate Python models from that schema > @api.py Create REST endpoints > @tests/test_api.py Write integration tests > exit ``` #### Iterative Refinement ```bash zo --chat /coder 'Write a binary search tree in Rust' > Add a delete method > Make it generic over any Ord type > Add iterators > Optimize the rebalancing > Add comprehensive documentation > exit ``` #### Problem Solving Session ```bash cat benchmark.txt | zo --chat 'My app is slow, help me optimize' > Profile the hot path > I see malloc is called frequently. Explain. > How do I use a memory pool? > Show me the implementation > How much improvement should I expect? > exit ``` #### Educational Dialogue ```bash zo --chat /teacher 'Explain how compilers work' > What is the difference between lexing and parsing? > Show me a simple example > How does semantic analysis work? > What about optimization passes? > Can you recommend resources to learn more? > exit ``` ### Shell Integration #### Quick Chat Alias ```bash # ~/.bashrc or ~/.zshrc alias chat='zo --chat' alias chat-code='zo --chat /coder' alias chat-review='zo --chat /reviewer' alias chat-debug='zo --chat /debugger' ``` Usage: ```bash chat 'Let us discuss databases' chat-code @main.rs 'Refactor this' chat-review @pr.diff 'Review this PR' ``` #### Chat with Context Function ```bash # Start chat with git context gitchat() { git diff | zo --chat /reviewer 'Let us review these changes' } # Chat about errors debugchat() { "$@" 2>&1 | zo --chat /debugger 'Let us fix this' } ``` Usage: ```bash gitchat debugchat cargo build ``` ### Comparison: Chat Mode vs Single Request #### Use Chat Mode When: ✅ You need to ask follow-up questions\ ✅ Building something iteratively\ ✅ Exploring a topic in depth\ ✅ Debugging complex issues\ ✅ Pair programming sessions\ ✅ Learning conversations #### Use Single Request When: ✅ One-off questions\ ✅ Quick transformations\ ✅ Simple analysis\ ✅ Scripting/automation\ ✅ Pipeline processing ### Examples Gallery #### Real-World Chat Sessions ##### Session 1: Feature Implementation ```bash zo --chat /coder @app.rs 'Add user authentication' > Use JWT tokens > Add password reset functionality > Add rate limiting on login endpoint > Write integration tests > Document the auth flow in comments > exit ``` ##### Session 2: Performance Investigation ```bash cat profile.txt | zo --chat /debugger 'App is using 2GB memory' > Show me common memory leak patterns in this context > I see a lot of Vec allocations. Explain. > Should I use a different data structure? > Show me how to use a slab allocator here > exit ``` ##### Session 3: Learning New Concept ```bash zo --chat /teacher 'Explain the ownership system of Rust' > Give me a simple example > What happens if I try to use a value after moving it? > How do borrowing and references work? > When should I use Rc vs Arc? > Give me a real-world example using all these concepts > exit ``` ##### Session 4: Architecture Review ```bash zo --chat @architecture.md 'Review this system design' > What are the bottlenecks? > How should we handle database failover? > What about cross-region replication? > Estimate the infrastructure costs > Suggest monitoring strategy > exit ``` ### Troubleshooting #### Context Limit Exceeded **Problem**: Error about context/token limit. **Solution**: * Use models with larger context windows (Claude has 200K, GPT-4 has 128K) * Start a new chat session to clear history * Summarize earlier parts of the conversation ```bash # Summarize and start fresh > Summarize what we discussed so far # Copy summary > exit zo --chat 'Continuing from: [paste summary]' ``` #### Can't Input After STDIN **Problem**: Can't type after piping initial input. **Solution**: This should work automatically on Unix systems. If not: ```bash # Workaround: save to file first cat data.txt > /tmp/context.txt zo --chat @/tmp/context.txt 'Discuss this' ``` #### Lost Context **Problem**: AI seems to forget earlier messages. **This shouldn't happen** - zo sends full history. If it does: 1. Check for API errors in earlier messages 2. Verify the model has sufficient context window 3. File an issue - this is a bug #### Model Not Using System Prompt **Problem**: Custom model not following system prompt. **Solution**: Verify configuration: ```bash # List models (shows custom ones too) zo +list-models | grep yourmodel # Check config file cat ~/.config/zo/config.toml ``` System prompt must be in `[[custom_models]]` section. ### Performance Considerations #### Token Usage Every message sends full history: ``` Message 1: system_prompt + user1 Message 2: system_prompt + user1 + assistant1 + user2 Message 3: system_prompt + user1 + assistant1 + user2 + assistant2 + user3 ``` **Token cost grows quadratically** with conversation length. **Tips**: * Keep sessions focused * Use cheaper models for long conversations * Start new session when changing topics #### Latency Each message includes full history, so: * Longer conversations = more tokens to process * Slower response times as chat grows * More API cost per message **Recommendation**: For very long sessions (20+ exchanges), consider starting fresh and providing a summary. #### Memory Usage Full conversation history kept in memory. For typical sessions (\<100 messages), this is negligible (\<1MB). ### Next Steps * [STDIN Pipelines →](/docs/stdin) - Pipe command output to zo * [Custom Models →](/docs/custom-models) - Create specialized chat personas * [Shell Integration →](/examples/shell-integration) - Workflow integration * [Configuration →](/docs/configuration) - Set up custom models ## Configuration zo uses a TOML configuration file for settings, custom models, and personalization. ### Config File Location * **Linux/macOS:** `~/.config/zo/config.toml` ### Quick Setup #### Initialize Config ```bash zo +init-config ``` This creates `~/.config/zo/config.toml` with: * Helpful comments explaining all options * Example custom models * List of available themes * Color customization examples #### Basic Configuration ```toml # API Key (alternatively use OPENROUTER_API_KEY env var) api_key = "sk-or-v1-..." # Default model (uses fuzzy matching) default_model = "flash" ``` ### Complete Configuration Example ```toml # ~/.config/zo/config.toml # API Key (alternatively set OPENROUTER_API_KEY environment variable) api_key = "sk-or-v1-..." # Default model when no model specified # Uses fuzzy matching - can be "sonnet", "flash", "gpt4", etc. default_model = "flash" # Syntax highlighting theme for code blocks # See available themes below theme = "base16-ocean.dark" # Custom colors for inline markdown elements [inline_colors] heading = "cyan" # Color for # Headers inline_code = "yellow" # Color for `code` emphasis = "white" # Color for *italic* and **bold** # Define custom models with system prompts [[custom_models]] name = "coder" model = "anthropic/claude-sonnet-4.5" system_prompt = "You are an expert programmer. Provide concise, well-commented code with error handling. Follow best practices and explain your choices." [[custom_models]] name = "reviewer" model = "anthropic/claude-sonnet-4.5" system_prompt = "You are a senior code reviewer. Focus on: bugs, performance, security, readability, and best practices. Be thorough but constructive." [[custom_models]] name = "writer" model = "openai/gpt-4o" system_prompt = "You are a professional technical writer. Write clear, engaging documentation. Use examples, avoid jargon, and structure content logically." ``` ### Configuration Fields #### API Key **Field:** `api_key`\ **Type:** String (optional)\ **Default:** None ```toml api_key = "sk-or-v1-your-key-here" ``` **Alternative:** Environment variable (recommended) ```bash export OPENROUTER_API_KEY="sk-or-v1-your-key-here" ``` **Priority:** Environment variable takes precedence over config file. #### Default Model **Field:** `default_model`\ **Type:** String (optional)\ **Default:** `"flash"` (Google Gemini Flash) ```toml default_model = "sonnet" ``` Uses fuzzy matching - accepts any model name that matches built-in or custom models. #### Theme **Field:** `theme`\ **Type:** String (optional)\ **Default:** `"base16-ocean.dark"` ```toml theme = "Monokai Extended" ``` **Available Themes:** **Dark Themes:** * `base16-ocean.dark` (default) * `Solarized-dark` * `Monokai Extended` * `Nord` * `Dracula` * `One Dark` * `Zenburn` **Light Themes:** * `base16-ocean.light` * `InspiredGitHub` * `Solarized-light` * `One Light` #### Inline Colors **Section:** `[inline_colors]`\ **Type:** Object (optional)\ **Fields:** `heading`, `inline_code`, `emphasis` ```toml [inline_colors] heading = "cyan" inline_code = "yellow" emphasis = "white" ``` **Named Colors:** * `black`, `red`, `green`, `yellow` * `blue`, `magenta`, `cyan`, `white` * `gray`, `darkgray` * `lightred`, `lightgreen`, `lightyellow` * `lightblue`, `lightmagenta`, `lightcyan` **Hex Colors:** ```toml [inline_colors] heading = "#00FFFF" inline_code = "#FFFF00" emphasis = "#FFFFFF" ``` **Smart Defaults:** zo automatically chooses colors based on your theme: * Dark themes → Bright colors * Light themes → Dark colors #### Custom Models **Section:** `[[custom_models]]`\ **Type:** Array of objects ```toml [[custom_models]] name = "model_name" model = "provider/model-id" system_prompt = "Optional system prompt" ``` **Fields:** * `name` (required) - Short name for fuzzy matching * `model` (required) - Full OpenRouter model ID * `system_prompt` (optional) - System prompt applied to all requests **Examples:** ```toml # Specialized coder [[custom_models]] name = "coder" model = "anthropic/claude-sonnet-4.5" system_prompt = "Expert programmer. Provide well-commented, tested code following best practices." # Security analyst [[custom_models]] name = "security" model = "anthropic/claude-opus-4.5" system_prompt = "Security expert. Analyze for vulnerabilities, attack vectors, and provide mitigation strategies." # Quick alias (no system prompt) [[custom_models]] name = "fast" model = "google/gemini-2.5-flash" ``` ### Environment Variables #### OPENROUTER\_API\_KEY **Required:** Yes (either this or `api_key` in config) ```bash export OPENROUTER_API_KEY="sk-or-v1-..." ``` **Recommended approach:** ```bash # Add to ~/.bashrc or ~/.zshrc echo 'export OPENROUTER_API_KEY="sk-or-v1-..."' >> ~/.bashrc source ~/.bashrc ``` ### Configuration Examples #### Minimal Setup ```toml # Just the essentials api_key = "sk-or-v1-..." ``` #### Recommended Setup ```toml # API key via environment variable # default_model uses fuzzy matching default_model = "sonnet" # Dark theme optimized theme = "base16-ocean.dark" # One custom model for coding [[custom_models]] name = "coder" model = "anthropic/claude-sonnet-4.5" system_prompt = "Expert programmer. Provide clean, well-documented code." ``` #### Power User Setup ```toml default_model = "flash" theme = "Monokai Extended" [inline_colors] heading = "#61AFEF" inline_code = "#E5C07B" emphasis = "#ABB2BF" # Multiple specialized models [[custom_models]] name = "coder" model = "anthropic/claude-sonnet-4.5" system_prompt = "Expert programmer focusing on clean, tested code." [[custom_models]] name = "reviewer" model = "anthropic/claude-sonnet-4.5" system_prompt = "Senior code reviewer. Flag bugs, security issues, and performance problems." [[custom_models]] name = "architect" model = "anthropic/claude-opus-4.5" system_prompt = "Software architect. Consider scalability, maintainability, and tradeoffs." [[custom_models]] name = "writer" model = "openai/gpt-4o" system_prompt = "Technical writer. Create clear, comprehensive documentation." [[custom_models]] name = "debugger" model = "openai/gpt-4o" system_prompt = "Debugging expert. Analyze errors systematically and provide root cause analysis." ``` ### Validation zo validates your config on load and provides helpful error messages. #### Common Validation Errors **Empty Custom Model Name:** ``` Error: Custom model name cannot be empty ``` **Duplicate Model Names:** ``` Error: Duplicate custom model name: 'coder' ``` **Invalid Theme:** ``` Error: Theme 'invalid-theme' not found. Available themes: base16-ocean.dark, Solarized-dark, ... ``` ### Best Practices #### API Key Security ```bash # ✅ Use environment variable export OPENROUTER_API_KEY="..." # ✅ Restrict config file permissions chmod 600 ~/.config/zo/config.toml # ❌ Don't commit to git echo "config.toml" >> .gitignore ``` #### Model Organization Group custom models by use case: ```toml # Code-related [[custom_models]] name = "coder" # ... [[custom_models]] name = "reviewer" # ... # Writing-related [[custom_models]] name = "writer" # ... [[custom_models]] name = "docs" # ... ``` #### System Prompt Tips ```toml # ✅ Good - specific and actionable system_prompt = "You are a Rust expert. Provide idiomatic code with error handling, documentation, and tests." # ❌ Too vague system_prompt = "You are helpful." ``` ### Troubleshooting #### Config Not Found ```bash # Create default config zo +init-config # Verify location ls -la ~/.config/zo/config.toml ``` #### API Key Not Working ```bash # Check environment variable echo $OPENROUTER_API_KEY # Check config file cat ~/.config/zo/config.toml | grep api_key ``` #### Theme Not Working ```bash # Initialize config to see available themes zo +init-config # Check your theme name exactly matches # Theme names are case-sensitive ``` #### Custom Model Not Found ```bash # List all models (including custom) zo +list-models # Verify your custom model appears in the list ``` ### Next Steps * [Custom Models Guide →](/docs/custom-models) * [Model Selection →](/docs/models) * [Quick Start →](/docs/quick-start) ## Custom Models Create specialized AI assistants with custom system prompts tailored to your workflow. ### Overview Custom models let you: * Define role-specific AI assistants * Set consistent behavior across sessions * Create shortcuts for common use cases * Override built-in model names ### Quick Start #### Create Custom Model Edit `~/.config/zo/config.toml`: ```toml [[custom_models]] name = "coder" model = "anthropic/claude-sonnet-4.5" system_prompt = "You are an expert programmer. Provide concise, well-commented code with error handling." ``` #### Use Custom Model ```bash zo /coder "Implement a binary search tree in Rust" ``` The system prompt is automatically included in every request. ### Configuration #### Basic Format ```toml [[custom_models]] name = "short_name" # Used for /short_name model = "provider/model-id" # Full OpenRouter model ID system_prompt = "..." # Optional system prompt ``` #### Required Fields * `name` - Short name for fuzzy matching (cannot be empty) * `model` - Full OpenRouter model ID (cannot be empty) #### Optional Fields * `system_prompt` - Persona or instructions for the model ### Example Custom Models #### Code Reviewer ```toml [[custom_models]] name = "reviewer" model = "anthropic/claude-sonnet-4.5" system_prompt = """You are a senior code reviewer with 15 years of experience. Focus on: 1. Bugs and logical errors 2. Performance and optimization 3. Security vulnerabilities 4. Code readability 5. Best practices Provide: - Severity level (Critical/High/Medium/Low) - Specific line references when possible - Concrete suggestions with code examples - Positive feedback for good practices """ ``` Usage: ```bash zo /reviewer @code.rs "Review this code" git diff | zo /reviewer "Review my changes" ``` #### Technical Writer ```toml [[custom_models]] name = "writer" model = "openai/gpt-4o" system_prompt = """You are a professional technical writer. Guidelines: - Write clear, engaging documentation - Use examples liberally - Avoid jargon unless necessary - Structure content logically - Include code snippets when relevant - Target audience: developers """ ``` Usage: ```bash zo /writer @api.rs "Generate API documentation" zo /writer "Explain how authentication works in our app" ``` #### Teacher ```toml [[custom_models]] name = "teacher" model = "anthropic/claude-opus-4.5" system_prompt = """You are a patient, knowledgeable teacher. Approach: - Explain concepts from first principles - Use analogies and examples - Check for understanding - Adapt to student's level - Encourage questions - Provide practice exercises """ ``` Usage: ```bash zo /teacher "Explain how compilers work" zo --chat /teacher "Teach me about operating systems" ``` #### Debugger ```toml [[custom_models]] name = "debugger" model = "openai/gpt-4o" system_prompt = """You are a debugging expert. Process: 1. Analyze the error systematically 2. Identify root cause 3. Explain why it happened 4. Provide fix with code 5. Suggest prevention strategies 6. Include debugging steps Be thorough but concise. """ ``` Usage: ```bash cargo build 2>&1 | zo /debugger "Help me fix this" cat error.log | zo /debugger "Root cause analysis" ``` #### DevOps Specialist ```toml [[custom_models]] name = "devops" model = "anthropic/claude-sonnet-4.5" system_prompt = """You are a DevOps expert specializing in: - Infrastructure as code - CI/CD pipelines - Container orchestration - Monitoring and observability - Security and compliance - Cost optimization Prefer cloud-native, scalable solutions. Provide production-ready configurations. """ ``` Usage: ```bash zo /devops "Design a CI/CD pipeline for a Node.js app" zo /devops @Dockerfile "Optimize this for production" ``` #### Security Analyst ```toml [[custom_models]] name = "security" model = "anthropic/claude-opus-4.5" system_prompt = """You are a security expert. Analyze for: - Vulnerabilities (OWASP Top 10) - Attack vectors - Data exposure risks - Authentication/authorization flaws - Input validation issues Provide: - Severity ratings - Exploitation scenarios - Mitigation strategies - Code examples for fixes - References (CVE, OWASP) """ ``` Usage: ```bash zo /security @auth.js "Security review" zo /security "How should I implement password reset securely?" ``` ### Advanced Patterns #### Language-Specific Models ```toml [[custom_models]] name = "rustexpert" model = "anthropic/claude-sonnet-4.5" system_prompt = "Rust expert. Focus on: ownership, lifetimes, zero-cost abstractions, idiomatic patterns, and safety." [[custom_models]] name = "pythonista" model = "openai/gpt-4o" system_prompt = "Python expert. Follow PEP 8, use type hints, prefer comprehensions, focus on readability." [[custom_models]] name = "jswizard" model = "openai/gpt-4o" system_prompt = "JavaScript/TypeScript expert. Modern ES6+, async/await, TypeScript types, React best practices." ``` #### Task-Specific Models ```toml [[custom_models]] name = "sqlgen" model = "anthropic/claude-sonnet-4.5" system_prompt = "SQL expert. Generate optimized queries with proper indexing. Explain query plans. Focus on PostgreSQL." [[custom_models]] name = "regex" model = "openai/gpt-4o" system_prompt = "Regex expert. Provide patterns with explanations. Include test cases. Prefer readability." [[custom_models]] name = "api" model = "anthropic/claude-sonnet-4.5" system_prompt = "API design expert. Follow REST principles. Focus on: consistency, versioning, error handling, documentation." ``` #### Model Aliases Create shortcuts without system prompts: ```toml # Quick alias to favorite model [[custom_models]] name = "fast" model = "google/gemini-2.5-flash" # Override built-in names [[custom_models]] name = "pro" model = "anthropic/claude-opus-4.5" # Override geminipro ``` ### Custom Model Precedence Custom models take precedence over built-in models at each matching stage. #### Example ```toml [[custom_models]] name = "pro" model = "anthropic/claude-opus-4.5" ``` ```bash zo /pro "test" # Uses your custom 'pro' (Opus), not built-in 'geminipro' ``` ### System Prompt Best Practices #### Be Specific ```toml # ❌ Too vague system_prompt = "You are helpful." # ✅ Specific system_prompt = "You are a Rust expert. Provide idiomatic code with error handling, docs, and tests." ``` #### Include Context ```toml # ✅ Good system_prompt = """You are a frontend developer specializing in React. Focus on: - Functional components and hooks - TypeScript types - Accessibility (WCAG 2.1) - Performance optimization - Testing with Jest and RTL Provide production-ready code. """ ``` #### Set Expectations ```toml system_prompt = """Code reviewer. Provide: 1. Summary of changes 2. Critical issues (block merge) 3. Suggestions (nice to have) 4. Praise for good practices Format: Markdown with code blocks. """ ``` #### Use Constraints ```toml system_prompt = """Python code generator. Constraints: - Python 3.10+ - Type hints required - Maximum function length: 20 lines - Docstrings in Google style - Error handling with custom exceptions """ ``` ### Usage Patterns #### With File References ```bash zo /coder @spec.md "Implement this specification" zo /reviewer @main.rs @tests.rs "Review code and tests" ``` #### With STDIN ```bash git diff | zo /reviewer "Review these changes" cat error.log | zo /debugger "Analyze" ``` #### In Chat Mode ```bash zo --chat /teacher "Let's learn about databases" > Explain ACID properties > Give me examples > exit ``` System prompt applies to entire conversation. #### With Debug Mode ```bash zo --debug /coder "Write hello world" # Shows your custom system prompt ``` ### Listing Custom Models ```bash zo +list-models ``` Output: ``` Built-in models: sonnet -> anthropic/claude-sonnet-4.5 ... Custom models: coder -> anthropic/claude-sonnet-4.5 reviewer -> anthropic/claude-sonnet-4.5 writer -> openai/gpt-4o ``` ### Validation zo validates custom models on config load. #### Validation Rules * Model name cannot be empty * Model ID cannot be empty * No duplicate names (case-insensitive) #### Example Errors ``` Error: Custom model name cannot be empty Error: Custom model ID cannot be empty for model 'coder' Error: Duplicate custom model name: 'reviewer' ``` ### Model Selection Use custom models just like built-in models: ```bash # Slash command zo /coder "task" # CLI flag zo --model coder "task" # In chat zo --chat /reviewer "initial prompt" ``` Fuzzy matching works: ```bash zo /cod "task" # Matches 'coder' zo /review "task" # Matches 'reviewer' ``` ### Real-World Examples #### Software Development Team ```toml [[custom_models]] name = "dev" model = "anthropic/claude-sonnet-4.5" system_prompt = "Full-stack developer. Provide complete solutions with frontend, backend, and database code." [[custom_models]] name = "qa" model = "anthropic/claude-sonnet-4.5" system_prompt = "QA engineer. Generate comprehensive test cases. Include unit, integration, and E2E tests." [[custom_models]] name = "pm" model = "openai/gpt-4o" system_prompt = "Product manager. Help with: requirements, user stories, acceptance criteria, and roadmap planning." ``` #### Data Science Workflow ```toml [[custom_models]] name = "datascience" model = "openai/gpt-4o" system_prompt = "Data scientist. Provide statistical analysis, ML recommendations, and Python code with pandas/sklearn." [[custom_models]] name = "viz" model = "openai/gpt-4o" system_prompt = "Data visualization expert. Generate charts with matplotlib/seaborn/plotly. Focus on clarity and insights." ``` #### Content Creation ```toml [[custom_models]] name = "blog" model = "openai/gpt-4o" system_prompt = "Technical blogger. Write engaging posts. Use examples, analogies, and clear structure." [[custom_models]] name = "docs" model = "openai/gpt-4o" system_prompt = "Documentation writer. Create clear API docs, guides, and tutorials. Include examples and common pitfalls." ``` ### Tips #### Model Choice Match model capability to task complexity: ```toml # Fast, simple tasks [[custom_models]] name = "quick" model = "google/gemini-2.5-flash" # Complex reasoning [[custom_models]] name = "think" model = "anthropic/claude-opus-4.5" ``` #### Iterative Refinement Start simple, add details as needed: ```toml # Version 1 system_prompt = "Code reviewer." # Version 2 system_prompt = "Code reviewer. Focus on bugs and performance." # Version 3 system_prompt = """Code reviewer focusing on: 1. Bugs and edge cases 2. Performance and optimization 3. Security vulnerabilities 4. Code clarity and maintainability """ ``` #### Test Your Prompts ```bash # Test with debug mode zo --debug /coder "simple task" # Review the system prompt sent # Test behavior zo /coder "Write hello world in 5 languages" # Verify output matches expectations ``` ### Next Steps * [Configuration →](/docs/configuration) * [Model Selection →](/docs/models) * [Examples →](/examples) ## File Output with Tool Calls Let AI models write and update files directly using `!filename` syntax. zo provides a security-first approach with beautiful diff visualization and interactive approval. ### Quick Start #### Create New Files Use `!filename` to have the AI create a new file: ```bash zo 'Create a Python hello world program in !hello.py' ``` The AI writes the code directly to `hello.py`. #### Update Existing Files Use `@!filename` to let the AI see and modify existing files: ```bash zo 'Add error handling to @!main.rs' ``` zo shows you a beautiful colored diff and asks for approval before saving. #### Auto-Approve Changes Skip the approval prompt with `--yes` or `-y`: ```bash zo --yes 'Add type hints to @!script.py' zo -y 'Update dependencies in @!Cargo.toml' ``` ### Syntax Overview #### Write-Only Mode: `!filename` The model can write to the file but doesn't see existing content: ```bash zo 'Write a Rust HTTP server in !server.rs' ``` **Use when:** * Creating new files * You want the AI to generate from scratch * File content isn't relevant to the task #### Read-Write Mode: `@!filename` The model can read existing content and make updates: ```bash zo 'Refactor this function in @!utils.py to use async' ``` **Use when:** * Updating existing files * AI needs to see current content * Making incremental changes ### How It Works #### Tool Calling API zo uses OpenRouter's tool calling API with a `save_file` tool. When you use `!` or `@!` syntax: 1. zo registers the files as writable in the tool definition 2. The AI can call `save_file(path, content)` 3. zo validates the path and content 4. Shows a diff for existing files 5. Asks for approval (unless `--yes` flag) 6. Writes the file if approved #### Security Model **Whitelist Approach:** Only files explicitly marked with `!` or `@!` can be written. ```bash # ✅ Can write to output.txt zo 'Save results to !output.txt' # ❌ Cannot write to secret.txt (not in whitelist) zo 'Also save to secret.txt' # AI can't write this ``` **Path Validation:** * All absolute paths rejected (`/etc/passwd` ❌) * Path traversal blocked (`../../../etc/passwd` ❌) * Paths normalized before comparison * Only relative paths from current directory allowed **User Approval:** * Overwrites require approval (unless `--yes`) * Beautiful diff display shows changes * Interactive confirmation prompt * Can reject changes safely #### Diff Display When updating existing files, zo shows a colored diff: ``` 📝 Changes to main.rs: -fn main() {} +fn main() { + println!("Hello, world!"); +} Apply changes? [y/N]: ``` **Colors:** * 🟥 Red: Removed lines (-) * 🟩 Green: Added lines (+) * ⬜ Context lines (unchanged) ### Use Cases #### Code Generation Create complete files from prompts: ```bash # Single file zo 'Create a FastAPI hello world in !main.py' # Multiple files zo 'Create !README.md with docs and !LICENSE with MIT license' # Complete project zo 'Create a Rust CLI project: !Cargo.toml, !src/main.rs, !src/lib.rs' ``` #### Incremental Refactoring Update code step by step: ```bash zo --chat @!legacy_code.py 'Let us modernize this step by step' > Add type hints > Convert to async > Add error handling > exit ``` Each change shows a diff and can be approved individually. #### Documentation Generation Generate docs directly to files: ```bash # From source code zo @src/main.rs @src/lib.rs 'Generate API docs in !API.md' # From README zo @README.md 'Create !CHANGELOG.md from commit history style' ``` #### Configuration Updates Modify config files with AI assistance: ```bash # Add features zo @!nginx.conf 'Add rate limiting and caching rules' # Fix issues zo @!package.json 'Add missing TypeScript dependencies' # Upgrade zo @!Cargo.toml 'Upgrade all dependencies to latest compatible versions' ``` #### Test Generation Create test files based on implementation: ```bash # Unit tests zo @!app.py 'Generate comprehensive unit tests in !test_app.py' # Integration tests zo @!api.rs 'Create integration tests in !tests/integration_test.rs' ``` #### Code Migration Convert between languages or versions: ```bash # Language conversion zo @!old_api.js 'Convert to TypeScript in !new_api.ts' # Version upgrade zo @!python2_script.py 'Migrate to Python 3 with type hints' # Framework migration zo @!jquery_app.js 'Convert to React in !App.jsx' ``` #### Batch Operations Handle multiple files at once: ```bash # Generate project structure zo 'Create a Rust CLI project: !Cargo.toml, !src/main.rs, !README.md, !LICENSE' # Update related files zo @!package.json @!tsconfig.json 'Upgrade to latest TypeScript and update configs' # Code review with fixes zo @!buggy_code.rs 'Review and fix bugs, save to @!buggy_code.rs' ``` ### Chat Mode Integration File output works seamlessly in chat mode: #### Iterative Development ```bash zo --chat 'Let us build a web scraper' > Write the basic scraper to !scraper.py # AI creates the file, shows content, asks approval > Add retry logic with exponential backoff # AI updates the file, shows diff, asks approval > Create configuration file !config.yaml # AI creates config file > Write unit tests to !test_scraper.py # AI creates test file > Update !README.md with usage instructions # AI creates/updates README > exit ``` #### Files Persist Across Turns ```bash zo --chat 'Build a REST API' > Create !models.py with User and Post models # Models file created > Now create !routes.py with CRUD endpoints # Routes file created > Add authentication to @!models.py and @!routes.py # Both files updated with diffs shown > exit ``` The AI remembers which files exist and can reference them in subsequent messages. ### Advanced Patterns #### Combining Input and Output Read from one file, write to another: ```bash # Transform data zo @input.json 'Convert to CSV and save in !output.csv' # Generate from template zo @template.rs 'Create a similar file for HTTP in !http_handler.rs' # Split functionality zo @monolith.py 'Extract auth logic to !auth.py and update @!monolith.py' ``` #### With STDIN Combine piped input with file output: ```bash # Generate from build errors cargo build 2>&1 | zo 'Create !BUGS.md documenting these errors and fixes' # Documentation from git history git log --oneline -20 | zo 'Generate !CHANGELOG.md from these commits' # Analysis to file cat large_log.txt | zo 'Summarize errors and patterns in !analysis.md' ``` #### With Custom Models Use specialized models for file operations: ```bash # Code generation zo /coder 'Implement a LRU cache in !cache.rs' # Documentation zo /writer @api.rs 'Generate user-facing docs in !USER_GUIDE.md' # Review and fix zo /reviewer @!buggy_code.rs 'Review and fix issues' ``` ### Important Notes #### No Streaming File output disables streaming (API limitation with tool calls): ```bash zo 'Create !output.py' # Response appears after completion, not progressively ``` The full response is displayed once the model finishes, including all file operations. #### Tool Call Feedback Clear feedback for each file operation: ``` ✓ Created hello.py (42 lines) ✓ Updated main.rs (15 lines changed) ✗ Skipped secret.txt (not in whitelist) ``` #### Parent Directories Must Exist zo won't create nested directories: ```bash # ❌ Fails if src/ doesn't exist zo 'Create !src/lib.rs' # ✅ Create directory first mkdir -p src zo 'Create !src/lib.rs' ``` #### Model Compatibility File output requires models that support tool calling: * ✅ Claude (Sonnet, Opus, Haiku) * ✅ GPT-4, GPT-4o * ✅ Most modern models on OpenRouter * ❌ Some older or simpler models If a model doesn't support tools, zo shows an error. ### Security Best Practices #### Use Specific Filenames Always explicitly list files that can be written: ```bash # ✅ Good - specific whitelist zo 'Analyze data and save to !results.txt' # ❌ Risky - vague instructions zo 'Analyze data and save somewhere' ``` #### Review Diffs Carefully Don't auto-approve (`--yes`) unless you trust the operation: ```bash # ⚠️ Careful with auto-approve zo --yes @!production_config.yaml 'Optimize settings' # ✅ Better - review changes zo @!production_config.yaml 'Optimize settings' # Review diff, then approve or reject ``` #### Validate Critical Files For important files, review in chat mode: ```bash zo --chat @!critical_code.rs 'Let us optimize this' > Add performance improvements # Review diff before approving > Actually, revert that change > Try a different approach # Iterative with full control > exit ``` #### Use Version Control Always have files under version control: ```bash # Before AI modifications git add . git commit -m "Before AI changes" # Make AI changes zo @!src/lib.rs 'Refactor to use async' # Review with git git diff # Revert if needed git checkout -- src/lib.rs ``` ### Real-World Workflows #### Full Feature Implementation ```bash zo --chat 'Implement user authentication' > Create !models/user.rs with User struct and password hashing > Create !auth/login.rs with login logic > Create !auth/register.rs with registration logic > Update @!main.rs to include auth routes > Create !tests/auth_tests.rs with comprehensive tests > Create !docs/AUTH.md with authentication flow documentation > exit ``` #### Codebase Modernization ```bash # Analyze and update zo @!old_code.js 'Modernize to ES6+: save to @!old_code.js' # Generate migration guide zo @old_code.js @!old_code.js 'Document changes in !MIGRATION.md' ``` #### Documentation Sprint ```bash # Generate all docs zo @src/*.rs 'Create !README.md, !API.md, and !CONTRIBUTING.md' # Keep them in sync zo @src/main.rs @!README.md 'Update README with new features' ``` #### Configuration Management ```bash # Environment-specific configs zo @!config.toml 'Create !config.dev.toml and !config.prod.toml variants' # Validate and fix zo @!nginx.conf 'Review and fix any configuration errors' ``` #### Error Recovery ```bash # Document and fix cargo build 2>&1 | zo 'Explain errors in !ERRORS.md and create fixes in @!src/lib.rs' # Comprehensive debugging zo @!broken.rs @error.log 'Fix bugs and document changes in !FIXES.md' ``` ### Troubleshooting #### "File not in writable paths" You forgot to mark the file with `!` or `@!`: ```bash # ❌ Error zo 'Save to output.txt' # ✅ Fixed zo 'Save to !output.txt' ``` #### "Absolute path not allowed" Use relative paths only: ```bash # ❌ Error zo 'Save to !/home/user/output.txt' # ✅ Fixed cd /home/user zo 'Save to !output.txt' ``` #### "Parent directory doesn't exist" Create parent directories first: ```bash # ❌ Error zo 'Create !src/lib.rs' # src/ doesn't exist # ✅ Fixed mkdir -p src zo 'Create !src/lib.rs' ``` #### Model doesn't support tools Try a different model: ```bash # ❌ Might not work zo /flash 'Create !output.txt' # ✅ Use tool-capable model zo /sonnet 'Create !output.txt' zo /gpt4o 'Create !output.txt' ``` ### Tips and Tricks #### Dry Run with Debug Mode See what would happen without writing: ```bash zo --debug 'Create !test.py' # Shows the request, but you can cancel before sending ``` #### Generate From Templates ```bash # Use existing file as template zo @template.rs 'Create similar files !module1.rs and !module2.rs for HTTP and WebSocket' ``` #### Automated Backups ```bash # Before major changes cp important.rs important.rs.backup zo @!important.rs 'Major refactoring' # Review diff, approve/reject ``` #### Chain Operations ```bash # Analysis → Code → Tests → Docs zo @data.csv 'Analyze and create !analysis.md' zo @!analysis.md 'Implement solution in !solution.py' zo @!solution.py 'Generate tests in !test_solution.py' zo @!solution.py 'Create user docs in !SOLUTION.md' ``` ### Next Steps Now that you understand file output, explore: * [File References](/docs/file-references) - Read files with `@filename` * [Chat Mode](/docs/chat) - Iterative file modifications * [Custom Models](/docs/custom-models) - Specialized coding assistants * [Examples](/examples) - Real-world workflows with file I/O ## File References Include file contents in your prompts using the intuitive `@filename` syntax. zo reads the files and formats them clearly for the AI, making it easy to analyze code, review documents, or process data. ### Basic Usage #### Single File Include a single file in your prompt: ```bash zo @data.csv 'Analyze this dataset and find patterns' ``` zo reads `data.csv` and includes its contents in the request to the AI. #### Multiple Files Include multiple files in a single prompt: ```bash zo @version1.rs @version2.rs 'What are the key differences?' ``` Files are processed in order and each is clearly labeled for the AI. #### With Model Selection Combine file references with slash commands: ```bash zo /sonnet @src/main.rs "Review for bugs and performance issues" ``` The model is selected first, then the file contents are included in the prompt. ### How It Works #### File Formatting Files are formatted with XML-style tags for clarity: ```xml col1,col2,col3 1,2,3 4,5,6 ``` This format: * Makes it clear to the AI where each file begins and ends * Preserves the exact filename for context * Handles multi-line content cleanly * Works well with AI language models #### Message Order When you use multiple input sources, they're combined in this order: 1. **File references** - Provide context first 2. **Prompt text** - Your natural language question 3. **STDIN** - Any piped input (if present) For example: ```bash cat log.txt | zo @config.toml "Why is this error occurring?" ``` The AI receives: 1. Contents of `config.toml` (file reference) 2. Your question: "Why is this error occurring?" 3. Contents from `log.txt` (STDIN) ### Use Cases #### Code Analysis Analyze a single file: ```bash zo @app.py "Find potential bugs and suggest improvements" ``` Compare implementations: ```bash zo @old_version.c @new_version.c "Explain the improvements made" ``` #### Code Review Review with a specific model: ```bash zo /sonnet @src/main.rs "Review for bugs and performance issues" ``` Multi-file review: ```bash zo @api.rs @types.rs "Check if the API matches the type definitions" ``` #### Documentation Generation Generate docs from code: ```bash zo @api.rs "Generate API documentation in markdown format" ``` Multiple files: ```bash zo @*.rs "Generate comprehensive API documentation with examples" ``` #### Data Processing Analyze datasets: ```bash zo @sales_data.csv "Calculate summary statistics and identify trends" ``` Transform formats: ```bash zo @input.json "Convert this to CSV format with headers" ``` #### Configuration Analysis Understand config files: ```bash zo @config.toml "Explain what each setting does" ``` Suggest improvements: ```bash zo @nginx.conf "Review this config and suggest optimizations" ``` #### Learning from Code Explain complex code: ```bash zo @algorithm.c "Explain this algorithm step by step for a beginner" ``` Understand new codebases: ```bash zo @main.go @types.go "Explain how this application works" ``` ### Advanced Patterns #### Combining with STDIN Use files for context and STDIN for input: ```bash git diff | zo @README.md "Do these code changes require README updates?" ``` The AI receives: * `README.md` contents (for context) * Your question * The git diff output (changes to review) #### Chat Mode with Files Start a chat with file context: ```bash zo --chat @complex_code.rs "Let's refactor this together" > Make it more functional > Add error handling > Now add comprehensive tests > exit ``` File references in subsequent messages: ```bash zo --chat "Let's review some code" > @main.rs What does this do? > @tests.rs Are these tests comprehensive? > exit ``` #### Multiple File Workflows Architecture review: ```bash zo @schema.sql @models.py "Does the database schema match the Python models?" ``` Debug session: ```bash zo @error.log @app.rs "Why is this error occurring and how do I fix it?" ``` Refactoring: ```bash zo @old_code.py "Refactor this to use async/await and add type hints" ``` ### Path Handling #### Relative Paths Reference files relative to your current directory: ```bash zo @src/main.rs "Review this code" zo @../config.toml "Explain this config" zo @./data/input.csv "Analyze this data" ``` #### Absolute Paths Use full paths: ```bash zo @/home/user/project/src/main.rs "Review this" zo @/var/log/app.log "Find error patterns" ``` #### Wildcards Some shells expand wildcards before zo sees them: ```bash # Shell expands to: zo @file1.rs @file2.rs @file3.rs zo @*.rs "Generate documentation" ``` ### Error Handling #### Missing Files If a file doesn't exist, zo shows a clear error: ```bash zo @nonexistent.txt "analyze" # Error: Failed to read file 'nonexistent.txt': No such file or directory ``` #### Unreadable Files If you don't have permission: ```bash zo @/root/secret.txt "read" # Error: Failed to read file '/root/secret.txt': Permission denied ``` #### In Chat Mode Errors during chat don't exit the session: ```bash zo --chat "Let's work together" > @missing.txt analyze this # Error: Failed to read file 'missing.txt': No such file or directory > @correct.txt analyze this instead # Works normally ``` ### Technical Details #### File Reading * Files are read from disk when zo starts (or when you send a message in chat mode) * Contents are cached in memory for the request * Large files are supported (limited by available memory) * Binary files can be referenced but may not produce useful results * UTF-8 encoding is assumed #### Supported File Types File references work with any text file: * **Code:** `.rs`, `.py`, `.js`, `.go`, `.c`, `.cpp`, `.java`, etc. * **Data:** `.csv`, `.json`, `.xml`, `.yaml`, `.toml`, etc. * **Docs:** `.md`, `.txt`, `.html`, `.rst`, etc. * **Config:** `.conf`, `.ini`, `.env`, `.config`, etc. * **Logs:** `.log`, any text-based log format #### Parsing Logic zo detects file references using character-by-character parsing: 1. Looks for `@` character 2. Followed by non-whitespace characters (the filename) 3. Terminated by whitespace or end of input 4. Files at the end of input work correctly (no trailing space needed) Examples: ```bash zo @file.txt analyze # ✅ Works zo analyze @file.txt # ✅ Works zo @file.txt # ✅ Works (no trailing space needed) zo @file1.txt @file2.txt # ✅ Both files parsed zo "@file with spaces.txt" # ❌ Quotes not supported, use paths without spaces ``` ### Best Practices #### Clear Prompts Be specific about what you want: ```bash # ✅ Good zo @app.py "Find potential security vulnerabilities in authentication" # ❌ Vague zo @app.py "check this" ``` #### Right Model for the Job Use appropriate models: ```bash # Complex code review zo /sonnet @main.rs "Comprehensive review with performance analysis" # Quick syntax check zo /flash @script.sh "Does this bash script have syntax errors?" ``` #### File Order Matters Put the most important files first: ```bash # Main file first, then dependencies zo @main.rs @lib.rs @types.rs "Explain the architecture" ``` #### Combine Features Mix file references with other zo features: ```bash # With STDIN git diff | zo @old_version.rs "Compare the diff with the old version" # With custom models zo /reviewer @pr_changes.rs "Review this PR" # With chat mode zo --chat @codebase.rs "Let's discuss the architecture" ``` ### Real-World Examples #### Debugging Find the root cause: ```bash zo @error.log @app.py "Why is this error occurring?" ``` #### Code Migration Modernize code: ```bash zo @legacy.py "Convert this Python 2 code to Python 3 with type hints" ``` #### Security Review Audit code: ```bash zo /security @auth.rs @api.rs "Find security vulnerabilities" ``` #### Performance Analysis Optimize code: ```bash zo @slow_function.c "How can I optimize this for better performance?" ``` #### Test Generation Create tests: ```bash zo @lib.rs "Generate comprehensive unit tests with edge cases" ``` #### API Documentation Document APIs: ```bash zo @api.rs @types.rs "Generate OpenAPI/Swagger documentation" ``` #### Refactoring Improve code structure: ```bash zo @messy_code.js "Refactor this to use modern ES6+ features" ``` #### Architecture Review Validate design: ```bash zo @schema.sql @models.py @api.py "Review the overall architecture" ``` ### Limitations #### Binary Files Binary files (images, executables, etc.) can be referenced but won't produce useful results: ```bash # Won't work well zo @image.png "Describe this image" ``` For vision tasks, you need a vision-capable model and proper image encoding (not currently supported). #### File Size Very large files (100MB+) can: * Take time to read * Use significant memory * Hit API token limits * Increase costs Consider using filters or excerpts: ```bash # Instead of the full log zo @huge.log 'analyze' # Use excerpts tail -n 1000 huge.log | zo 'Analyze recent errors' ``` #### No Directory References You can't reference entire directories: ```bash # Doesn't work zo @src/ "analyze all files" # Instead, use shell expansion zo @src/*.rs "analyze these files" ``` ### Tips and Tricks #### Quick File Inspection ```bash # One-liner to understand a file zo @unknown.py "What does this do in one sentence?" ``` #### Compare Versions ```bash # Before and after zo @before.rs @after.rs "Summarize the changes" ``` #### Generate Based on Example ```bash # Use a file as a template zo @example.rs "Create a similar file but for HTTP handling" ``` #### Extract Information ```bash # Pull specific data zo @config.json "Extract all database connection strings" ``` #### Validate Correctness ```bash # Check implementations zo @interface.ts @implementation.ts "Does the implementation match the interface?" ``` ### Next Steps Now that you understand file references, explore: * [STDIN Pipelines](/docs/stdin) - Combine with piped input * [Chat Mode](/docs/chat) - Use files in multi-turn conversations * [Custom Models](/docs/custom-models) - Create specialized reviewers and analyzers * [Examples](/examples) - See real-world workflows ## Installation ### Prerequisites * **OpenRouter API Key** - Get one at [https://openrouter.ai/keys](https://openrouter.ai/keys) * **Already have API keys for OpenAI, Anthropic, or Google?** Use OpenRouter's [BYOK (Bring Your Own Key)](https://openrouter.ai/settings/keys) feature to route requests through your existing accounts without additional payment processing through OpenRouter. * **Rust** (optional, only for building from source) ### Installation Methods #### Method 1: Pre-built Binary (Recommended) Download the latest release for your platform from [GitHub Releases](https://github.com/svent/zo/releases). #### Method 2: Cargo Install ```bash cargo install zo-cli ``` #### Method 3: Build from Source ```bash # Clone the repository git clone https://github.com/svent/zo.git cd zo # Build release binary cargo build --release # Install sudo cp target/release/zo /usr/local/bin/ ``` ### Setup #### 1. Get OpenRouter API Key 1. Visit [https://openrouter.ai/keys](https://openrouter.ai/keys) 2. Sign up or log in 3. Create a new API key 4. Copy the key (starts with `sk-or-v1-`) **💡 Tip: Already have OpenAI, Anthropic, or Google API keys?** You can use OpenRouter's **BYOK (Bring Your Own Key)** feature to use your existing provider keys instead of adding funds to OpenRouter. This lets you use zo as an LLM router without payment processing through OpenRouter: 1. Go to [https://openrouter.ai/settings/keys](https://openrouter.ai/settings/keys) 2. Add your existing provider API keys (OpenAI, Anthropic, Google, etc.) 3. OpenRouter will route requests through your accounts 4. You'll be billed directly by your providers #### 2. Configure API Key You have two options: ##### Option A: Environment Variable (Recommended) ```bash # Set for current session export OPENROUTER_API_KEY="sk-or-v1-..." # Make it persistent (add to ~/.bashrc or ~/.zshrc) echo 'export OPENROUTER_API_KEY="sk-or-v1-..."' >> ~/.bashrc source ~/.bashrc ``` ##### Option B: Configuration File ```bash # Initialize config file zo +init-config # Edit the config file vi ~/.config/zo/config.toml # Add your API key api_key = "sk-or-v1-..." ``` #### 3. Verify Installation ```bash # Test with a simple query zo 'What is Rust?' # Should see a streaming response ``` ### Configuration #### Initialize Config File ```bash zo +init-config ``` This creates `~/.config/zo/config.toml` with helpful comments and examples. #### Config File Location * **Linux/macOS:** `~/.config/zo/config.toml` #### Basic Configuration ```toml # API Key (alternatively use OPENROUTER_API_KEY env var) api_key = "sk-or-v1-..." # Default model (uses fuzzy matching) default_model = "flash" # Syntax highlighting theme for code blocks theme = "base16-ocean.dark" # Custom colors for inline markdown elements [inline_colors] heading = "cyan" inline_code = "yellow" emphasis = "white" ``` #### Advanced Configuration See [Configuration](/docs/configuration) for details on: * Custom models with system prompts * Theme selection * Color customization ### Troubleshooting #### "API key not found" Make sure you've set the API key via environment variable or config file: ```bash # Check environment variable echo $OPENROUTER_API_KEY # Or check config file cat ~/.config/zo/config.toml ``` #### "Model not found" List available models: ```bash zo +list-models ``` Use fuzzy matching - `/son` matches `sonnet`, `/gpt` matches `gpt4`, etc. #### Permission Denied Make sure the binary is executable: ```bash chmod +x /usr/local/bin/zo ``` #### Command Not Found Ensure `/usr/local/bin` is in your PATH: ```bash echo $PATH # Add to PATH if needed (in ~/.bashrc or ~/.zshrc) export PATH="/usr/local/bin:$PATH" ``` ### Upgrading #### Pre-built Binary Download and replace the binary: ```bash curl -L https://github.com/svent/zo/releases/latest/download/zo-linux-x86_64 -o zo chmod +x zo sudo mv zo /usr/local/bin/ ``` #### Cargo Install ```bash cargo install zo-cli --force ``` #### From Source ```bash cd zo git pull cargo build --release sudo cp target/release/zo /usr/local/bin/ ``` ### Uninstallation ```bash # Remove binary sudo rm /usr/local/bin/zo # Remove config (optional) rm -rf ~/.config/zo # Remove from shell config (if using environment variable) # Edit ~/.bashrc or ~/.zshrc and remove OPENROUTER_API_KEY line ``` ### Next Steps * [Quick Start →](/docs/quick-start) * [Configuration →](/docs/configuration) * [View Examples →](/examples) ## Model Selection zo provides intelligent fuzzy model selection with access to 50+ AI models through OpenRouter. ### Quick Reference #### Built-in Model Shortcuts | Short Name | Full Model ID | Best For | Speed | Cost | | ----------- | --------------------------- | ---------------------------------- | ------ | --------- | | `sonnet` | anthropic/claude-sonnet-4.5 | Complex reasoning, code analysis | Medium | Medium | | `sonnet3` | anthropic/claude-3.5-sonnet | Previous Claude version | Medium | Medium | | `opus` | anthropic/claude-opus-4.5 | Highest quality Claude | Slow | High | | `haiku` | anthropic/claude-3-haiku | Fast, simple tasks | Fast | Low | | `flash` | google/gemini-2.5-flash | **Default** - Balanced performance | Fast | Low | | `geminipro` | google/gemini-3-pro-preview | Google's most capable | Medium | Medium | | `gpt4` | openai/gpt-4-turbo | Latest GPT-4 | Medium | High | | `gpt4o` | openai/gpt-4o | GPT-4 Optimized | Medium | Medium | | `gpt4omini` | openai/gpt-4o-mini | Fast, cheap GPT-4 | Fast | Low | | `o1` | openai/o1 | Reasoning-focused GPT | Slow | Very High | | `o1mini` | openai/o1-mini | Lighter reasoning model | Medium | High | | `grok` | x-ai/grok-4 | X.AI's latest | Medium | Medium | ### Using Models #### Slash Command Most common method - use `/` followed by model name: ```bash zo /sonnet 'Explain async/await in Rust' zo /gpt4 'Write a poem about programming' zo /flash 'Quick question: what is TCP?' ``` #### CLI Flag Override any model selection: ```bash zo --model opus 'Complex reasoning task' zo --model haiku 'Simple question' ``` #### Config Default Set in `~/.config/zo/config.toml`: ```toml default_model = "sonnet" ``` Now `zo 'question'` uses Sonnet instead of Flash. #### Priority Order Model selection priority (highest to lowest): * **CLI `--model` flag** (highest priority) * **Slash command** in prompt (`/sonnet`) * **`default_model`** from config file * **Hardcoded fallback:** `flash` (lowest priority) Example: ```bash # Uses opus (CLI flag wins) zo --model opus /sonnet 'test' # Uses sonnet (slash command) zo /sonnet 'test' # Uses config default (if set) zo 'test' # Uses flash (fallback) zo 'test' # With no config default ``` ### Fuzzy Matching zo uses intelligent 3-stage matching to find models: #### Stage 1: Exact Match (case-insensitive) ```bash zo /sonnet "test" # Exact match zo /SONNET "test" # Also matches (case-insensitive) ``` #### Stage 2: Substring Match Input contained in model name: ```bash zo /son "test" # Matches 'sonnet' (son ⊂ sonnet) zo /pro "test" # Matches 'geminipro' (pro ⊂ geminipro) zo /mini "test" # Matches 'gpt4omini' or 'o1mini' ``` #### Stage 3: Fuzzy Match Uses SkimMatcherV2 algorithm (minimum score: 50): ```bash zo /sonet "test" # Typo - fuzzy matches 'sonnet' zo /gpt "test" # Matches 'gpt4' zo /claud "test" # Matches 'claude' models ``` #### Did You Mean? When model not found, zo suggests alternatives: ```bash zo /sonnett "test" # Error: Model 'sonnett' not found. # # Did you mean: # sonnet -> anthropic/claude-sonnet-4.5 (score: 92) # sonnet3 -> anthropic/claude-3.5-sonnet (score: 85) # # Available models: # sonnet, opus, haiku, flash, ... ``` ### Model Characteristics #### Anthropic Claude Models **Claude Sonnet 4.5** (`/sonnet`) * Best for: Code, analysis, technical writing * Strengths: Reasoning, instruction following, code quality * Speed: Medium * Context: 200K tokens **Claude 3 Opus** (`/opus`) * Best for: Complex tasks, highest quality * Strengths: Deep analysis, nuanced understanding * Speed: Slower * Context: 200K tokens **Claude 3 Haiku** (`/haiku`) * Best for: Quick tasks, high volume * Strengths: Speed, cost efficiency * Speed: Fast * Context: 200K tokens #### Google Gemini Models **Gemini 2.5 Flash** (`/flash`) - **Default** * Best for: General use, balanced performance * Strengths: Speed, cost, quality balance * Speed: Very fast * Context: 1M tokens **Gemini 2.5 Pro** (`/geminipro`) * Best for: Complex reasoning, large context * Strengths: Long context, multimodal * Speed: Medium * Context: 2M tokens #### OpenAI Models **GPT-4 Turbo** (`/gpt4`) * Best for: General intelligence tasks * Strengths: Versatility, knowledge * Speed: Medium * Context: 128K tokens **GPT-4o** (`/gpt4o`) * Best for: Multimodal, optimized performance * Strengths: Speed, quality * Speed: Medium-fast * Context: 128K tokens **GPT-4o Mini** (`/gpt4omini`) * Best for: Cost-effective GPT-4 access * Strengths: Speed, low cost * Speed: Fast * Context: 128K tokens **o1** (`/o1`) * Best for: Complex reasoning, math, coding * Strengths: Deep reasoning, problem solving * Speed: Slow * Cost: Very high * Context: 200K tokens **o1-mini** (`/o1mini`) * Best for: Coding, STEM tasks * Strengths: Fast reasoning * Speed: Medium * Cost: High #### X.AI Models **Grok 3** (`/grok`) * Best for: Real-time information * Strengths: Up-to-date knowledge * Speed: Medium * Context: 128K tokens ### Model Selection Strategy #### By Task Type **Code Review & Analysis:** ```bash zo /sonnet @code.rs "Review this code" ``` **Quick Questions:** ```bash zo /flash "What is TCP?" zo /haiku "Explain in one sentence" ``` **Complex Reasoning:** ```bash zo /opus "Design a distributed system" zo /o1 "Solve this algorithm problem" ``` **Writing & Documentation:** ```bash zo /gpt4o @api.rs "Generate documentation" ``` **Cost-Sensitive:** ```bash zo /flash "question" # Cheapest, very good zo /haiku "question" # Cheap, fast zo /gpt4omini "question" # Cheap GPT-4 ``` **Quality-Critical:** ```bash zo /opus "important task" # Highest quality Claude zo /o1 "complex reasoning" # Best reasoning ``` #### By Speed Need **Immediate (under 2 seconds):** * `/flash`, `/haiku`, `/gpt4omini` **Balanced (2 to 5 seconds):** * `/sonnet`, `/gpt4o`, `/geminipro` **Thorough (5 to 15 seconds):** * `/opus`, `/o1` #### By Context Size **Large Documents:** ```bash # Gemini has largest context cat large_file.txt | zo /geminipro "Analyze" cat huge_file.txt | zo /flash "Summarize" # 1M context ``` **Normal Use:** ```bash zo /sonnet @file.rs "Review" # 200K context zo /gpt4 @doc.md "Explain" # 128K context ``` ### Custom Models Define your own models with system prompts. #### Configuration ```toml # ~/.config/zo/config.toml [[custom_models]] name = "coder" model = "anthropic/claude-sonnet-4.5" system_prompt = "You are an expert programmer. Provide concise, well-commented code with error handling." [[custom_models]] name = "reviewer" model = "anthropic/claude-sonnet-4.5" system_prompt = "You are a senior code reviewer. Focus on bugs, performance, security, and best practices." [[custom_models]] name = "fast" model = "google/gemini-3-flash-preview" # No system prompt - just an alias ``` #### Using Custom Models ```bash # Use just like built-in models zo /coder "Implement a binary tree" zo /reviewer @code.rs "Review this" zo /fast "Quick question" ``` #### Custom Model Precedence Custom models take precedence over built-in models at each matching stage: ```toml # Override built-in 'pro' [[custom_models]] name = "pro" model = "anthropic/claude-opus-4.5" ``` ```bash zo /pro "test" # Uses your custom 'pro' (Opus), not built-in 'geminipro' ``` ### Listing Models #### Show All Models ```bash zo +list-models ``` Output: ``` Built-in models: sonnet -> anthropic/claude-sonnet-4.5 opus -> anthropic/claude-opus-4.5 haiku -> anthropic/claude-3-haiku flash -> google/gemini-2.5-flash ... Custom models: coder -> anthropic/claude-sonnet-4.5 reviewer -> anthropic/claude-sonnet-4.5 fast -> google/gemini-2.5-flash ``` #### Filter Models ```bash zo +list-models | grep claude zo +list-models | grep google zo +list-models | grep custom ``` ### Debug Mode Verify model selection before sending request: ```bash zo --debug /sonnet "test" ``` Output: ``` Model: sonnet (anthropic/claude-sonnet-4.5) Prompt: test Send request? [y/N] ``` With custom model: ```bash zo --debug /coder "test" ``` Output: ``` Model: coder (anthropic/claude-sonnet-4.5) System Prompt: You are an expert programmer... Prompt: test Send request? [y/N] ``` ### Best Practices #### Start Fast, Scale Up ```bash # Try with fast model first zo /flash "question" # If insufficient, use smarter model zo /sonnet "question" # For critical tasks, use best zo /opus "question" ``` #### Match Model to Task ```bash # ❌ Overkill zo /opus "What is 2+2?" # ✅ Appropriate zo /flash "What is 2+2?" # ❌ Underpowered zo /haiku "Design a complex distributed system" # ✅ Appropriate zo /opus "Design a complex distributed system" ``` #### Use Chat for Iteration ```bash # Start with good model zo --chat /sonnet "Let's build a feature" > Refine the approach > Add error handling > exit ``` #### Create Task-Specific Models ```toml [[custom_models]] name = "security" model = "anthropic/claude-opus-4.5" system_prompt = "Security expert. Analyze for vulnerabilities, attack vectors, and provide mitigation strategies." [[custom_models]] name = "perf" model = "anthropic/claude-sonnet-4.5" system_prompt = "Performance expert. Focus on optimization, profiling, and benchmarking." ``` ### Troubleshooting #### Model Not Found ```bash # Check available models zo +list-models # Use exact name from list zo /sonnet "test" # Or use fuzzy matching zo /son "test" ``` #### Wrong Model Selected ```bash # Use CLI flag to override zo --model opus "test" # Or be more specific zo /claude-opus "test" ``` #### Verify Selection ```bash # Always use debug mode when unsure zo --debug /model "test" ``` ### Next Steps * [Custom Models Guide →](/docs/custom-models) * [Configuration →](/docs/configuration) * [Examples →](/examples) ## Quick Start Get up and running with zo in 5 minutes. \:::info Already have OpenAI, Anthropic, or Google API keys? You can use OpenRouter's **BYOK (Bring Your Own Key)** feature to route requests through your existing accounts. Visit [https://openrouter.ai/settings/keys](https://openrouter.ai/settings/keys) to add your provider keys and get billed directly by your providers instead of through OpenRouter. \::: ### Basic Usage #### Simple Query ```bash zo 'What is Rust?' ``` This sends a query to the default model (`sonnet` - Claude Sonnet) and streams the response in real-time. #### With Model Selection ```bash # Use Claude Sonnet zo /sonnet 'Explain async/await in Rust' # Use GPT-4 zo /gpt4 'Write a poem about programming' # Use fuzzy matching zo /son 'test' # Matches 'sonnet' ``` #### Using CLI Flag ```bash zo --model opus 'Complex reasoning task' ``` ### File References Include file contents using `@filename` syntax: ```bash # Single file zo @code.rs 'Review this code for bugs' # Multiple files zo @v1.py @v2.py 'What are the differences?' # With model selection zo /sonnet @main.rs 'Add error handling' ``` ### File Output Let AI write files directly using `!filename` syntax: ```bash # Create a new file zo 'Write a Python hello world in !hello.py' # Update existing file (read + write) zo 'Add error handling to @!main.rs' # Generate tests from implementation zo @app.py 'Generate unit tests in !test_app.py' # Auto-approve changes (skip confirmation) zo --yes 'Add type hints to @!script.py' ``` zo shows a colored diff and asks for approval before writing. Use `@!file` when the AI needs to see existing content before modifying it. ### STDIN Pipelines Pipe command output for AI analysis: ```bash # Git diff analysis git diff | zo 'Summarize these changes' # Error diagnosis cargo build 2>&1 | zo /sonnet 'Explain these errors' # Log analysis tail -n 100 error.log | zo 'Find patterns' # System diagnostics ps aux | zo 'Which processes use too much memory?' ``` ### Chat Mode Have multi-turn conversations: ```bash zo --chat 'Let us discuss Rust lifetimes' > Can you give me an example? > What happens if I violate the rules? > exit ``` #### Chat with Initial Context ```bash # Start with file context zo --chat @code.rs 'Let us refactor this' # Start with piped input git diff | zo --chat 'Let us review these changes' ``` ### Debug Mode Inspect the request before sending: ```bash zo --debug /sonnet 'Test prompt' # Model: sonnet (anthropic/claude-sonnet-4.5) # Prompt: Test prompt # Send request? [y/N] ``` ### Configuration #### Initialize Config ```bash zo +init-config ``` This creates `~/.config/zo/config.toml` with examples and comments. #### Set Default Model ```toml # ~/.config/zo/config.toml default_model = "sonnet" ``` Now `zo 'query'` uses Sonnet instead of Flash. #### Create Custom Model ```toml [[custom_models]] name = "coder" model = "anthropic/claude-sonnet-4.5" system_prompt = "You are an expert programmer. Provide concise, well-commented code." ``` ```bash zo /coder 'Implement a binary search tree' ``` ### Common Workflows #### Code Review ```bash # Review current changes git diff | zo /sonnet 'Review for bugs and best practices' # Review specific file zo @src/main.rs 'Code review' # Review PR git diff main...feature | zo /reviewer 'Review this PR' ``` #### Error Debugging ```bash # Build errors cargo build 2>&1 | zo 'Explain and fix' # Test failures npm test 2>&1 | zo 'Why are these tests failing?' # Runtime errors cat error.log | zo /debugger 'Root cause analysis' ``` #### Documentation ```bash # Generate docs zo @lib.rs 'Generate API documentation' # Explain code zo @complex.c 'Explain this line by line' # README generation zo @*.rs 'Create README with examples' ``` #### Data Analysis ```bash # CSV analysis cat data.csv | zo 'Calculate statistics' # JSON processing curl -s api.example.com | zo 'Extract emails' # SQL generation zo @schema.sql 'Query top 10 customers by revenue' ``` #### File Generation ```bash # Generate from scratch zo 'Create a REST API in !server.py with health and users endpoints' # Transform code zo @old_api.js 'Convert to TypeScript in !api.ts' # Generate from build errors cargo build 2>&1 | zo 'Fix errors in @!src/lib.rs' # Multi-file generation zo 'Create !Cargo.toml and !src/main.rs for a CLI that counts words' ``` #### Learning ```bash # Concept explanation zo 'Explain TCP congestion control' # Code examples zo /teacher 'Explain Rust ownership with examples' # Command help man grep | zo 'Explain useful grep options' ``` ### Shell Integration Add to `~/.bashrc` or `~/.zshrc`: ```bash # Explain command explain() { echo "$*" | zo 'Explain this command' } # Get command suggestions howto() { zo 'How do I $* in bash?' } # Analyze errors fix() { "$@" 2>&1 | zo 'Why did this fail?' } # Aliases alias chat='zo --chat' alias review='zo /reviewer' ``` Usage: ```bash explain tar -xzf file.tar.gz howto find all python files modified today fix cargo build ``` ### Actions #### List Models ```bash zo +list-models # sonnet -> anthropic/claude-sonnet-4.5 # opus -> anthropic/claude-opus-4.5 # flash -> google/gemini-2.5-flash # ... ``` #### Initialize Config ```bash zo +init-config # Creates ~/.config/zo/config.toml ``` ### Tips & Tricks #### Model Selection Priority 1. CLI `--model` flag (highest) 2. Slash command in prompt (`/sonnet`) 3. `default_model` from config 4. Hardcoded fallback: `sonnet` #### Fuzzy Matching * Exact match: `/sonnet` → `sonnet` * Substring: `/pro` → `geminipro` * Fuzzy: `/son` → `sonnet` #### Combining Features ```bash # All features together cat data.csv | zo --debug /sonnet @schema.sql 'Analyze this data' # STDIN + debug + model + file + prompt ``` #### Chat Exit Commands * `exit` * `quit` * `q` * Ctrl+D #### API Key Sources 1. `OPENROUTER_API_KEY` environment variable 2. `api_key` in config file ### Next Steps * [File Output →](/docs/file-output) * [Progressive Streaming →](/docs/streaming) * [Model Selection →](/docs/models) * [View Examples →](/examples) * [Configuration →](/docs/configuration) ## STDIN Pipelines Pipe output from any command directly to zo for AI analysis. Works seamlessly with Unix philosophy to make AI a natural part of your command pipelines. ### Overview STDIN pipeline integration allows you to: * Analyze command output without intermediate files * Combine piped input with prompts and file references * Build complex data processing workflows * Integrate AI into automation and scripting ### How It Works zo uses the `IsTerminal` trait to detect piped input automatically. When STDIN is piped (not interactive), zo reads it and combines it with your prompt for the AI model. #### Message Construction When you pipe input to zo, the final message sent to the AI combines: 1. **File references** (if any `@filename` syntax used) 2. **Your prompt** (the text you provide) 3. **STDIN content** (the piped input) This ordering provides context first, then the question, then the data to analyze. ### Basic Usage #### Simple Pipeline ```bash # Pipe command output directly echo "Hello World" | zo 'Translate to Spanish' # Pipe file contents cat error.log | zo 'Summarize the errors' # Pipe stderr too cargo build 2>&1 | zo 'Explain these errors' ``` #### With Model Selection ```bash # Use specific model with piped input git diff | zo /sonnet 'Review these changes' # CLI flag also works ps aux | zo --model opus 'Which processes are problematic?' ``` #### With File References ```bash # Combine STDIN with file references git diff | zo @README.md 'Do these changes require README updates?' # Multiple files plus STDIN cat data.csv | zo @schema.sql @config.toml 'Validate this data' ``` ### Common Use Cases #### Code Review from Git ```bash # Review uncommitted changes git diff | zo 'Summarize these changes and check for bugs' # Review staged changes git diff --cached | zo /reviewer 'Review before I commit' # Review specific commit git show HEAD | zo 'Explain what this commit does and why' # Review PR changes git diff main...feature | zo 'Generate detailed PR review' # Review recent commits git log --oneline -20 | zo 'Summarize recent development activity' ``` #### Error Analysis ```bash # Rust build errors cargo build 2>&1 | zo /sonnet 'Explain these errors and how to fix them' # JavaScript test failures npm test 2>&1 | zo 'Why are these tests failing?' # Python runtime errors python script.py 2>&1 | zo /debugger 'Root cause analysis' # Go compilation errors go build 2>&1 | zo 'Fix these compilation errors' # Make errors make 2>&1 | zo 'What is wrong with my build?' ``` #### Log Analysis ```bash # Application logs tail -n 100 /var/log/nginx/error.log | zo 'Find patterns in these errors' # Docker logs docker logs myapp | zo 'Identify the root cause of the crash' # System logs journalctl -n 100 | zo 'Any security concerns?' # Custom app logs tail -f app.log | head -50 | zo 'Summarize recent activity' # Multi-file logs cat *.log | zo 'Find anomalies across all logs' ``` #### Data Processing ```bash # CSV analysis cat large_file.csv | zo 'Calculate summary statistics' # JSON extraction curl -s https://api.example.com/data | zo 'Extract all email addresses' # Data transformation cat input.json | zo 'Convert this to CSV format' # Data validation cat data.csv | zo @schema.json 'Validate against this schema' # SQL generation from data head -10 sample.csv | zo 'Generate SQL CREATE TABLE for this data' ``` #### System Diagnostics ```bash # Memory usage ps aux --sort=-%mem | head -20 | zo 'Which processes are using too much memory?' # Disk space df -h | zo 'Do I have any disk space issues?' # Network connections netstat -tuln | zo 'Any suspicious connections?' # Process tree pstree -p | zo 'Explain what is running on this system' # System resources top -b -n 1 | head -20 | zo 'System health check' ``` #### Documentation ```bash # Man page summaries man grep | zo 'Explain the most useful grep options with examples' # API documentation curl -s https://docs.rust-lang.org/book/ch04-00-understanding-ownership.html \ | zo 'Summarize the key concepts' # Code documentation cargo doc --no-deps 2>&1 | zo 'Any doc warnings I should fix?' # README generation ls -la | zo 'Generate directory structure documentation' ``` ### Advanced Workflows #### Multi-Stage Pipelines ```bash # Filter → Transform → Analyze cat access.log \ | grep "ERROR" \ | zo 'Categorize these errors and suggest fixes' # Fetch → Parse → Summarize curl -s https://api.github.com/repos/rust-lang/rust/issues \ | jq '.[].title' \ | zo 'Summarize trending issues' # Process → Validate → Report cat data.csv \ | awk -F',' '{print $1, $3}' \ | zo 'Check for invalid entries' ``` #### Combining with Chat Mode ```bash # Start chat with piped context cat error.log | zo --chat 'Let us debug this together' > What should I check first? > I tried that, what else? > exit # Initial context from git git diff | zo --chat /reviewer 'Let us review these changes' > Focus on the authentication code > What about security? > exit ``` #### Automation Scripts ```bash #!/bin/bash # automated-review.sh # Get changes diff=$(git diff --cached) if [ -z "$diff" ]; then echo "No staged changes" exit 0 fi # AI review echo "$diff" | zo /reviewer 'Quick review. Flag only critical issues.' # Check exit code if [ $? -ne 0 ]; then echo "Review failed" exit 1 fi echo "Review complete" ``` #### CI/CD Integration ```bash # In .gitlab-ci.yml or similar script: - git diff origin/main...HEAD | zo /reviewer 'Automated PR review' > review.md - cat review.md - grep -qi "critical" review.md && exit 1 || exit 0 ``` ### Shell Integration Add these functions to `~/.bashrc` or `~/.zshrc`: #### Quick Helpers ```bash # Explain command errors fix() { "$@" 2>&1 | zo 'Why did this fail and how do I fix it?' } # Analyze recent history history-analyze() { history | tail -20 | zo 'What have I been working on?' } # Commit message generator gcm() { git diff --cached | zo 'Generate conventional commit message' } # Log analyzer logs() { tail -n "${1:-100}" /var/log/syslog | zo 'Summarize errors' } ``` #### Usage Examples ```bash # Use fix function fix cargo build # Generate commit message gcm # Analyze logs logs 200 ``` ### Technical Details #### STDIN Detection zo uses Rust's `std::io::IsTerminal` trait: ```rust if stdin.is_terminal() == false { // STDIN is piped - read it let mut content = String::new(); stdin.read_to_string(&mut content)?; } ``` #### Empty STDIN Handling Empty STDIN is treated as `None` - no content added to the message. This prevents sending empty strings to the API. #### Character Encoding zo reads STDIN as UTF-8. Non-UTF-8 input may cause errors or be replaced with Unicode replacement characters. #### Size Limits While zo has no hard limit on STDIN size, keep in mind: * **API limits**: OpenRouter models have context window limits (typically 8K-200K tokens) * **Memory**: Very large inputs are loaded into memory * **Cost**: Larger inputs consume more tokens **Recommendation**: For files larger than 1MB, consider using file references (`@filename`) or filtering/sampling the data first. #### Exit Codes ```bash # Success echo "test" | zo 'analyze' echo $? # 0 # API error echo "test" | zo 'analyze' # (network failure) echo $? # 1 # Empty prompt and STDIN echo "" | zo "" # Error: No input provided ``` ### Best Practices #### ✅ Do This ```bash # Capture stderr with stdout command 2>&1 | zo 'analyze' # Limit large outputs tail -n 100 huge.log | zo 'summarize' # Combine with file context git diff | zo @CONTRIBUTING.md 'Check against guidelines' # Use specific models for specific tasks error.log | zo /debugger 'diagnose' ``` #### ❌ Avoid This ```bash # Don't pipe huge files without filtering cat 10GB.log | zo 'analyze' # Too large! # Don't forget stderr command | zo 'fix errors' # Errors might be on stderr # Don't pipe binary data cat image.png | zo 'analyze' # Text models only ``` ### Troubleshooting #### No Input Received **Problem**: zo says "No input provided" even though you piped data. **Solution**: Check if STDIN is actually empty: ```bash # Debug: check what's being piped command | tee /dev/tty | zo 'analyze' # Or save to file first command > output.txt cat output.txt | zo 'analyze' ``` #### Truncated Output **Problem**: Very long output gets truncated. **Solution**: Filter or sample the data: ```bash # Take first N lines head -100 huge.log | zo 'analyze' # Take last N lines tail -100 huge.log | zo 'analyze' # Sample every Nth line awk 'NR % 10 == 0' huge.log | zo 'analyze' # Filter for relevant content grep "ERROR" huge.log | zo 'analyze' ``` #### Special Characters **Problem**: Special characters in output cause issues. **Solution**: zo handles UTF-8 well, but for other encodings: ```bash # Convert to UTF-8 iconv -f ISO-8859-1 -t UTF-8 file.txt | zo 'analyze' # Remove non-printable characters tr -cd '[:print:]\n' < file.txt | zo 'analyze' ``` #### Chat Mode + STDIN **Problem**: Want to use STDIN in chat mode but also type interactively. **Solution**: zo uses `/dev/tty` for interactive input after initial STDIN: ```bash # This works! STDIN for first message, then interactive cat context.txt | zo --chat 'Let us discuss this' > Follow-up question here > exit ``` ### Performance Tips #### 1. Filter Before Piping ```bash # ❌ Slow - sends everything cat huge.log | zo 'find errors' # ✅ Fast - filter first grep "ERROR" huge.log | zo 'categorize' ``` #### 2. Use Specific Models ```bash # Fast model for simple tasks ps aux | zo /flash 'quick check' # Powerful model for complex analysis complex_output | zo /opus 'deep analysis' ``` #### 3. Batch Similar Queries ```bash # ❌ Inefficient - multiple API calls cat file1.txt | zo 'analyze' cat file2.txt | zo 'analyze' cat file3.txt | zo 'analyze' # ✅ Better - one API call cat file*.txt | zo 'analyze each section' ``` ### Real-World Examples #### Development Workflow ```bash # Morning standup summary git log --since="yesterday" --author="$(git config user.email)" \ | zo 'Summarize what I worked on yesterday' # Pre-commit checks git diff --cached | zo /reviewer 'Quick sanity check before commit' # Dependency check npm outdated | zo 'Which updates are important?' ``` #### DevOps Workflow ```bash # Container health docker ps -a | zo 'Any containers in bad state?' # Kubernetes debugging kubectl logs deployment/myapp --tail=100 \ | zo 'Why is this pod crashing?' # Resource usage kubectl top nodes | zo 'Any resource constraints?' ``` #### Data Science Workflow ```bash # Quick stats head -1000 dataset.csv | zo 'Basic statistics for each column' # Data quality cat data.csv | zo 'Check for missing values, outliers, anomalies' # SQL generation head -5 data.csv | zo 'Generate SQL schema for this data' ``` ### Next Steps * [Chat Mode →](/docs/chat) - Multi-turn conversations * [Shell Integration →](/examples/shell-integration) - Integrate into your workflow * [Git Workflows →](/examples/git-workflows) - Git-specific examples * [Quick Start →](/docs/quick-start) - General zo usage ## Progressive Streaming zo's progressive streaming architecture displays responses as they're generated, providing instant feedback and a superior user experience. ### How It Works #### Dual-Mode Rendering zo implements a sophisticated dual-mode rendering system: 1. **Regular Text** - Rendered line-by-line with inline markdown formatting (bold, italic, inline code) applied in real-time 2. **Code Blocks** - Buffered from opening fence (\`\`\`) to closing fence, then rendered with full syntax highlighting This approach ensures: * ✅ No buffering delay for regular text * ✅ Professional syntax highlighting for code * ✅ True streaming UX #### Visual Comparison **Without Streaming (traditional):** ``` [Waiting...........................] 10s [Complete response appears all at once] ``` **With zo's Streaming:** ``` [First token appears] ~1s [Text flows in real-time] [Code blocks highlight when complete] [Response completes] ~10s ``` ### Technical Implementation #### StreamRenderer Architecture ``` Character Stream → Line Buffer → Decision Point ↓ ┌─────────────┴─────────────┐ ↓ ↓ Regular Text Code Block Fence ↓ ↓ Inline Formatting Buffer Until Close ↓ ↓ Immediate Display Syntax Highlight ``` #### Performance Characteristics * **First Token Latency:** Approximately 1 second (network + API dependent) * **Regular Text:** Immediate display per line * **Code Blocks:** Displayed when closing fence received * **Processing Overhead:** Minimal (less than 1ms per line) ### Rich Markdown Rendering #### Inline Elements Rendered immediately as text streams: * **Headers** - `# Heading` → Rendered in cyan (configurable) * **Bold** - `**text**` → Terminal bold + emphasis color * **Italic** - `*text*` → Terminal italic + emphasis color * **Inline Code** - `` `code` `` → Yellow (configurable) #### Code Blocks Buffered and syntax-highlighted: ````markdown ```rust fn main() { println!("Hello, world!"); } ``` ```` Features: * 100+ programming languages supported * Professional syntax highlighting (same engine as VS Code) * 24-bit true color support * Automatic language detection from fence info #### Lists and Tables ```markdown - Item 1 - Item 2 - Nested item | Header 1 | Header 2 | |----------|----------| | Cell 1 | Cell 2 | ``` Rendered with proper formatting and alignment. ### Syntax Highlighting #### Supported Languages zo uses `syntect` (the same highlighting engine as VS Code and `bat`) with support for 100+ languages: **Popular Languages:** * Rust, Python, JavaScript, TypeScript * Go, C, C++, Java, Kotlin * Ruby, PHP, Swift, Shell * SQL, HTML, CSS, Markdown * YAML, JSON, TOML, XML * And many more... #### Language Detection ````bash # Automatic detection from fence zo 'Write a Python script' # AI responds with: ```python def hello(): print("Hello!") ``` ```` #### Available Themes Choose your preferred syntax highlighting theme: **Dark Themes:** * `base16-ocean.dark` (default) * `Solarized-dark` * `Monokai Extended` * `Nord` * `Dracula` **Light Themes:** * `base16-ocean.light` * `InspiredGitHub` * `Solarized-light` **Configure in \~/.config/zo/config.toml:** ```toml theme = "base16-ocean.dark" ``` ### Color Customization #### Inline Element Colors Customize colors for inline markdown elements: ```toml # ~/.config/zo/config.toml [inline_colors] heading = "cyan" # For # Headers inline_code = "yellow" # For `code` emphasis = "white" # For *italic* and **bold** ``` #### Hex Color Support ```toml [inline_colors] heading = "#00FFFF" inline_code = "#FFFF00" emphasis = "#FFFFFF" ``` #### Named Colors Available named colors: * `black`, `red`, `green`, `yellow` * `blue`, `magenta`, `cyan`, `white` * `gray`, `darkgray` * `lightred`, `lightgreen`, `lightyellow` * `lightblue`, `lightmagenta`, `lightcyan` #### Smart Defaults zo automatically chooses appropriate colors based on your theme: **Dark Themes:** * Bright colors (cyan, yellow, white) * High contrast for readability **Light Themes:** * Dark colors (blue, magenta, black) * Optimized for light backgrounds ### Real-Time Experience #### Immediate Feedback ```bash zo /sonnet 'Explain how TCP works in detail' ``` **User Experience:** 1. **\~1s** - First words appear 2. **\~2s** - First paragraph visible 3. **\~5s** - Code example fence opens, buffering starts 4. **\~8s** - Code fence closes, highlighted code appears 5. **\~10s** - Response completes #### No Buffering Delay Traditional approach buffers entire response: ``` Wait 10s → Parse markdown → Highlight → Display ``` zo's approach streams immediately: ``` Receive chunk → Render immediately (regular text) → Buffer only code blocks ``` ### Practical Examples #### Long Explanations ```bash zo 'Explain the history of the internet in detail' ``` * Text appears paragraph by paragraph * No waiting for complete response * Can start reading immediately * Interrupt with Ctrl+C if satisfied #### Code Generation ```bash zo /coder 'Implement a web server in Rust with routing and middleware' ``` * Explanation streams as regular text * Code blocks appear highlighted when complete * Multiple code blocks handled correctly * Maintains context between blocks #### Mixed Content ```bash zo 'Explain quicksort with Python implementation and complexity analysis' ``` **Rendering Flow:** 1. Introduction text (immediate) 2. Algorithm explanation (immediate) 3. Code block (buffered, highlighted) 4. Complexity analysis (immediate) 5. Example walkthrough (immediate) ### Performance Optimization #### Character-Level Processing zo processes streaming response character-by-character to ensure: * No chunking artifacts * Correct line boundary detection * Proper fence marker detection #### Efficient Buffering * Only code blocks are buffered * Regular text has zero buffering delay * Memory usage minimal (approximately 1KB per code block) #### Terminal Output * `stdout.flush()` after each line * ANSI color codes for styling * Efficient terminal updates ### Comparison #### vs Batch Processing **Batch (traditional):** ``` Time to First Token: 10s Time to Complete: 10s User Experience: Wait, then read ``` **Streaming (zo):** ``` Time to First Token: 1s Time to Complete: 10s User Experience: Read while generating ``` **Improvement:** 10x faster perceived response time #### vs Other Tools | Tool | Streaming | Syntax Highlighting | Markdown | | -------------- | ----------- | ------------------- | ---------- | | **zo** | ✅ Real-time | ✅ Full | ✅ Rich | | curl + jq | ❌ No | ❌ No | ❌ No | | Web UIs | ⚠️ Delayed | ✅ Yes | ✅ Yes | | Most CLI tools | ❌ No | ⚠️ Limited | ⚠️ Limited | ### Configuration #### Theme Selection ```bash # Initialize config zo +init-config # Edit config vi ~/.config/zo/config.toml # Choose theme theme = "Monokai Extended" ``` #### Color Customization ```toml [inline_colors] heading = "lightblue" inline_code = "lightyellow" emphasis = "lightgreen" ``` #### Fallback Behavior If theme or colors are invalid: * Falls back to `base16-ocean.dark` * Uses sensible color defaults * Displays warning message * Continues working ### Advanced Features #### Multiple Code Blocks zo correctly handles multiple code blocks in a single response: ````markdown First explanation... ```python def example1(): pass ``` More explanation... ```rust fn example2() {} ``` Final thoughts... ```` Each block is syntax-highlighted independently. #### Mixed Fence Markers Supports both \`\`\` and \~\~\~ fence markers: ````markdown ```python code here ``` ~~~javascript more code ~~~ ```` #### Edge Cases zo handles: * Empty code blocks * Code blocks without language specification * Nested fence markers in inline code * Unicode characters * Very long lines (truncated at 2000 chars for performance) ### Tips for Best Experience #### Use Modern Terminals For best results, use terminals with: * 24-bit true color support * Unicode support * Good font rendering **Recommended:** * iTerm2 (macOS) * Alacritty (cross-platform) * Windows Terminal (Windows) * GNOME Terminal (Linux) * kitty (cross-platform) #### Terminal Settings Enable true color support: ```bash # Check if your terminal supports true color echo $COLORTERM # Should output: truecolor or 24bit ``` #### Font Selection Use fonts with good unicode support: * JetBrains Mono * Fira Code * Cascadia Code * Source Code Pro ### Troubleshooting #### Colors Look Wrong ```bash # Check terminal color support echo $TERM # Should be: xterm-256color or better # Try a different theme # Edit ~/.config/zo/config.toml theme = "InspiredGitHub" # Light theme ``` #### No Syntax Highlighting ```bash # Verify theme is valid zo +init-config # Lists available themes # Check config file cat ~/.config/zo/config.toml ``` #### Slow Performance ```bash # Use faster model for simple tasks zo /flash 'quick question' # Avoid piping huge files head -100 large.log | zo 'analyze this' ``` ### Next Steps * [Model Selection →](/docs/models) * [Configuration →](/docs/configuration) * [View Examples →](/examples)