> ## Documentation Index
> Fetch the complete documentation index at: https://extended-openai-conversation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Edit File Functions

> Safely edit files with find-and-replace operations

Edit File functions provide a safe way to modify existing files using find-and-replace operations. Unlike Write File, Edit File ensures that only intended changes are made and prevents accidental overwrites.

## Configuration

```yaml theme={null}
function:
  type: edit_file
  path: "{{ filename }}"
  old_text: "{{ text_to_find }}"
  new_text: "{{ replacement_text }}"
```

<ParamField path="path" type="template" required>
  Path to the file to edit. Can be absolute or relative to the working directory (`config/extended_openai_conversation/`).
</ParamField>

<ParamField path="old_text" type="template" required>
  Exact text to find and replace. Must appear exactly once in the file.
</ParamField>

<ParamField path="new_text" type="template" required>
  Text to replace the old text with.
</ParamField>

<ParamField path="allow_dir" type="array">
  Optional list of additional allowed directories (as templates). By default, only the working directory is allowed.
</ParamField>

## Working Directory

The default working directory is `config/extended_openai_conversation/`.

<Tabs>
  <Tab title="Relative Path">
    ```yaml theme={null}
    # Edits /config/extended_openai_conversation/notes.txt
    function:
      type: edit_file
      path: "notes.txt"
      old_text: "old content"
      new_text: "new content"
    ```
  </Tab>

  <Tab title="Subdirectory">
    ```yaml theme={null}
    # Edits /config/extended_openai_conversation/data/config.json
    function:
      type: edit_file
      path: "data/config.json"
      old_text: "{{ old_value }}"
      new_text: "{{ new_value }}"
    ```
  </Tab>

  <Tab title="Absolute Path">
    ```yaml theme={null}
    # Edits /config/configuration.yaml (must be in allowed directories)
    function:
      type: edit_file
      path: "/config/configuration.yaml"
      old_text: "{{ old_setting }}"
      new_text: "{{ new_setting }}"
    ```
  </Tab>
</Tabs>

## Examples

### Edit File

```yaml theme={null}
- spec:
    name: edit_file
    description: Edit a file with find-and-replace in workspace.
    parameters:
      type: object
      properties:
        filename:
          type: string
          description: Name of the file to edit
        old_text:
          type: string
          description: Text to find
        new_text:
          type: string
          description: Text to replace with
      required:
      - filename
      - old_text
      - new_text
  function:
    type: edit_file
    path: "{{ filename }}"
    old_text: "{{ old_text }}"
    new_text: "{{ new_text }}"
```

### Custom Allowed Directories

Extend allowed directories beyond the default workspace. The `allow_dir` parameter adds additional directories where files can be edited.

```yaml theme={null}
- spec:
    name: edit_file_with_allow_dir
    description: Edit a file with custom allowed directories.
    parameters:
      type: object
      properties:
        filename:
          type: string
          description: Name of the file to edit
        old_text:
          type: string
          description: Text to find
        new_text:
          type: string
          description: Text to replace with
      required:
      - filename
      - old_text
      - new_text
  function:
    type: edit_file
    path: "{{ filename }}"
    old_text: "{{ old_text }}"
    new_text: "{{ new_text }}"
    allow_dir:
      - "/backup"
      - "/media"
```

## How It Works

Edit File is safer than Write File because it:

1. **Reads the current file** to verify it exists
2. **Searches for exact match** of `old_text`
3. **Validates single occurrence** - fails if text appears 0 or 2+ times
4. **Performs replacement** - replaces only the one matched occurrence
5. **Writes back** to the same file

<Steps>
  <Step title="File is read">
    The entire file is read into memory
  </Step>

  <Step title="Text is searched">
    Searches for exact string match of `old_text`
  </Step>

  <Step title="Occurrence check">
    * If found 0 times → Error: "Text not found in file"
    * If found 1 time → Proceed with replacement
    * If found 2+ times → Error: "Text appears N times in file"
  </Step>

  <Step title="Replacement performed">
    Replaces the single occurrence with `new_text`
  </Step>

  <Step title="File is written">
    The modified content is written back to the file
  </Step>
</Steps>

## Return Value

On success:

```json theme={null}
{
  "success": true,
  "path": "/config/extended_openai_conversation/config.yaml",
  "replacements": 1
}
```

On error:

```json theme={null}
{
  "error": "Text not found in file: old text here..."
}
```

or

```json theme={null}
{
  "error": "Text appears 3 times in file. Please provide more specific text to ensure single replacement."
}
```

## Safety Features

