# Helper Functions and Standardized Output

LMTune includes helper functions that are automatically injected into every generated script, making it easier to handle common operations like file I/O and standardized JSON output.

## Included Helper Functions

### 1. `output_results(result_dict)` (REQUIRED)

This function prints a standardized JSON output for the script. It must be called at the end of every script:

```python
def output_results(result_dict):
    """Helper function to format and print results as JSON."""
    import json
    print(json.dumps(result_dict))
```

### 2. `read_input_file(filename, base_dir=None)`

This function reads files from the standard input directory:

```python
def read_input_file(filename, base_dir=None):
    """Helper function to read a file from the standard input directory."""
    import os
    import json
    
    if base_dir is None:
        # Default to the problems directory in the project
        base_dir = os.path.expanduser("~/git/lmtune/problems")
    
    filepath = os.path.join(base_dir, filename)
    
    with open(filepath, 'r') as f:
        try:
            # Try to parse as JSON
            return json.load(f)
        except json.JSONDecodeError:
            # If not valid JSON, return as text
            f.seek(0)
            return f.read()
```

## How It Works

1. The LMTune system:
   - Automatically injects these helper functions into every script
   - Requires scripts to end with a call to `output_results`, passing a result dictionary
   - Parses the JSON output and displays it in a formatted view

2. This approach ensures:
   - Consistent output format across all generated scripts
   - Easy file I/O without requiring full paths
   - Clean separation between script logic and I/O operations

## Using the Result Dictionary

When running a script through LMTune, the system will:

1. Execute the Python script normally
2. Parse the output to find and extract the JSON result dictionary
3. Display the full script output for reference
4. Display the extracted result dictionary in a formatted view

This makes it easy to:
- Quick scan the key results
- Process the results programmatically
- Pass the structured data to other tools or APIs

## For Script Developers

If you're creating scripts for LMTune:

1. Collect all relevant results in a dictionary
2. Call `output_results(result_dict)` at the end of your script
3. No need to import any modules or define the function - it's automatically available

Example:
```python
# Your script logic here
result_dict = {
    "calculations": [1, 2, 3, 4],
    "total": 10,
    "status": "success" 
}

# Output results at the end
output_results(result_dict)
```

## Validation

LMTune automatically validates that your script calls the `output_results` function using the `check()` tool. If this validation fails, the script won't execute and you'll receive a helpful error message.

## Available Tools

The following tools are available to the script generation agent:

1. `clear()` - Clears the current string content
2. `view([start_line, end_line])` - Views the content, optionally within a specific range
3. `insert(line_num, "code")` - Inserts text at a specific location
4. `check()` - Validates the code, including verifying the call to output_results
5. `execute_script()` - Executes the Python script and captures output