Skip to content

.saveToFile()


AgentForceAgent Execution Method Asynchronous

Execute the agent and save the response to a file with the format automatically determined by the file extension. This is a execution method that triggers agent execution and returns the file path where the content was saved - not the agent instance for chaining.

saveToFile(fileName: string): Promise<string>
Parameter
Type
Default
Description
fileName
string
undefined
The filename to save to. Extension determines format: .txt (text), .json (JSON), .md (markdown)

Returns a Promise<string> containing the full file path where the content was saved.

import { AgentForceAgent } from '@agentforce/adk';
const agent = new AgentForceAgent({
name: "QuestionAgent"
})
.useLLM("ollama", "gemma3:4b")
.systemPrompt("You are a helpful assistant")
.prompt("What is the capital of France?");
const filePath = await agent.saveToFile("answer.txt");
console.log(`Response saved to: ${filePath}`);
// File content format:
// === Agent QuestionAgent Output (Text Format) ===
// System: You are a helpful assistant
// User: What is the capital of France?
// Response: Paris is the capital of France.
import { AgentForceAgent } from '@agentforce/adk';
const agent = new AgentForceAgent({
name: "ComponentGenerator",
tools: ["fs_read_file"]
})
.systemPrompt("You are a React expert. Generate production-ready TypeScript components")
.useLLM("google", "gemini-1.5-pro")
.prompt("Read the design system file and create a Button component with all variants");
// Save as markdown for documentation
const docPath = await agent.saveToFile("components/Button.md");
console.log(`Component documentation: ${docPath}`);
// Save as JSON for metadata
const metaPath = await agent.saveToFile("components/Button-meta.json");
console.log(`Component metadata: ${metaPath}`);
// Automatically choose format based on use case
async function saveAgentResponse(agent: AgentForceAgent, purpose: string) {
const timestamp = new Date().toISOString().split('T')[0];
switch (purpose) {
case 'documentation':
return await agent.saveToFile(`docs/${timestamp}-guide.md`);
case 'data':
return await agent.saveToFile(`data/${timestamp}-analysis.json`);
case 'log':
return await agent.saveToFile(`logs/${timestamp}-output.txt`);
default:
return await agent.saveToFile(`output/${timestamp}-response.txt`);
}
}
// Usage
const docAgent = new AgentForceAgent({ name: "DocAgent" })
.prompt("Create API documentation");
const filePath = await saveAgentResponse(docAgent, 'documentation');
console.log(`Saved to: ${filePath}`);
Parameter
Type
Default
Description
.txt
Text Format
Structured
Includes agent metadata, system prompt, user prompt, and response in readable format
.json
JSON Format
Complete
Full structured data with all agent configuration, prompts, response, and timestamp
.md
Markdown Format
Response Only
Clean markdown containing only the agent's response content

Documentation Generation

Format: .md files

Best for: API docs, guides, tutorials, technical writing

Example: Generate clean markdown documentation from code analysis

Data Export

Format: .json files

Best for: Structured data, analysis results, API responses

Example: Save analysis results with full metadata for processing

Log & Debug

Format: .txt files

Best for: Debugging, audit trails, complete interaction logs

Example: Save full agent interactions for troubleshooting

Batch Processing

Format: Multiple formats

Best for: Automated workflows, report generation, bulk operations

Example: Process multiple prompts and save results systematically

// Use descriptive filenames with timestamps
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filePath = await agent.saveToFile(`analysis-${timestamp}.json`);
// Choose appropriate format for content type
const documentationAgent = agent.saveToFile("guide.md"); // For readable content
const dataAgent = agent.saveToFile("results.json"); // For structured data
const debugAgent = agent.saveToFile("debug.txt"); // For debugging info
// Organize files in directories
await agent.saveToFile("reports/quarterly-analysis.md");
await agent.saveToFile("data/processed-results.json");
await agent.saveToFile("logs/execution-log.txt");
// Handle file paths properly
const fullPath = await agent.saveToFile("output.json");
console.log(`File saved at: ${fullPath}`);
// ❌ Trying to chain after saveToFile()
const result = await agent
.prompt("Hello")
.saveToFile("output.txt")
.prompt("Follow up"); // Error: saveToFile() is terminal
// ❌ Unsupported file extensions
await agent.saveToFile("output.csv"); // Error: Only .txt, .json, .md supported
// ❌ Empty or invalid filename
await agent.saveToFile(""); // Error: Filename must be non-empty string
await agent.saveToFile(123); // Error: Filename must be string
// ❌ Not handling async properly
const path = agent.saveToFile("output.txt"); // Missing await
console.log(path); // Logs Promise object
try {
const agent = new AgentForceAgent({
name: "FileAgent",
tools: ["fs_read_file"]
})
.systemPrompt("You are a file processor")
.prompt("Process the configuration file");
const filePath = await agent.saveToFile("results.json");
console.log(`Successfully saved to: ${filePath}`);
} catch (error) {
if (error.message.includes("Unsupported file extension")) {
console.error("Use .txt, .json, or .md extensions");
} else if (error.message.includes("Failed to write file")) {
console.error("File system error:", error.message);
} else if (error.message.includes("Filename must be")) {
console.error("Invalid filename provided");
} else {
console.error("Unexpected error:", error.message);
}
}

Common Error Messages:

  • Filename must be a non-empty string - Invalid filename parameter
  • Unsupported file extension. Use .txt, .json, or .md - Wrong file extension
  • Failed to write file: [reason] - File system write errors
  • .getResponse() - Execute and return raw response string
  • .output() - Execute and return structured output with format control
  • .run() - Execute multi-step task workflows
  • .prompt() - Set the main user prompt