Skip to main content
Save agent responses to files using multiple methods. Choose the approach that fits your use case.

Quick Start

Simplest - Just pass a file path:
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

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)

One line - just pass a file path string to output.

Basic Usage

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

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
The agent automatically creates parent directories if they don’t exist.

Method 2: OutputConfig (With Template)

Use OutputConfig when you need to save output AND apply template formatting.
Recommended: For response templates without file saving, use TemplateConfig.response instead. See Templates for details.

With Template

from praisonaiagents import Agent
from praisonaiagents.config import 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")
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

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

Recommended when the agent needs to decide what to save and where.

Basic Usage

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

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")
The agent autonomously decides when to call write_file based on the task.

Method 4: Task output_file

Recommended for task-based workflows where you want automatic file saving.

Basic Usage

from praisonaiagents import Agent, Task, Agents

# 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 = AgentManager(agents=[writer], tasks=[task])
result = agents.start()
# File automatically saved to blog_post.md

Multiple Tasks with Different Outputs

from praisonaiagents import Agent, Task, Agents

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 = AgentManager(
    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

Recommended for YAML-based workflows with variable substitution.

agents.yaml Example

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

praisonai agents.yaml

Method 6: Manual Capture

Use when you need full control over the saving process.

Basic Manual Save

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

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

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
Always set create_directory=True when using Task.output_file to avoid errors:
Task(
    output_file="deep/nested/path/file.txt",
    create_directory=True  # Creates all parent directories
)
Use variables for flexible output paths:
variables:
  output_dir: "reports"
  date: "2024-01"

steps:
  - output_file: "{{output_dir}}/{{date}}/report.md"
For large outputs, consider streaming to file:
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

pip install praisonaiagents
export OPENAI_API_KEY="your-key"
2

Create Agent with File Tools

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

# 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!")