Skip to main content

Overview

The createAgent() function is the primary factory function for creating agent instances in AgentLIB. It accepts either a configuration object or a decorated class and returns an AgentInstance.

Signature

function createAgent<TData = unknown>(
  configOrClass?: AgentConfig<TData> | (new (...args: any[]) => any)
): AgentInstance<TData>

Parameters

configOrClass
AgentConfig<TData> | Class
Agent configuration object or a class decorated with @Agent.When using an object configuration:When using a decorated class, it must be annotated with @Agent and optionally contain methods decorated with @Tool.

Returns

agent
AgentInstance<TData>
A fully configured agent instance ready to execute tasks

Usage Examples

Basic Configuration

import { createAgent } from '@agentlib/core'
import { openai } from '@agentlib/openai'

const agent = createAgent({
  name: 'my-assistant',
  description: 'A helpful AI assistant',
  model: openai({ apiKey: process.env.OPENAI_API_KEY }),
  systemPrompt: 'You are a helpful assistant.'
})

const result = await agent.run('What is 2+2?')
console.log(result.output)

With Tools and Memory

import { createAgent, defineTool } from '@agentlib/core'
import { openai } from '@agentlib/openai'
import { inMemoryStorage } from '@agentlib/memory'

const calculator = defineTool({
  schema: {
    name: 'calculate',
    description: 'Perform basic arithmetic',
    parameters: {
      type: 'object',
      properties: {
        operation: { type: 'string', enum: ['add', 'subtract', 'multiply', 'divide'] },
        a: { type: 'number' },
        b: { type: 'number' }
      },
      required: ['operation', 'a', 'b']
    }
  },
  execute: async (args) => {
    const { operation, a, b } = args
    switch (operation) {
      case 'add': return a + b
      case 'subtract': return a - b
      case 'multiply': return a * b
      case 'divide': return a / b
    }
  }
})

const agent = createAgent({
  name: 'math-tutor',
  model: openai(),
  tools: [calculator],
  memory: inMemoryStorage(),
  reasoning: 'react'
})

const result = await agent.run({
  input: 'Calculate 42 * 8',
  sessionId: 'user-123'
})

With Typed State

interface MyAgentData {
  userId: string
  preferences: Record<string, any>
}

const agent = createAgent<MyAgentData>({
  name: 'personalized-assistant',
  model: openai(),
  data: {
    userId: 'user-123',
    preferences: {}
  }
})

// Tools can access typed state via ctx.data
const tool = defineTool<MyAgentData>({
  schema: { name: 'getUser', description: 'Get user info', parameters: {} },
  execute: async (args, ctx) => {
    return { userId: ctx.data.userId, prefs: ctx.data.preferences }
  }
})

Using Class Decorators

import { createAgent, Agent, Tool, Arg } from '@agentlib/core'
import { openai } from '@agentlib/openai'

@Agent({
  name: 'weather-bot',
  model: openai(),
  systemPrompt: 'You are a weather assistant.'
})
class WeatherAgent {
  @Tool('getWeather', 'Get current weather for a location')
  async getWeather(
    @Arg('location') location: string,
    @Arg({ name: 'unit', type: 'string', required: false }) unit: string = 'celsius'
  ) {
    // Fetch weather data
    return { location, temp: 22, unit }
  }
}

const agent = createAgent(WeatherAgent)
const result = await agent.run('What is the weather in Paris?')

With Policy Constraints

const agent = createAgent({
  name: 'constrained-agent',
  model: openai(),
  policy: {
    maxSteps: 10,              // Limit reasoning iterations
    timeout: 30000,            // 30 second timeout
    maxCost: 0.50,             // Budget limit in USD
    allowedTools: ['search'],   // Restrict to specific tools
    tokenBudget: 4000,         // Max tokens in context
    maxParallelTools: 3        // Concurrent tool execution limit
  }
})

No Configuration

// Creates a minimal agent with default settings
const agent = createAgent()

// Configure fluently
agent
  .provider(openai())
  .use(loggingMiddleware)
  .policy({ maxSteps: 5 })

const result = await agent.run('Hello!')

Error Handling

The function throws an error if:
  • A class is provided without the @Agent decorator
  • Invalid configuration is passed
try {
  const agent = createAgent(MyUndecoratedClass)
} catch (error) {
  console.error(error.message)
  // "Class MyUndecoratedClass is not decorated with @Agent"
}

Type Parameters

TData
generic
default:"unknown"
Type of the custom state data accessible in tools and middleware via ctx.data

See Also

Build docs developers (and LLMs) love