Template Quick Reference

This quick reference provides a concise summary of ostruct’s most commonly used template features. For comprehensive documentation, see the Template Guide.

Template Structure

---
system_prompt: You are an expert assistant.
---

# Template content with {{ variables }} and {% logic %}

Note

Model and Temperature: Use CLI flags --model gpt-4o --temperature 0.7 instead of frontmatter.

Essential Syntax

Variables

{{ variable_name }}              <!-- Output variable -->
{{ file.content }}               <!-- File content (REQUIRED .content) -->
{{ config.database.host }}      <!-- Nested object access -->
{{ items | length }}             <!-- Apply filter -->

Control Flow

{% if condition %}...{% endif %}
{% if var is defined %}...{% endif %}
{% for item in items %}...{% endfor %}
{% for file in files if file.extension == "py" %}...{% endfor %}

Comments

{# This is a comment #}

File Variables

File Routing Flags

File Routing Quick Reference

Flag

Purpose

Template Variable

--file alias

Template access only

alias variable

--file ci:data

Code Interpreter upload

data variable with analysis context

--file fs:docs

File Search upload

docs variable with search context

File Aliases

Choose meaningful aliases for your files:

--file config config.yaml                    # β†’ config
--file app_config config.yaml               # β†’ app_config

File Content Access

βœ… {{ my_file.content }}           <!-- Correct -->
❌ {{ my_file }}                   <!-- Wrong - shows guidance message -->

File Properties

{{ file.name }}          <!-- filename.txt -->
{{ file.path }}          <!-- relative/path/filename.txt -->
{{ file.abs_path }}      <!-- /full/path/filename.txt -->
{{ file.size }}          <!-- 1024 (bytes) -->
{{ file.extension }}     <!-- txt -->
{{ file.suffix }}        <!-- .txt -->
{{ file.stem }}          <!-- filename without extension -->
{{ file.mtime }}         <!-- modification time (Unix timestamp) -->
{{ file.first }}         <!-- first file (itself for single files) -->
{{ file.is_collection }} <!-- false for single files -->

Boolean Properties

{% if file.exists %}     <!-- file exists -->
{% if file.is_file %}    <!-- is regular file -->
{% if file.is_url %}     <!-- is remote URL -->

Multiple Files

{% for file in source_files %}
## {{ file.name }}
{{ file.content }}
{% endfor %}

Tool Variables

{% if code_interpreter_enabled %}
{% if file_search_enabled %}
{% if web_search_enabled %}
{% if auto_download_enabled %}

{{ current_model }}              <!-- gpt-4o -->
{{ code_interpreter_config }}    <!-- CI configuration object -->

Note

Advanced only

auto_download_enabled and code_interpreter_config are useful when you write meta-templates that must adapt to different Code-Interpreter settings. auto_download_enabled reflects the --ci-download flag or legacy config. Most templates can ignore them.

Standard Input

{% if stdin %}{{ stdin }}{% endif %}

CLI Variables

String Variables

ostruct run template.j2 schema.json -V env=production -V debug=false
Environment: {{ env }}
Debug: {{ debug }}

JSON Variables

ostruct run template.j2 schema.json -J config='{"host": "localhost", "port": 5432}'
Host: {{ config.host }}
Port: {{ config.port }}

Essential Filters

Text Processing

{{ text | word_count }}             <!-- Count words -->
{{ text | char_count }}             <!-- Count characters -->
{{ text | length }}                 <!-- Count characters (built-in) -->
{{ text | upper }}                  <!-- UPPERCASE -->
{{ text | lower }}                  <!-- lowercase -->
{{ long_text | truncate(100) }}     <!-- Truncate to 100 chars -->
{{ text | extract_keywords }}       <!-- Extract keywords -->
{{ text | normalize }}              <!-- Normalize whitespace -->
{{ text | strip_markdown }}         <!-- Remove markdown -->

Data Processing

{{ items | length }}                <!-- Count items -->
{{ items | sort_by("name") }}       <!-- Sort by property -->
{{ items | group_by("category") }}  <!-- Group by property -->
{{ items | filter_by("active", true) }} <!-- Filter by criteria -->
{{ items | unique }}                <!-- Remove duplicates -->
{{ users | extract_field("email") }} <!-- Extract field -->
{{ items | frequency }}             <!-- Calculate frequencies -->
{{ data | aggregate }}              <!-- Aggregate data -->

JSON Operations

{{ data | to_json }}                <!-- Convert to JSON -->
{{ json_string | from_json }}       <!-- Parse JSON -->

Table Formatting

{{ data | table }}                  <!-- Format as table -->
{{ data | align_table }}            <!-- Align table columns -->
{{ dictionary | dict_to_table }}    <!-- Dict to markdown table -->
{{ list_data | list_to_table }}     <!-- List to markdown table -->
{{ data | auto_table }}             <!-- Auto-format table -->

Code Processing

{{ code | format_code("python") }}  <!-- Syntax highlighting -->
{{ code | strip_comments("python") }} <!-- Remove comments -->
{{ text | escape_special }}         <!-- Escape special chars -->

Common Patterns

Conditional Content

{% if config_file is defined %}
Configuration: {{ config_file.content }}
{% else %}
No configuration provided.
{% endif %}

File Processing

{% for file in source_files %}
### {{ file.path }}

**Size**: {{ file.size }} bytes
**Type**: {{ file.extension }}

```{{ file.extension }}
{{ file.content }}
```
{% endfor %}

Data Analysis

{% set stats = data | aggregate %}
Total: {{ stats.sum }}
Average: {{ stats.avg }}
Count: {{ stats.count }}

Error Handling

{% if files and files | length > 0 %}
Processing {{ files | length }} files...
{% else %}
No files to process.
{% endif %}

Global Functions

Utility Functions

{{ now() }}                         <!-- Current timestamp -->
{{ type_of(variable) }}             <!-- Get type name -->
{{ debug(variable) }}               <!-- Debug output -->
{{ format_json(data) }}             <!-- Format JSON with indentation -->

File Attachment Helpers

<!-- Text workflow (XML appendix) -->
{{ embed_text("config") }}          <!-- Schedule file for appendix -->
{{ get_embed_ref("config") }}       <!-- Get reference tag: <config> -->

<!-- Binary workflow (vision/code interpreter) -->
{{ attach_file("chart.png") }}      <!-- Attach for binary access -->
{{ get_file_ref("chart.png") }}     <!-- Get file label: FILE A -->

<!-- Deprecated -->
{{ file_ref("alias") }}             <!-- Use get_embed_ref() instead -->

Token Estimation

Estimated tokens: {{ estimate_tokens(content) }}

Data Analysis Functions

{% set summary = summarize(data_list) %}
Records: {{ summary.total_records }}

{% set pivot = pivot_table(data, "category", "month") %}
{{ pivot | auto_table }}

File Operations

File Processing

{{ files | single }}               <!-- Extract single file -->
{{ file.name }}                    <!-- Filename -->
{{ file.path }}                    <!-- Full path -->
{{ file.size }}                    <!-- File size -->

Common Issues

File Content Access

❌ {{ my_file }}                   <!-- Shows: guidance message -->
βœ… {{ my_file.content }}           <!-- Shows: actual file content -->

Variable Existence

{% if optional_var is defined %}
{{ optional_var }}
{% endif %}

Safe Defaults

<!-- Simple variable defaults -->
{{ config.timeout | default(30) }}
{{ project_name | default("Unnamed Project") }}

<!-- Safe nested property access -->
{{ safe_get("config.database.host", "localhost") }}
{{ safe_get("user.profile.name", "Anonymous") }}
{{ safe_get("api.response.data") }}              <!-- Empty string default -->

CLI Examples

Basic Usage

# Simple file processing
ostruct run template.j2 schema.json --file config config.yaml

# Multiple files with custom names
ostruct run template.j2 schema.json --file config config.yaml --file data data.csv

# Directory processing
ostruct run template.j2 schema.json --dir ci:data source_code/

Multi-Tool Integration

# Code analysis with execution
ostruct run analysis.j2 schema.json --file ci:data data.csv --file fs:docs docs.pdf

# With web search
ostruct run research.j2 schema.json --enable-tool web-search -V topic="AI trends"

Variables and Configuration

# String and JSON variables
ostruct run template.j2 schema.json \
  -V env=production \
  -J config='{"debug": false, "timeout": 30}'

# With system prompt
ostruct run template.j2 schema.json \
  --sys-prompt "You are an expert analyst" \
  --file config data.txt

Debugging

# Show available variables
ostruct run template.j2 schema.json --template-debug vars --file config config.yaml

# Dry run to test template
ostruct run template.j2 schema.json --dry-run --file config config.yaml

# Debug template expansion
ostruct run template.j2 schema.json --template-debug post-expand --file config config.yaml

See also