Documentation Generation
Format: .md files
Best for: API docs, guides, tutorials, technical writing
Example: Generate clean markdown documentation from code analysis
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>
fileName
string
undefined
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: "CodeGenerator"}) .systemPrompt("You are a TypeScript expert") .useLLM("google", "gemini-1.5-flash") .prompt("Create a function to validate email addresses");
const filePath = await agent.saveToFile("code-response.json");console.log(`Structured data saved to: ${filePath}`);
// File content format:// {// "agent": "CodeGenerator",// "provider": "google",// "model": "gemini-1.5-flash",// "systemPrompt": "You are a TypeScript expert",// "userPrompt": "Create a function to validate email addresses",// "response": "function validateEmail(email: string): boolean { ... }",// "timestamp": "2024-03-15T10:30:00.000Z"// }
import { AgentForceAgent } from '@agentforce/adk';
const agent = new AgentForceAgent({ name: "DocumentationAgent"}) .systemPrompt("You are a technical writer. Format responses as clean markdown") .useLLM("openrouter", "mistralai/mistral-small") .prompt("Write a guide on REST API best practices");
const filePath = await agent.saveToFile("api-guide.md");console.log(`Documentation saved to: ${filePath}`);
// File content format: Clean markdown response only// # REST API Best Practices//// ## 1. Use HTTP Status Codes Correctly// ...
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 documentationconst docPath = await agent.saveToFile("components/Button.md");console.log(`Component documentation: ${docPath}`);
// Save as JSON for metadataconst metaPath = await agent.saveToFile("components/Button-meta.json");console.log(`Component metadata: ${metaPath}`);
import { AgentForceAgent } from '@agentforce/adk';
const agent = new AgentForceAgent({ name: "DataAnalyst", tools: ["fs_read_file"]}) .systemPrompt("You are a data analyst. Provide detailed insights with charts and recommendations") .useLLM("ollama", "qwen3-coder-tool", { appendToolResults: true, maxToolRounds: 3 }) .prompt("Read 'data/sales-q4.csv' and generate a comprehensive analysis report");
// Save analysis as markdown reportconst reportPath = await agent.saveToFile("reports/q4-analysis.md");console.log(`Analysis report: ${reportPath}`);
// Save raw data as JSON for further processingconst dataPath = await agent.saveToFile("reports/q4-data.json");console.log(`Raw analysis data: ${dataPath}`);
import { AgentForceAgent } from '@agentforce/adk';
class BatchProcessor { static async processPrompts(prompts: string[], baseFileName: string) { const results: string[] = [];
for (let i = 0; i < prompts.length; i++) { const agent = new AgentForceAgent({ name: `BatchAgent${i + 1}` }) .useLLM("ollama", "gemma3:4b") .systemPrompt("You are a helpful assistant") .prompt(prompts[i]);
const fileName = `${baseFileName}-${i + 1}.txt`; const filePath = await agent.saveToFile(fileName); results.push(filePath);
console.log(`Processed prompt ${i + 1}/${prompts.length} → ${filePath}`); }
return results; }}
// Usageconst prompts = [ "Explain machine learning", "Describe blockchain technology", "What is quantum computing?"];
const savedFiles = await BatchProcessor.processPrompts(prompts, "batch-response");console.log("All files saved:", savedFiles);
// Automatically choose format based on use caseasync 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`); }}
// Usageconst docAgent = new AgentForceAgent({ name: "DocAgent" }) .prompt("Create API documentation");
const filePath = await saveAgentResponse(docAgent, 'documentation');console.log(`Saved to: ${filePath}`);
.txt
Text Format
Structured
.json
JSON Format
Complete
.md
Markdown Format
Response Only
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 timestampsconst timestamp = new Date().toISOString().replace(/[:.]/g, '-');const filePath = await agent.saveToFile(`analysis-${timestamp}.json`);
// Choose appropriate format for content typeconst documentationAgent = agent.saveToFile("guide.md"); // For readable contentconst dataAgent = agent.saveToFile("results.json"); // For structured dataconst debugAgent = agent.saveToFile("debug.txt"); // For debugging info
// Organize files in directoriesawait agent.saveToFile("reports/quarterly-analysis.md");await agent.saveToFile("data/processed-results.json");await agent.saveToFile("logs/execution-log.txt");
// Handle file paths properlyconst 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 extensionsawait agent.saveToFile("output.csv"); // Error: Only .txt, .json, .md supported
// ❌ Empty or invalid filenameawait agent.saveToFile(""); // Error: Filename must be non-empty stringawait agent.saveToFile(123); // Error: Filename must be string
// ❌ Not handling async properlyconst path = agent.saveToFile("output.txt"); // Missing awaitconsole.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 parameterUnsupported file extension. Use .txt, .json, or .md
- Wrong file extensionFailed 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