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
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.

Diagram

Save Output

📋 Input

🤖 Agent

📄 File

✅ Console

Quick Start

  1. Simple Usage

    Pass a file path string to output:

    python
    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
    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.

Diagram
FileAgentUserFileAgentUserstart(“Write a poem”)Generate responseSave to output pathWrittenResponse (also on console)

Methods Comparison

MethodBest ForAuto-SaveAgent Control
String PathSimplest usageYesFramework
OutputConfigTemplate formattingYesFramework
write_file ToolDynamic file operationsNoAgent decides
Task.output_fileTask-based workflowsYesFramework
Workflow output_fileYAML workflowsYesFramework
ManualFull controlNoDeveloper

Method 1: String Path (Simplest)

Diagram

Agent

Response

output_file

Console

Basic Usage

python
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
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

Method 2: OutputConfig (With Template)

With Template

python
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")

Combined with Other Settings

python
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

Diagram

Agent

Decides

write_file Tool

File

Basic Usage

python
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
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")

Method 4: Task output_file

Diagram

Task Completes

save_output_to_file

output_file

Basic Usage

python
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
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

Method 5: Workflow output_file

Diagram

Step Completes

Variable Substitution

output_file

agents.yaml Example

yaml
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

CLI
praisonai agents.yaml
Python
from praisonaiagents import AgentFlow

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

Project-Root Containment

Agent.output_file, Task.output_file and Workflow step output_file only write inside the project root. A path that escapes it is skipped with a warning log — no exception is raised. Relative paths are resolved against the project root.

Diagram

Yes

No

📝 output_file set

Resolves inside
project root?

💾 Write file

⚠️ Skip + log warning

✅ Saved

❌ No file

python
import os
from praisonaiagents import Agent, Task, AgentTeam

# Default root is the current working directory. Override when needed:
os.environ["PRAISONAI_PROJECT_ROOT"] = "/home/user/myproject"

writer = Agent(name="Writer", role="Writer", goal="Write content")
task = Task(
    description="Write a summary",
    agent=writer,
    output_file="reports/summary.md",   # ✅ saved to /home/user/myproject/reports/summary.md
    # output_file="../summary.md"       # ❌ escapes root → skipped
    create_directory=True,
)
AgentTeam(agents=[writer], tasks=[task]).start()
PathResult
reports/summary.md✅ Saved
/home/user/myproject/out.md (absolute, under root)✅ Saved
../summary.md, /var/log/report.md❌ Skipped
reports/{{input}}.md with input="../../x"❌ Skipped
Symlink inside root pointing outside❌ Skipped

The skipped write logs Output file '<path>' is outside project root '<root>'; skipping save. Only Agent.output_file also prints ⚠️ Output path outside project root to stdout — Task and Workflow writes log the warning only.

Same rules on every write path. Since PraisonAI PR #6172, Agent(output=OutputConfig(output_file=...)) and Agent(output="file.txt") use the same writer as Task.output_file and Workflow step output_file, so the root check, symlink and hardlink protection, and permission preservation apply to all three.

See PRAISONAI_PROJECT_ROOT for details.


Method 6: Manual Capture

Basic Manual Save

python
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
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
ScenarioRecommended Method
Simplest usageString path (output="file.txt")
Template formattingOutputConfig
Agent decides what to savewrite_file tool
Auto-save task resultsTask.output_file
YAML workflowsWorkflow output_file
Custom save logicManual capture
Use create_directory

Always set create_directory=True when using Task.output_file to avoid errors:

python
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
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
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
    pip install praisonaiagents
    export OPENAI_API_KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY in your shell}"
  2. Create Agent with File Tools
    python
    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
    # 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