<AccordionGroup>
  <Accordion title="Exact Match Required">
    `old_text` must match exactly, including:

    * Whitespace (spaces, tabs, newlines)
    * Case sensitivity
    * Special characters

    This prevents accidental matches.
  </Accordion>

  <Accordion title="Single Occurrence Validation">
    If text appears multiple times, the edit is rejected. This prevents unintended changes to multiple locations.

    To edit when text appears multiple times, make `old_text` more specific by including surrounding context.
  </Accordion>

  <Accordion title="File Must Exist">
    Unlike Write File, Edit File requires the file to already exist. This prevents accidental file creation.
  </Accordion>

  <Accordion title="Atomic Operation">
    The entire read-modify-write operation is atomic. If any step fails, the file remains unchanged.
  </Accordion>
</AccordionGroup>

## Common Patterns

### Update YAML Configuration Value

```yaml theme={null}
- spec:
    name: update_yaml_config
    description: Update a YAML configuration value
    parameters:
      type: object
      properties:
        key:
          type: string
        old_value:
          type: string
        new_value:
          type: string
  function:
    type: edit_file
    path: "/config/configuration.yaml"
    old_text: "{{ key }}: {{ old_value }}"
    new_text: "{{ key }}: {{ new_value }}"
```

### Update Python Variable

```yaml theme={null}
- spec:
    name: update_python_variable
    description: Update a variable in Python script
    parameters:
      type: object
      properties:
        script_name:
          type: string
        variable_name:
          type: string
        new_value:
          type: string
  function:
    type: edit_file
    path: "python_scripts/{{ script_name }}.py"
    old_text: "{{ variable_name }} = "
    new_text: "{{ variable_name }} = {{ new_value }}"
```

### Comment Out a Line

```yaml theme={null}
- spec:
    name: comment_out_line
    description: Comment out a configuration line
    parameters:
      type: object
      properties:
        filename:
          type: string
        line_content:
          type: string
  function:
    type: edit_file
    path: "{{ filename }}"
    old_text: "{{ line_content }}"
    new_text: "# {{ line_content }}"
```

### Update Automation Trigger

```yaml theme={null}
- spec:
    name: update_automation_trigger
    description: Update automation trigger entity
    parameters:
      type: object
      properties:
        automation_file:
          type: string
        old_entity:
          type: string
        new_entity:
          type: string
  function:
    type: edit_file
    path: "automations/{{ automation_file }}"
    old_text: |
      trigger:
        - platform: state
          entity_id: {{ old_entity }}
    new_text: |
      trigger:
        - platform: state
          entity_id: {{ new_entity }}
```

<Tip>
  Include surrounding context in `old_text` to make it unique when the value appears multiple times in the file.
</Tip>

## Use Cases

<CardGroup cols={2}>
  <Card title="Configuration Updates" icon="gear">
    Update settings in YAML, JSON, or INI files
  </Card>

  <Card title="Version Updates" icon="code-branch">
    Change version numbers or identifiers
  </Card>

  <Card title="Entity ID Changes" icon="id-card">
    Update entity references in automations
  </Card>

  <Card title="Text Corrections" icon="spell-check">
    Fix typos or update documentation
  </Card>
</CardGroup>

## Advanced Examples

### Multi-line Replacement

Edit File supports multi-line text:

```yaml theme={null}
- spec:
    name: update_yaml_block
    description: Update a multi-line YAML block
    parameters:
      type: object
      properties:
        service_name:
          type: string
  function:
    type: edit_file
    path: "/config/automations.yaml"
    old_text: |
      action:
        - service: light.turn_on
          target:
            entity_id: light.bedroom
    new_text: |
      action:
        - service: {{ service_name }}
          target:
            entity_id: light.bedroom
```

### Replace with Empty String (Delete)

```yaml theme={null}
- spec:
    name: remove_config_line
    description: Remove a configuration line
    parameters:
      type: object
      properties:
        line_to_remove:
          type: string
  function:
    type: edit_file
    path: "config.yaml"
    old_text: "{{ line_to_remove }}\n"
    new_text: ""
```

<Note>
  To delete a line, include the newline character (`\n`) in `old_text` so the empty line is also removed.
</Note>

### Conditional Edit with Validation

```yaml theme={null}
- spec:
    name: safe_config_update
    description: Safely update config with validation
    parameters:
      type: object
      properties:
        old_value:
          type: string
        new_value:
          type: string
  function:
    type: composite
    sequence:
      - type: read_file
        path: "config.yaml"
        response_variable: file_content
      - type: template
        value_template: |
          {% if old_value in file_content.content %}
            {% if file_content.content.count(old_value) == 1 %}
              OK: Ready to replace
            {% else %}
              ERROR: Value appears multiple times
            {% endif %}
          {% else %}
            ERROR: Value not found
          {% endif %}
        response_variable: validation
      - type: edit_file
        path: "config.yaml"
        old_text: "{{ old_value }}"
        new_text: "{{ new_value }}"
```

## Best Practices

