Skip to content

.task()


AgentForceAgent Optional Chainable

Add tasks to the agent’s execution queue for sequential processing. Each task is executed independently, and its result is passed as context to the next task, enabling complex multi-step workflows.

task(taskDescription: string): AgentForceAgent
Parameter
Type
Default
Description
taskDescription
string
undefined
The task description/prompt that defines what the agent should do in this step

Returns the AgentForceAgent instance for method chaining.

import { AgentForceAgent } from '@agentforce/adk';
const agent = new AgentForceAgent({
name: "ContentProcessor",
tools: ["web_fetch", "fs_write_file"]
})
.useLLM("ollama", "gemma3:4b")
.task("Fetch content from https://example.com/article")
.task("Extract all links from the content")
.task("Save the links to a file named 'extracted-links.txt'");
await agent.run();
const documentationAgent = new AgentForceAgent({
name: "DocGenerator",
tools: ["fs_read_file", "fs_write_file", "fs_list_files"]
})
.systemPrompt("You are a technical documentation specialist")
.useLLM("openrouter", "mistralai/mistral-small")
.task("List all TypeScript files in the 'src/api' directory")
.task("Read each API file and extract function signatures and JSDoc comments")
.task("Generate comprehensive API documentation with examples")
.task("Create a table of contents and navigation structure")
.task("Save the complete documentation to 'docs/api-reference.md'");
await documentationAgent.run();

Build task lists programmatically based on conditions:

function createProcessingTasks(fileTypes: string[], outputFormat: 'json' | 'markdown' | 'csv') {
const agent = new AgentForceAgent({
name: "DynamicProcessor",
tools: ["fs_read_file", "fs_write_file", "fs_list_files"]
})
.systemPrompt("You are a file processing specialist")
.useLLM("ollama", "phi4-mini:latest");
// Add initial task
agent.task("List all files in the current directory");
// Add tasks for each file type
fileTypes.forEach(type => {
agent.task(`Process all .${type} files and extract key information`);
});
// Add output task based on format
const outputTasks = {
json: "Combine all processed data into a structured JSON format",
markdown: "Generate a markdown report with headers and formatted content",
csv: "Create a CSV file with all extracted data in tabular format"
};
agent.task(outputTasks[outputFormat]);
agent.task(`Save the final result to 'output/processed-data.${outputFormat}'`);
return agent;
}
// Usage
const processor = createProcessingTasks(['txt', 'md', 'json'], 'markdown');
await processor.run();
class TaskBuilder {
private agent: AgentForceAgent;
constructor(name: string, tools: string[]) {
this.agent = new AgentForceAgent({ name, tools })
.systemPrompt("You are a versatile automation assistant");
}
addDataSourceTask(source: 'file' | 'web' | 'api', location: string) {
const taskMap = {
file: `Read data from file: ${location}`,
web: `Fetch data from URL: ${location}`,
api: `Call API endpoint: ${location} and retrieve data`
};
this.agent.task(taskMap[source]);
return this;
}
addAnalysisTask(analysisType: string) {
this.agent.task(`Perform ${analysisType} analysis on the retrieved data`);
return this;
}
addOutputTask(format: string, destination: string) {
this.agent.task(`Format results as ${format} and save to ${destination}`);
return this;
}
build(): AgentForceAgent {
return this.agent;
}
}
// Usage
const customAgent = new TaskBuilder("CustomAnalyzer", ["fs_read_file", "web_fetch", "fs_write_file"])
.addDataSourceTask("web", "https://api.example.com/data")
.addAnalysisTask("trend")
.addAnalysisTask("statistical")
.addOutputTask("JSON", "results/analysis.json")
.build();
await customAgent.run();

The task() method supports extensive chaining for building complex workflows:

const agent = new AgentForceAgent({
name: "ChainedWorkflow",
tools: ["fs_read_file", "web_fetch", "fs_write_file"]
})
.useLLM("google", "gemini-1.5-pro")
.systemPrompt("You are a research assistant and content creator")
.task("Research the latest trends in artificial intelligence")
.task("Find 3 credible sources with recent statistics")
.task("Summarize key findings from each source")
.task("Write a 500-word article combining the insights")
.task("Add proper citations and references")
.task("Save the article as 'articles/ai-trends-2024.md'")
.debug(); // Enable debug logging
await agent.run();

Data Processing Pipelines

Pattern: Read → Process → Transform → Save

Best for: ETL operations, data analysis, report generation

Tools: fs_read_file, fs_write_file, analysis tools

Content Workflows

Pattern: Fetch → Extract → Transform → Publish

Best for: Content aggregation, SEO optimization, publishing

Tools: web_fetch, fs_write_file, content processing

Code Automation

Pattern: Analyze → Generate → Test → Deploy

Best for: Code generation, testing, documentation

Tools: fs_read_file, fs_write_file, code analysis

Research & Analysis

Pattern: Gather → Analyze → Synthesize → Report

Best for: Market research, competitive analysis, insights

Tools: web_fetch, fs_read_file, fs_write_file

// Clear, specific task descriptions
.task("Extract all email addresses from the contact page HTML")
// Include expected input/output format
.task("Convert the CSV data to JSON format with camelCase property names")
// Specify file paths and locations
.task("Save the processed results to 'output/processed-data.json'")
// Break complex operations into smaller steps
.task("Read the configuration file 'config/settings.yml'")
.task("Validate all configuration values against the schema")
.task("Generate environment-specific config files for dev, staging, prod")
// Too vague
.task("Process the data")
// Too complex for a single step
.task("Read all files, process them, analyze results, generate reports, and send emails")
// Missing context about data format
.task("Convert the data") // Convert from what to what?
// Unclear dependencies
.task("Use the previous results") // Which results? How?
// Robust task design with error handling
const agent = new AgentForceAgent({
name: "RobustAgent",
tools: ["fs_read_file", "fs_write_file", "web_fetch"]
})
.systemPrompt("Handle errors gracefully and provide fallback solutions")
.task("Try to read 'data/primary-source.json', if not found, read 'data/backup-source.json'")
.task("Validate the data format and report any issues found")
.task("Process valid records and skip any malformed entries")
.task("Save successful results to 'output/processed.json' and errors to 'output/errors.log'");
try {
await agent.run();
} catch (error) {
console.error("Workflow failed:", error.message);
}
  • .run() - Execute all queued tasks sequentially
  • .systemPrompt() - Set system instructions for task execution
  • .useLLM() - Configure the LLM for task processing
  • .debug() - Enable debug logging for task execution