AI Agents Module (@microfn/agent)
AI Agents Module
Section titled “AI Agents Module”The @microfn/agent
module enables you to create autonomous AI agents that can execute complex tasks by intelligently using available functions. Agents run asynchronously in the background and can make decisions about which functions to call based on their objective.
Installation
Section titled “Installation”No installation required! The module is automatically available in all Microfn functions.
Import
Section titled “Import”import agent from "@microfn/agent";// orimport { start, getStatus } from "@microfn/agent";
API Reference
Section titled “API Reference”start(config, functions)
Section titled “start(config, functions)”Start an agent execution asynchronously and return immediately.
Parameters
Section titled “Parameters”Parameter | Type | Required | Description |
---|---|---|---|
config | AgentConfig | Yes | Configuration object with agent objective |
config.objective | string | Yes | What the agent should accomplish |
functions | FunctionConfig[] | Yes | Array of functions the agent can use |
FunctionConfig
Section titled “FunctionConfig”Property | Type | Required | Description |
---|---|---|---|
function | string | Function | Yes | Function reference by name or direct import |
description | string | No | When to use this function (hint for the LLM) |
Returns
Section titled “Returns”Promise<{ executionId: string }>
- Object containing the execution ID
Throws
Section titled “Throws”Error
if agent config is invalidError
if no functions are providedError
if the request fails
getStatus(executionId)
Section titled “getStatus(executionId)”Get the current status of an asynchronous agent execution.
Parameters
Section titled “Parameters”Parameter | Type | Required | Description |
---|---|---|---|
executionId | string | Yes | The execution ID returned from start() |
Returns
Section titled “Returns”Promise<AgentStatus>
- The agent status object
AgentStatus
Section titled “AgentStatus”Property | Type | Description |
---|---|---|
status | 'waiting' | 'running' | 'completed' | 'failed' | Current execution status |
progress | any | Intermediate steps or logs (optional) |
result | any | The final result upon completion (optional) |
Throws
Section titled “Throws”Error
if execution ID is invalidError
if the status request fails
Examples
Section titled “Examples”Basic Agent Execution
Section titled “Basic Agent Execution”import agent from "@microfn/agent";
export default async function main() { // Start an agent to research a topic const { executionId } = await agent.start({ objective: "Research the latest developments in quantum computing and summarize the top 3 breakthroughs" }, [ { function: "myusername/search-web", description: "Searches the web for information" }, { function: "myusername/extract-article", description: "Extracts content from a web article" }, { function: "myusername/summarize-text", description: "Summarizes long text content" } ]);
return { executionId, message: "Agent started. Check status with execution ID." };}
Checking Agent Status
Section titled “Checking Agent Status”import agent from "@microfn/agent";
export default async function main(input: { executionId: string }) { const status = await agent.getStatus(input.executionId);
switch (status.status) { case "completed": return { success: true, result: status.result, message: "Agent task completed successfully" };
case "failed": return { success: false, error: "Agent execution failed", details: status.progress };
case "running": return { success: true, status: "running", progress: status.progress, message: "Agent is still working..." };
case "waiting": return { success: true, status: "waiting", message: "Agent is waiting to start" };
default: return { error: "Unknown status" }; }}
Data Processing Agent
Section titled “Data Processing Agent”import agent from "@microfn/agent";
export default async function main(input: { csvUrl: string; analysisType: string;}) { const { executionId } = await agent.start({ objective: `Download CSV from ${input.csvUrl}, analyze the data for ${input.analysisType}, and generate a report with visualizations` }, [ { function: "myusername/download-file", description: "Downloads a file from a URL" }, { function: "myusername/parse-csv", description: "Parses CSV data into structured format" }, { function: "myusername/analyze-data", description: "Performs statistical analysis on data" }, { function: "myusername/create-chart", description: "Creates data visualizations" }, { function: "myusername/generate-report", description: "Generates a formatted report" } ]);
return { executionId, analysisType: input.analysisType };}
Customer Support Agent
Section titled “Customer Support Agent”import agent from "@microfn/agent";
export default async function main(input: { customerId: string; issue: string;}) { const { executionId } = await agent.start({ objective: `Help customer ${input.customerId} resolve: ${input.issue}. Check their account history, identify the problem, and provide a solution or escalate if needed.` }, [ { function: "myusername/get-customer-info", description: "Retrieves customer account information" }, { function: "myusername/check-order-history", description: "Gets customer's order history" }, { function: "myusername/search-knowledge-base", description: "Searches support documentation for solutions" }, { function: "myusername/create-support-ticket", description: "Creates a support ticket for escalation" }, { function: "myusername/send-email", description: "Sends email to customer" } ]);
return { executionId, customerId: input.customerId, issueLogged: true };}
Content Generation Agent
Section titled “Content Generation Agent”import agent from "@microfn/agent";
export default async function main(input: { topic: string; platform: "twitter" | "linkedin" | "blog"; tone: string;}) { const { executionId } = await agent.start({ objective: `Create ${input.platform} content about ${input.topic} with a ${input.tone} tone. Research the topic, generate content, and optimize for the platform.` }, [ { function: "myusername/research-topic", description: "Researches information about a topic" }, { function: "myusername/generate-content", description: "Generates written content" }, { function: "myusername/optimize-for-platform", description: "Optimizes content for specific social media platform" }, { function: "myusername/generate-hashtags", description: "Generates relevant hashtags" }, { function: "myusername/create-image", description: "Creates accompanying images" } ]);
return { executionId };}
Monitoring Agent Execution
Section titled “Monitoring Agent Execution”import agent from "@microfn/agent";import kv from "@microfn/kv";
export default async function main(input: { action: "start" | "check"; executionId?: string; objective?: string;}) { if (input.action === "start") { const { executionId } = await agent.start({ objective: input.objective! }, [ // ... function configurations ]);
// Store execution metadata await kv.set(`agent:${executionId}`, { startTime: new Date(), objective: input.objective, status: "started" });
return { executionId }; }
if (input.action === "check" && input.executionId) { const status = await agent.getStatus(input.executionId); const metadata = await kv.get(`agent:${input.executionId}`);
// Update metadata await kv.set(`agent:${input.executionId}`, { ...metadata, status: status.status, lastChecked: new Date(), result: status.result });
return { ...status, metadata }; }
return { error: "Invalid action or missing parameters" };}
Complex Workflow Agent
Section titled “Complex Workflow Agent”import agent from "@microfn/agent";
export default async function main(input: { projectRequirements: string;}) { const { executionId } = await agent.start({ objective: `Based on these requirements: ${input.projectRequirements} 1. Create a project plan 2. Set up the development environment 3. Generate initial code structure 4. Create documentation 5. Set up CI/CD pipeline` }, [ { function: "myusername/analyze-requirements", description: "Analyzes project requirements" }, { function: "myusername/create-project-plan", description: "Creates detailed project plan" }, { function: "myusername/setup-repository", description: "Sets up git repository" }, { function: "myusername/generate-boilerplate", description: "Generates project boilerplate code" }, { function: "myusername/create-documentation", description: "Creates project documentation" }, { function: "myusername/setup-ci-cd", description: "Sets up CI/CD pipeline" }, { function: "myusername/run-tests", description: "Runs initial tests" } ]);
return { executionId, message: "Project setup agent started" };}
Polling for Completion
Section titled “Polling for Completion”import agent from "@microfn/agent";
async function waitForCompletion( executionId: string, maxWaitTime = 300000, // 5 minutes pollInterval = 5000 // 5 seconds): Promise<any> { const startTime = Date.now();
while (Date.now() - startTime < maxWaitTime) { const status = await agent.getStatus(executionId);
if (status.status === "completed") { return status.result; }
if (status.status === "failed") { throw new Error("Agent execution failed"); }
// Wait before next poll await new Promise(resolve => setTimeout(resolve, pollInterval)); }
throw new Error("Agent execution timed out");}
export default async function main(input: { waitForResult: boolean }) { // Start agent const { executionId } = await agent.start({ objective: "Perform a complex task" }, [ // ... functions ]);
if (input.waitForResult) { try { const result = await waitForCompletion(executionId); return { success: true, result }; } catch (error) { return { success: false, error: error.message }; } }
return { executionId, message: "Agent started in background" };}
Best Practices
Section titled “Best Practices”- Provide clear objectives - Be specific about what the agent should accomplish
- Include relevant functions - Only provide functions the agent might need
- Add descriptions - Help the agent understand when to use each function
- Monitor execution - Check status periodically for long-running agents
- Handle failures gracefully - Agents may fail; have fallback strategies
- Limit function scope - Don’t give agents access to sensitive operations
- Log executions - Track agent activities for debugging and auditing
Use Cases
Section titled “Use Cases”- Research and Analysis: Gather information from multiple sources
- Data Processing: Transform and analyze complex datasets
- Content Creation: Generate articles, reports, and documentation
- Automation: Handle multi-step workflows autonomously
- Customer Service: Resolve customer issues intelligently
- Testing: Perform comprehensive testing scenarios
- Integration: Connect and orchestrate multiple services
Integration with Other Modules
Section titled “Integration with Other Modules”import agent from "@microfn/agent";import kv from "@microfn/kv";import { askAi } from "@microfn/ai";import fn from "@microfn/fn";
export default async function main(input: { task: string }) { // Get agent configuration from KV const agentConfig = await kv.get("agent-config");
// Use AI to enhance the objective const enhancedObjective = await askAi( `Improve this task description: ${input.task}`, { temperature: 0.3 } );
// Start the agent const { executionId } = await agent.start({ objective: enhancedObjective }, agentConfig.functions);
// Log the execution await fn.executeFunction("myusername/log-agent-start", { executionId, originalTask: input.task, enhancedObjective });
// Store execution reference await kv.set(`execution:${executionId}`, { task: input.task, startTime: new Date(), config: agentConfig });
return { executionId, objective: enhancedObjective };}
Limitations
Section titled “Limitations”- Agents run asynchronously and may take time to complete
- No real-time communication with running agents
- Results must be retrieved by polling status
- Agent execution time limits apply based on subscription
- Complex objectives may require careful function selection