Skip to content

AI Agents Module (@microfn/agent)

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.

No installation required! The module is automatically available in all Microfn functions.

import agent from "@microfn/agent";
// or
import { start, getStatus } from "@microfn/agent";

Start an agent execution asynchronously and return immediately.

ParameterTypeRequiredDescription
configAgentConfigYesConfiguration object with agent objective
config.objectivestringYesWhat the agent should accomplish
functionsFunctionConfig[]YesArray of functions the agent can use
PropertyTypeRequiredDescription
functionstring | FunctionYesFunction reference by name or direct import
descriptionstringNoWhen to use this function (hint for the LLM)

Promise<{ executionId: string }> - Object containing the execution ID

  • Error if agent config is invalid
  • Error if no functions are provided
  • Error if the request fails

Get the current status of an asynchronous agent execution.

ParameterTypeRequiredDescription
executionIdstringYesThe execution ID returned from start()

Promise<AgentStatus> - The agent status object

PropertyTypeDescription
status'waiting' | 'running' | 'completed' | 'failed'Current execution status
progressanyIntermediate steps or logs (optional)
resultanyThe final result upon completion (optional)
  • Error if execution ID is invalid
  • Error if the status request fails
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."
};
}
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"
};
}
}
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
};
}
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
};
}
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 };
}
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" };
}
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"
};
}
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" };
}
  1. Provide clear objectives - Be specific about what the agent should accomplish
  2. Include relevant functions - Only provide functions the agent might need
  3. Add descriptions - Help the agent understand when to use each function
  4. Monitor execution - Check status periodically for long-running agents
  5. Handle failures gracefully - Agents may fail; have fallback strategies
  6. Limit function scope - Don’t give agents access to sensitive operations
  7. Log executions - Track agent activities for debugging and auditing
  • 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
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 };
}
  • 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