<Steps>
  <Step title="Include context for uniqueness">
    When the value appears multiple times, include surrounding text to make it unique:

    ```yaml theme={null}
    # Too broad - might match multiple times
    old_text: "entity_id: light.bedroom"

    # Better - includes context
    old_text: |
      trigger:
        - platform: state
          entity_id: light.bedroom
    ```
  </Step>

  <Step title="Preserve exact formatting">
    Match indentation, spaces, and newlines exactly as they appear in the file:

    ```yaml theme={null}
    # Match the exact indentation (2 spaces)
    old_text: "  temperature: 20"
    new_text: "  temperature: {{ new_temp }}"
    ```
  </Step>

  <Step title="Read file first to verify content">
    Use composite function to read file first and verify the content exists:

    ```yaml theme={null}
    type: composite
    sequence:
      - type: read_file
        path: "{{ filename }}"
        response_variable: content
      - type: edit_file
        path: "{{ filename }}"
        old_text: "{{ old_value }}"
        new_text: "{{ new_value }}"
    ```
  </Step>

  <Step title="Handle errors gracefully">
    Expect and handle "not found" and "multiple occurrences" errors in your prompts or composite functions.
  </Step>
</Steps>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Text not found in file">
    The `old_text` doesn't exist in the file. Common causes:

    * Typo in `old_text`
    * Whitespace mismatch (spaces vs tabs)
    * Case sensitivity
    * File has already been edited

    **Solution**: Read the file first to verify exact content, then copy the exact text including whitespace.
  </Accordion>

  <Accordion title="Text appears N times in file">
    The `old_text` appears multiple times. This is blocked to prevent unintended changes.

    **Solution**: Make `old_text` more specific by including surrounding context:

    ```yaml theme={null}
    # Instead of:
    old_text: "enabled: true"

    # Use:
    old_text: |
      feature_name:
        enabled: true
    ```
  </Accordion>

  <Accordion title="File not found">
    The file doesn't exist at the specified path. Edit File requires existing files.

    **Solution**: Use Write File to create new files, or verify the file path is correct.
  </Accordion>

  <Accordion title="Access denied">
    The file is outside allowed directories.

    **Solution**: Add the directory to `allow_dir` or move the file to the workspace.
  </Accordion>
</AccordionGroup>

## Comparison: Edit vs Write

<AccordionGroup>
  <Accordion title="When to use Edit File">
    ✅ **Use Edit File when:**

    * Modifying existing files
    * You want to change specific values
    * You need safety against accidental overwrites
    * The file has other content you want to preserve
  </Accordion>

  <Accordion title="When to use Write File">
    ✅ **Use Write File when:**

    * Creating new files from scratch
    * Generating complete file contents
    * You want to overwrite the entire file
    * The file is a generated output (logs, reports, exports)
  </Accordion>
</AccordionGroup>

## FAQ

<AccordionGroup>
  <Accordion title="Can I replace multiple occurrences at once?">
    No. Edit File only replaces a single occurrence. This is a safety feature. To replace multiple occurrences, either:

    * Make `old_text` more specific so it matches only once
    * Use bash functions with `sed`:

    ```yaml theme={null}
    type: bash
    command: "sed -i 's/{{ old }}/{{ new }}/g' {{ filename }}"
    ```
  </Accordion>

  <Accordion title="What if I need to edit the same value multiple times?">
    Call the edit function multiple times, each time making `old_text` specific to one occurrence by including surrounding context.
  </Accordion>

  <Accordion title="Can I use regular expressions?">
    No. Edit File uses exact string matching. For regex replacements, use bash functions with `sed`.
  </Accordion>

  <Accordion title="Does it create backups?">
    No. The file is modified in place. If you need backups, use a composite function:

    ```yaml theme={null}
    type: composite
    sequence:
      - type: bash
        command: "cp {{ filename }} {{ filename }}.backup"
      - type: edit_file
        path: "{{ filename }}"
        old_text: "{{ old }}"
        new_text: "{{ new }}"
    ```
  </Accordion>
</AccordionGroup>

## Security

<AccordionGroup>
  <Accordion title="Path Restriction">
    Files must be within allowed directories. By default:

    * `/config/extended_openai_conversation/` (working directory)

    Additional directories can be added via `allow_dir`.
  </Accordion>

  <Accordion title="Exact Match Only">
    Only exact string matches are replaced. This prevents unintended changes through fuzzy matching or partial matches.
  </Accordion>

  <Accordion title="Single Occurrence">
    Only one occurrence can be replaced at a time. This prevents mass replacements that could corrupt the file.
  </Accordion>

  <Accordion title="File Must Exist">
    The file must already exist. This prevents accidental file creation.
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={3}>
  <Card title="Read File" icon="book-open" href="/functions/read_file">
    Read file contents before editing
  </Card>

  <Card title="Write File" icon="pen" href="/functions/write_file">
    Create new files or overwrite completely
  </Card>

  <Card title="Bash Functions" icon="terminal" href="/functions/bash">
    Advanced text processing with sed/awk
  </Card>
</CardGroup>
