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.
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.
Quick Start
- 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 - With Configuration
Use
OutputConfigfor 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.
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)
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.txtWith 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.mdMethod 2: OutputConfig (With Template)
With Template
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
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
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")Method 4: Task output_file
Basic Usage
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.mdMultiple Tasks with Different Outputs
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.mdMethod 5: Workflow output_file
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.yamlfrom praisonaiagents import AgentFlow
workflow = Workflow.from_yaml("agents.yaml")
workflow.run()
# Output saved to: generated/article.mdProject-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.
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()| Path | Result |
|---|---|
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
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
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:
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:
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:
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
- Install
bash pip install praisonaiagents export OPENAI_API_KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY in your shell}" - 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] ) - 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!")