> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Save Agent Output

> How to save agent responses to files automatically

Save agent responses to files automatically — pass a path, use `OutputConfig`, or let the agent call `write_file`.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    instructions="You are a helpful writer",
    output="poem.txt",
)
agent.start("Write a poem about nature")
```

The user asks for content; the agent writes the response to the configured output file.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Save Output"
        In[📋 Input] --> A[🤖 Agent]
        A --> F[📄 File]
        A --> C[✅ Console]
    end

    classDef input fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff
    class In input
    class A agent
    class F,C output
```

## Quick Start

**1. Simple Usage**

Pass a file path string to `output`:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    instructions="You are a helpful writer",
    output="poem.txt",
)
agent.start("Write a poem about nature")
# Output saved to poem.txt
```

**2. With Configuration**

Use `OutputConfig` for template formatting:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, OutputConfig

agent = Agent(
    instructions="You are a helpful writer",
    output=OutputConfig(
        output_file="poem.txt",
        template="# {{title}}\n\n{{content}}",
    ),
)
agent.start("Write a poem about nature")
```

***

## How It Works

The user sends a request; the agent generates a response and the framework writes it to the configured output file.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant File

    User->>Agent: start("Write a poem")
    Agent->>Agent: Generate response
    Agent->>File: Save to output path
    File-->>Agent: Written
    Agent-->>User: Response (also on console)
```

***

## Methods Comparison

| Method | Best For | Auto-Save | Agent Control |
| - | - | - | - |
| **String Path** | Simplest usage | Yes | Framework |
| **OutputConfig** | Template formatting | Yes | Framework |
| **write\_file Tool** | Dynamic file operations | No | Agent decides |
| **Task.output\_file** | Task-based workflows | Yes | Framework |
| **Workflow output\_file** | YAML workflows | Yes | Framework |
| **Manual** | Full control | No | Developer |

***

## Method 1: String Path (Simplest)

> [!NOTE]
>
> **One line** - just pass a file path string to `output`.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
flowchart LR
    A[Agent] --> R[Response]
    R --> F[output_file]
    R --> C[Console]
    
    style A fill:#189AB4,color:#fff
    style R fill:#8B0000,color:#fff
    style F fill:#8B0000,color:#fff
    style C fill:#8B0000,color:#fff
```

### Basic Usage

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    instructions="You are a helpful writer",
    output="output/response.txt"
)

agent.start("Write a poem about nature")
# ✅ Output saved to output/response.txt
```

### With Directory

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    instructions="You are a researcher",
    output="reports/summary.md"
)

agent.start("Summarize AI trends")
# ✅ Creates reports/ directory if needed
# ✅ Output saved to reports/summary.md
```

> [!TIP]
>
> The agent automatically creates parent directories if they don't exist.

***

## Method 2: OutputConfig (With Template)

> [!NOTE]
>
> Use `OutputConfig` when you need to save output AND apply template formatting.

