Skip to content
/ dcyfr-ai-agents Public template

Template for building autonomous AI agent packages with TypeScript, testing, and release workflows.

License

Notifications You must be signed in to change notification settings

dcyfr/dcyfr-ai-agents

Repository files navigation

@dcyfr/ai-agents

Autonomous agent framework template - Build AI agents with tool usage, memory, and observability

πŸ“¦ Starter Template β€” This is a starter template for cloning, not an npm package. Use git clone or download the source to create your own AI agent application. This package is marked private: true and is not published to npm.

TypeScript Node.js Tests License

Use Case: Customer Service Use Case: Research Use Case: Code Generation


⚑ 30-Second Quick Start

# Clone template
npx degit dcyfr/dcyfr-ai-agents my-agent
cd my-agent

# Install and run
npm install
npm run dev
# βœ… Agent running, ready to process tasks

🧭 Related Packages

Package Purpose Type
@dcyfr/ai Core AI framework npm package
@dcyfr/ai-nodejs Node.js starter Template
@dcyfr/ai-api REST API template Template
dcyfr-labs Production Next.js app Application

🎯 Overview

@dcyfr/ai-agents is a production-ready starter template for building autonomous AI agents with tool usage, memory management, and comprehensive observability.

Perfect for developers building AI assistants, research agents, workflow automation, or any application requiring autonomous decision-making with external tool integration.

⚑ Quick Decision: Is This Template Right for Me?

βœ… Use this template when:

  • πŸ€– Building autonomous AI agents that make multi-step decisions
  • πŸ› οΈ Need type-safe tool usage with Zod validation
  • 🧠 Require dual memory architecture (short-term + long-term)
  • πŸ“‘ Want full observability into agent behavior
  • πŸ”’ Need production-grade error handling and resilience
  • πŸ’Ό Building customer service bots, research assistants, or code generation tools

❌ Consider alternatives when:

  • Simple chat interface needed β†’ Use Vercel AI SDK or LangChain Chat
  • Browser automation required β†’ Use Playwright with custom orchestration
  • Low-latency streaming (<100ms) β†’ Use Vercel AI SDK with streaming
  • Complex agent orchestration β†’ Use LangGraph or AutoGPT
  • Just learning AI β†’ Start with simpler examples before autonomous agents

Table of Contents

πŸ“‘ Table of Contents

✨ Features

Core Capabilities

  • πŸ€– Autonomous Agent Loop - Multi-step reasoning with configurable iteration limits

    • Thought β†’ Action β†’ Observation cycle
    • Automatic decision-making flow
    • Graceful termination when goals are met
  • πŸ› οΈ Type-Safe Tool System - Production-ready tool framework

    • Zod schema validation for all inputs
    • TypeScript generics for full type safety
    • Built-in tools: calculator, search, time
    • Easy custom tool creation with examples
  • 🧠 Dual Memory Architecture - Flexible persistence options

    • Short-term: In-memory with configurable size limits
    • Long-term: File-based with auto-save and import/export
    • Async API compatible with any storage backend
    • Perfect for conversation history and learned knowledge
  • πŸ“‘ Event-Driven Observability - Complete visibility into agent behavior

    • Real-time events: start, step, tool_call, tool_result, error, finish
    • Multiple event listeners support
    • Custom monitoring and logging integrations
    • Debug agent behavior in development
  • πŸ”’ Production-Grade Error Handling - Resilient agent execution

    • Try-catch wrappers around all tool executions
    • Graceful degradation on failures
    • Detailed error propagation in results
    • Automatic Error/non-Error normalization
  • πŸ“Š Developer Experience - Built for productivity

    • TypeScript-first: 100% strict mode, full IntelliSense
    • 95%+ test coverage: Every feature thoroughly tested
    • Zero config: Works out of the box
    • 3 complete examples: Customer service, research, code generation

