Skip to main content

Overview

The Autonomous engine enables agents to run continuously, making decisions and using tools until they explicitly decide the task is complete by calling a finish tool. This creates truly self-directed agents. This approach is particularly effective for:
  • Research and information gathering tasks
  • Open-ended exploration problems
  • Scenarios requiring agent initiative and decision-making
  • Long-running tasks with unclear completion criteria

How It Works

  1. Continuous Loop: Agent runs indefinitely, making observations and taking actions
  2. Self-Direction: Agent decides what to do next without predefined steps
  3. Explicit Termination: Agent calls the finish tool when it determines the task is complete
  4. Safety Bounds: Respects maxSteps and tokenBudget limits to prevent runaway execution

Complete Example

This example shows an autonomous research agent:
import "dotenv/config"

import {  createAgent, AgentInstance, defineTool, ReasoningStep  } from '@agentlib/core'
import { openai } from '@agentlib/openai'
import { AutonomousEngine } from '@agentlib/reasoning'

const model = openai({ apiKey: process.env['OPENAI_API_KEY']!, model: process.env['OPENAI_MODEL']!, baseURL: process.env['OPENAI_BASE_URL']! })

const searchTool = defineTool({
    schema: {
        name: 'search',
        description: 'Search the web for information',
        parameters: {
            type: 'object',
            properties: { query: { type: 'string' } },
            required: ['query'],
        },
    },
    async execute({ query }) {
        return { results: [`Result for: ${query}`] }
    },
})

const readFileTool = defineTool({
    schema: {
        name: 'read_file',
        description: 'Read the contents of a file',
        parameters: {
            type: 'object',
            properties: { path: { type: 'string' } },
            required: ['path'],
        },
    },
    async execute({ path }) {
        return { content: `# Contents of ${path}\n...` }
    },
})

async function main() {
    const agent = createAgent({
        name: 'autonomous-agent',
        systemPrompt: 'You are an autonomous research assistant. Work step by step. When you are confident you have a complete answer, call the finish tool.',
    })
        .provider(model)
        .tool(searchTool)
        .tool(readFileTool)
        .reasoning(new AutonomousEngine({ maxSteps: 25 }))
        .policy({ maxSteps: 25, tokenBudget: 50_000 })

    agent.on('step:reasoning', (step: ReasoningStep) => {
        if (step.type === 'thought') console.log('πŸ€–', step.content.slice(0, 120))
        if (step.type === 'tool_call') console.log(`πŸ”§ ${step.toolName}(${JSON.stringify(step.args).slice(0, 60)})`)
    })

    const result = await agent.run(
        'Find and summarize recent developments in quantum computing from the last 6 months.'
    )
    console.log('\nβœ… Final answer:')
    console.log(result.output)
}

main().catch(console.error)

Configuration Options

  • maxSteps: Maximum steps before force-stopping the agent (default: 50)

The Finish Tool

The autonomous engine automatically provides a finish tool that the agent must call to complete:
// Agent calls this internally when task is complete
finish({ answer: "Here's my complete research summary..." })
Make sure your system prompt instructs the agent to call finish when done.

Monitoring Progress

Track the agent’s autonomous decision-making:
agent.on('step:reasoning', (step: ReasoningStep) => {
    if (step.type === 'thought') {
        console.log('πŸ€– Thinking:', step.content)
    }
    if (step.type === 'tool_call') {
        console.log(`πŸ”§ Tool: ${step.toolName}`)
        console.log('   Args:', step.args)
    }
})

Example Output

For the quantum computing research task:
πŸ€– I need to search for recent quantum computing developments
πŸ”§ search({"query":"quantum computing developments 2025"})
πŸ€– Found several breakthroughs. Let me search for more specific information
πŸ”§ search({"query":"quantum error correction 2025"})
πŸ€– I now have comprehensive information. Let me compile the summary
πŸ”§ finish({"answer":"Recent developments in quantum computing..."})

βœ… Final answer:
Recent developments in quantum computing include...

Safety Considerations

Always set safety bounds:
.reasoning(new AutonomousEngine({ maxSteps: 25 }))
.policy({ maxSteps: 25, tokenBudget: 50_000 })
This prevents:
  • Infinite loops
  • Excessive API costs
  • Runaway agent behavior

When to Use Autonomous

Use the Autonomous engine when:
  • Tasks are open-ended without clear step sequences
  • The agent should make its own decisions about what to do next
  • You need true autonomous behavior with self-termination
  • Research and exploration tasks where the path isn’t predetermined
  • You want the agent to demonstrate initiative and problem-solving

Build docs developers (and LLMs) love