> [!NOTE]
>
> **Recommended**: For response templates without file saving, use `TemplateConfig.response` instead. See [Templates](https://praison.ai/docs/features/templates.md) for details.

### With Template

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, OutputConfig

agent = Agent(
    instructions="You are a blog writer",
    output=OutputConfig(
        output_file="blog_post.md",
        template="""# {{title}}

{{content}}

---
*Generated by AI*
"""
    )
)

agent.start("Write about Python programming")
```

> [!TIP]
>
> The template instructs the agent to format its response accordingly. Both `OutputConfig.template` and `TemplateConfig.response` work - use `TemplateConfig.response` when you don't need file saving.

### Combined with Other Settings

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
agent = Agent(
    instructions="You are a researcher",
    output=OutputConfig(
        verbose=True,              # Show rich terminal output
        output_file="research.md", # Also save to file
        template="## Summary\n\n{{content}}"
    )
)
```

***

## Method 3: write\_file Tool

> [!NOTE]
>
> **Recommended** when the agent needs to decide what to save and where.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
flowchart LR
    A[Agent] --> D{Decides}
    D --> W[write_file Tool]
    W --> F[File]
    
    style A fill:#8B0000,color:#fff
    style D fill:#189AB4,color:#fff
    style W fill:#189AB4,color:#fff
    style F fill:#8B0000,color:#fff
```

### Basic Usage

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonaiagents.tools import write_file

agent = Agent(
    name="ReportWriter",
    role="Technical Writer",
    goal="Create and save technical documentation",
    tools=[write_file]
)

# Agent will use write_file tool to save the report
agent.start("Write a technical report about Python and save it to report.md")
```

### With Multiple File Tools

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonaiagents.tools import read_file, write_file, list_files

agent = Agent(
    name="FileManager",
    instructions="Manage files: read, write, and organize",
    tools=[read_file, write_file, list_files]
)

agent.start("Read config.json, update the version to 2.0, and save as config_new.json")
```

> [!TIP]
>
> The agent autonomously decides when to call `write_file` based on the task.

***

## Method 4: Task output\_file

> [!NOTE]
>
> **Recommended** for task-based workflows where you want automatic file saving.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
flowchart LR
    T[Task Completes] --> S[save_output_to_file]
    S --> F[output_file]
    
    style T fill:#8B0000,color:#fff
    style S fill:#189AB4,color:#fff
    style F fill:#8B0000,color:#fff
```

### Basic Usage

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Task, AgentTeam

# Create agent
writer = Agent(
    name="ContentWriter",
    role="Writer",
    goal="Create engaging content"
)

# Task with output_file
task = Task(
    description="Write a blog post about machine learning",
    expected_output="A well-structured blog post in markdown",
    agent=writer,
    output_file="blog_post.md",
    create_directory=True  # Creates parent directories if needed
)

# Run
agents = AgentTeam(agents=[writer], tasks=[task])
result = agents.start()
# File automatically saved to blog_post.md
```

### Multiple Tasks with Different Outputs

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Task, AgentTeam

researcher = Agent(name="Researcher", role="Research Analyst")
writer = Agent(name="Writer", role="Content Writer")

research_task = Task(
    description="Research AI trends for 2024",
    agent=researcher,
    output_file="research/ai_trends.txt"
)

writing_task = Task(
    description="Write a summary based on the research",
    agent=writer,
    output_file="output/summary.md",
    create_directory=True
)

agents = AgentTeam(
    agents=[researcher, writer],
    tasks=[research_task, writing_task],
    process="sequential"
)
agents.start()
# Creates: research/ai_trends.txt and output/summary.md
```

***

> [!NOTE]
>
> `framework: praisonai` honours `output_file` on YAML tasks and creates parent directories automatically. See [Headless YAML Runs](https://praison.ai/docs/features/headless-yaml-runs.md).

## Method 5: Workflow output\_file

> [!NOTE]
>
> **Recommended** for YAML-based workflows with variable substitution.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
flowchart LR
    S[Step Completes] --> V[Variable Substitution]
    V --> F[output_file]
    
    style S fill:#8B0000,color:#fff
    style V fill:#189AB4,color:#fff
    style F fill:#8B0000,color:#fff
```

### agents.yaml Example

```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
metadata:
  name: content-generator
  version: "1.0"

variables:
  output_dir: "generated"
  topic: "artificial intelligence"

agents:
  writer:
    role: Content Writer
    goal: Create engaging content about {{topic}}
    llm: gpt-4o-mini

steps:
  - agent: writer
    action: "Write a comprehensive article about {{topic}}"
    expected_output: "A well-structured article in markdown format"
    output_file: "{{output_dir}}/article.md"
```

### Run the Workflow

```bash CLI theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
praisonai agents.yaml
```

```python Python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import AgentFlow

workflow = Workflow.from_yaml("agents.yaml")
workflow.run()
# Output saved to: generated/article.md
```

***

## Method 6: Manual Capture

> [!NOTE]
>
> Use when you need full control over the saving process.

### Basic Manual Save

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
import json

agent = Agent(name="DataProcessor")
response = agent.start("Generate a list of 5 programming languages with descriptions")

# Save as text
with open("languages.txt", "w") as f:
    f.write(response)

# Or save as JSON (if response is structured)
with open("languages.json", "w") as f:
    json.dump({"content": response}, f, indent=2)
```

### With Error Handling

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from pathlib import Path

agent = Agent(name="Writer")
response = agent.start("Write a short story")

output_path = Path("stories/short_story.txt")
output_path.parent.mkdir(parents=True, exist_ok=True)

try:
    output_path.write_text(response)
    print(f"✅ Saved to {output_path}")
except IOError as e:
    print(f"❌ Failed to save: {e}")
```

***

## Best Practices

> **Choose the Right Method**
>
> | Scenario | Recommended Method |
> | - | - |
> | Simplest usage | String path (`output="file.txt"`) |
> | Template formatting | `OutputConfig` |
> | Agent decides what to save | `write_file` tool |
> | Auto-save task results | `Task.output_file` |
> | YAML workflows | Workflow `output_file` |
> | Custom save logic | Manual capture |

> **Use create\_directory**
>
> Always set `create_directory=True` when using `Task.output_file` to avoid errors:
>
> ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> Task(
>     output_file="deep/nested/path/file.txt",
>     create_directory=True  # Creates all parent directories
> )
> ```

> **Use Variables in Workflows**
>
> Use variables for flexible output paths:
>
> ```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> variables:
>   output_dir: "reports"
>   date: "2024-01"
>
> steps:
>   - output_file: "{{output_dir}}/{{date}}/report.md"
> ```

> **Handle Large Outputs**
>
> For large outputs, consider streaming to file:
>
> ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
> agent = Agent(name="Writer")
>
> with open("large_output.txt", "w") as f:
>     for chunk in agent.stream("Generate a long document"):
>         f.write(chunk)
>         f.flush()
> ```

***

## Complete Example

**1. Install**

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
pip install praisonaiagents
export OPENAI_API_KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY in your shell}"
```

**2. Create Agent with File Tools**

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonaiagents.tools import write_file, read_file

agent = Agent(
    name="DocumentProcessor",
    role="Document Specialist",
    goal="Process and save documents efficiently",
    tools=[write_file, read_file]
)
```

**3. Run and Save**

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Agent will automatically save to the specified file
result = agent.start("""
    Write a project README with:
    - Project title: My AI Project
    - Description
    - Installation steps
    - Usage examples
    
    Save it to README.md
""")

print("✅ Document saved!")
```

***

## Related

> **[File Tools](https://praison.ai/docs/tools/file_tools.md)**
>
> Complete file operations reference

> **[Workflows](https://praison.ai/docs/features/workflows.md)**
>
> YAML workflow configuration


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.