Production Ready

  • βœ… Semantic versioning with automated releases (changesets)
  • βœ… ESLint + Prettier for code quality
  • βœ… GitHub Actions for CI/CD
  • βœ… MIT License for commercial use
  • βœ… Comprehensive documentation with API reference
  • βœ… Security audited production dependencies

Use Cases

Perfect for building:

  • 🀝 Customer service chatbots with tool integration
  • πŸ”¬ Research assistants that search and synthesize information
  • πŸ’» Code generation agents with file system access
  • πŸ”„ Workflow automation with multi-step reasoning
  • πŸ“ Content creation agents with fact-checking tools
  • 🎯 Task planning and execution systems

πŸš€ Quick Start

# Clone or use as template
git clone https://github.com/dcyfr/dcyfr-ai-agents.git
cd dcyfr-ai-agents

# Install dependencies
npm install

# Run example agent
npm run example:customer-service

# Run tests
npm test

# Build for production
npm run build

πŸ“¦ Installation

npm install @dcyfr/ai-agents

πŸ’‘ Basic Usage

import { Agent, calculatorTool, searchTool, ShortTermMemory } from '@dcyfr/ai-agents';

// Create an agent
const agent = new Agent({
  name: 'Assistant',
  description: 'Helpful AI assistant',
  tools: [calculatorTool, searchTool],
  memory: new ShortTermMemory(),
  maxIterations: 10,
});

// Run the agent
const result = await agent.run('Calculate 15 * 23 and search for information about AI');

console.log(result.output);
console.log(`Completed in ${result.iterations} steps`);

πŸ—οΈ Architecture

Agent Execution Flow

The agent follows a continuous reasoning loop with tool integration and memory persistence:

sequenceDiagram
    participant User
    participant Agent
    participant Tools
    participant Memory
    participant LLM

    User->>Agent: Initialize with task
    Agent->>Tools: Register available tools
    Agent->>Memory: Load context

    loop Reasoning Loop (max iterations)
        Agent->>LLM: Thought (Plan next action)
        LLM-->>Agent: Decision

        alt Tool Required
            Agent->>Tools: Action (Execute tool)
            Tools-->>Agent: Observation (Result)
            Agent->>Memory: Store interaction
        else Goal Met
            Agent->>Memory: Save final state
            Agent-->>User: Return result
        end
    end

    style Agent fill:#d4edda
    style Tools fill:#fff3cd
    style Memory fill:#cfe2ff
    style LLM fill:#f8d7da
Loading

Core Components

Agent

The main agent class that orchestrates:

  • Decision-making loop
  • Tool execution
  • Memory management
  • Event emission
const agent = new Agent({
  name: 'My Agent',
  description: 'What this agent does',
  maxIterations: 10,
  temperature: 0.7,
  verbose: true,
  tools: [/* tools */],
  memory: new ShortTermMemory(),
  listeners: [(event) => console.log(event)],
});

Tools

Type-safe tools with Zod validation:

import { z } from 'zod';
import type { Tool } from '@dcyfr/ai-agents';

const myTool: Tool<{ query: string }, { result: string }> = {
  name: 'my_tool',
  description: 'Description for the agent',
  inputSchema: z.object({
    query: z.string().min(1),
  }),
  async execute(input) {
    // Tool logic here
    return { result: `Processed: ${input.query}` };
  },
};

Memory

Two memory implementations:

Short-term (in-memory):

const memory = new ShortTermMemory(100); // Max 100 entries
await memory.save('key', 'value');
const value = await memory.get('key');

Long-term (file-based):

const memory = new LongTermMemory({
  storagePath: './agent-memory.json',
  autoSaveInterval: 5000, // Auto-save every 5s
});

await memory.load();
await memory.save('knowledge', { learned: 'data' });
await memory.persist();

Events

Monitor agent execution:

const agent = new Agent({
  // ... config
  listeners: [
    (event) => {
      switch (event.type) {
        case 'start':
          console.log('Agent started:', event.data.input);
          break;
        case 'tool_call':
          console.log('Calling tool:', event.data.tool);
          break;
        case 'finish':
          console.log('Agent finished:', event.data.output);
          break;
      }
    },
  ],
});

⬆️ Back to top


πŸ“š Examples

Customer Service Agent

import { Agent, searchTool, getCurrentTimeTool } from '@dcyfr/ai-agents';

const agent = new Agent({
  name: 'Customer Support',
  description: 'Helpful customer service agent',
  tools: [searchTool, getCurrentTimeTool],
});

const result = await agent.run('Help me track my order #12345');

Research Agent

import { Agent, searchTool, calculatorTool, LongTermMemory } from '@dcyfr/ai-agents';

const memory = new LongTermMemory({ storagePath: './research.json' });
await memory.load();

const agent = new Agent({
  name: 'Researcher',
  description: 'Research assistant',
  tools: [searchTool, calculatorTool],
  memory,
});

const result = await agent.run('Research AI agent frameworks and compare adoption rates');

Custom Tool

import { z } from 'zod';

const weatherTool = {
  name: 'get_weather',
  description: 'Get current weather for a location',
  inputSchema: z.object({
    location: z.string(),
    units: z.enum(['celsius', 'fahrenheit']).optional(),
  }),
  async execute(input) {
    // Fetch weather from API
    return {
      location: input.location,
      temperature: 72,
      conditions: 'sunny',
    };
  },
};

agent.registerTool(weatherTool);

⬆️ Back to top


πŸ§ͺ Testing

# Run all tests
npm test

# Watch mode
npm run test

# Coverage report
npm run test:coverage

Test Structure

  • Unit tests - tests/unit/*.test.ts
  • Integration tests - tests/integration/*.test.ts
  • Fixtures - tests/fixtures/

⬆️ Back to top


πŸ“– API Reference

Agent

  • new Agent(options) - Create agent instance
  • agent.registerTool(tool) - Add tool to agent
  • agent.run(input) - Execute agent with input
  • agent.getState() - Get current execution state
  • agent.reset() - Reset agent to initial state

ToolRegistry

  • registry.register(tool, category?) - Register tool
  • registry.unregister(toolName) - Remove tool
  • registry.get(toolName) - Get tool by name
  • registry.getAll() - Get all tools
  • registry.execute(toolName, input) - Execute tool

Memory

Both ShortTermMemory and LongTermMemory implement:

  • save(key, value) - Store value
  • get(key) - Retrieve value
  • delete(key) - Remove value
  • clear() - Clear all data
  • keys() - List all keys

⬆️ Back to top


πŸ“š Documentation

Getting Started

Key Concepts

Agent Loop: The core execution pattern where the agent iterates through thought β†’ action β†’ observation cycles until completing its task or reaching the maximum iteration limit.

Tools: Functions the agent can call to interact with external systems. Each tool has:

  • A unique name
  • A description the agent uses to decide when to call it
  • A Zod input schema for validation
  • An execute function that performs the actual work

Memory: Persistent storage for the agent to save and retrieve information across runs. Use short-term for conversation context and long-term for learned knowledge.

Events: Real-time notifications of agent activity. Subscribe to events for logging, monitoring, debugging, or building custom integrations.

External Resources

Related Projects

⬆️ Back to top


βš™οΈ Configuration

Environment Variables

# None required - fully self-contained template
# Add your own as needed (e.g., API keys)
OPENAI_API_KEY=your-key-here  # If integrating with LLM providers

TypeScript

Strict mode enabled by default in tsconfig.json. Customize as needed.

🀝 Contributing

See CONTRIBUTING.md for guidelines.

πŸ“„ License

MIT Β© DCYFR

πŸ”— Related Templates

πŸ“ž Support


Built with ❀️ by DCYFR - Making AI development accessible

About

Template for building autonomous AI agent packages with TypeScript, testing, and release workflows.

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published