0.0.4-beta • Published 9 months ago

@agent_kit/core v0.0.4-beta

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

Agent Kit - Core

A powerful TypeScript framework for building production-ready AI applications with reusable prompts, workflows, and agents. Built for teams that need reliability, testability, and maintainability in their AI systems.

!WARNING
This is an initial beta release of Agent Kit. It is not yet ready for production use. Breaking changes will likely occur.

Key Features

Prompt Management

  • Type-safe prompt templates
  • Message-based conversations
  • Multi-format support (Text, Chat)
  • Variable validation with Zod

🤖 Agent Framework

  • Goal-oriented agents
  • Decision making capabilities
  • Tool integration
  • Context management

⚡ Workflow Engine

  • Sequential prompt chains
  • Parallel execution
  • Multi-agent orchestration
  • Error handling

Installation

pnpm add @agent_kit/core

Quick Start

import { Agent, MessagePrompt, PromptTemplate, ToolManager, WorkflowManager } from '@agent_kit/core';

// Create a prompt template
const template = new PromptTemplate('Generate a {{tone}} response about {{topic}}', { tone: 'professional' });

// Build a conversation
const chat = new MessagePrompt()
  .addSystemMessage('You are an expert content writer.')
  .addUserMessage('Write about AI')
  .addAssistantMessage('What aspect of AI?')
  .addUserMessage('Machine learning basics');

// Define and register a tool
const toolManager = new ToolManager();

const searchTool = {
  name: 'search',
  description: 'Search knowledge base',
  parameters: z.object({
    query: z.string(),
    limit: z.number().optional(),
  }),
  execute: async ({ query, limit = 5 }) => {
    // Implementation
  },
};

toolManager.registerTool(searchTool);

// Create an agent
const agent = new Agent({
  name: 'ContentWriter',
  backstory: 'Expert at creating engaging technical content',
  goal: 'Create engaging content',
  tools: [searchTool],
  decideNextAction: (context) => {
    // Return next action based on context
    return {
      type: 'tool',
      action: searchTool,
    };
  },
});

// Build a workflow
const workflow = new WorkflowManager().createWorkflow({
  type: 'prompt-chain',
  agents: [agent],
  context: { topic: 'machine learning' },
  maxSteps: 10,
});

// Execute the workflow
const result = await workflow.execute();

Core Concepts

Prompt Templates

The framework provides two powerful ways to create prompts:

1. Variable-based Templates (PromptTemplate)

Type-safe templates with variable interpolation:

// Create a template with variables
const template = new PromptTemplate('Write a {{length}} {{type}} about {{topic}} in a {{tone}} tone.', {
  length: 'short',
  type: 'blog post',
});

// Update variables
template.setVariables({
  topic: 'AI trends',
  tone: 'professional',
});

// Render the template
const prompt = template.render();

Key features:

  • Variable interpolation using {{variable}} syntax
  • Safe variable replacement with error checking
  • Reusable template definitions
  • Fluent interface for updates

2. Message-based Conversations (MessagePrompt)

Build structured multi-turn conversations:

const conversation = new MessagePrompt()
  // Add system context
  .addSystemMessage('You are an expert content writer specializing in tech topics.')

  // Add user query
  .addUserMessage('Write about AI trends')

  // Add AI response
  .addAssistantMessage('What specific aspects of AI would you like to focus on?')

  // Add data result
  .addDataMessage('Found 5 recent articles about AI trends', 'research_tool')

  // Add function call
  .addMessage('assistant', 'Let me analyze that data', {
    function_call: {
      name: 'analyze_trends',
      arguments: '{"timeframe": "last_6_months"}',
    },
  });

// Get conversation for AI model
const messages = conversation.render();

Key features:

  • Multiple message roles (system, user, assistant, tool)
  • Function calling support
  • Conversation state management
  • Fluent interface for building conversations
  • Compatible with OpenAI chat format

3. Combining Templates

You can use PromptTemplate within MessagePrompt for dynamic conversations:

// Create reusable templates for different message types
const systemTemplate = new PromptTemplate('You are an expert {{role}} specializing in {{domain}}.', {
  role: 'content writer',
  domain: 'technology',
});

const userTemplate = new PromptTemplate('Write a {{length}} article about {{topic}} focusing on {{aspect}}.');

// Use templates in a conversation
const conversation = new MessagePrompt()
  .addSystemMessage(systemTemplate.render())
  .addUserMessage(
    userTemplate
      .setVariables({
        length: 'comprehensive',
        topic: 'artificial intelligence',
        aspect: 'recent breakthroughs',
      })
      .render(),
  )
  .addAssistantMessage('I will help you write that article. Any specific areas of AI you want to emphasize?');

// Get the formatted conversation
const messages = conversation.render();

This pattern is useful for:

  • Creating reusable message templates
  • Dynamic system prompts
  • Standardized user queries
  • Consistent assistant responses
  • Template-based function calls

Both template types support:

  • Type safety with TypeScript
  • Method chaining
  • Clear error messages
  • Reusability across prompts

Prompt Chains

PromptChain enables sequential execution of prompts and tools with shared context:

// Create a chain with configuration
const chain = new PromptChain({
  maxSteps: 50,
  defaultMaxRetries: 3,
  model: 'gpt-4o-mini',
});

// Add a prompt step using a template
chain.addStep({
  id: 'research',
  type: 'prompt',
  action: new PromptTemplate('Research the latest developments in {{topic}}', {
    topic: 'AI',
  }),
});

// Add a tool step
chain.addStep({
  id: 'analyze',
  type: 'tool',
  action: analysisTool,
  condition: (context) => context.research?.length > 0,
});

// Add a conversation step
chain.addStep({
  id: 'summarize',
  type: 'prompt',
  action: new MessagePrompt()
    .addSystemMessage('You are an expert summarizer')
    .addUserMessage('Summarize the research and analysis'),
});

// Set initial context and execute
const result = await chain.setContext({ additionalInfo: 'Focus on practical applications' }).execute();

Key features:

  • Sequential execution of prompts and tools
  • Conditional step execution
  • Automatic retry handling
  • Shared context between steps
  • Execution statistics tracking
  • Error handling and logging
  • Support for both template types
  • Tool integration

Agents

The framework provides a robust system for creating and managing AI agents:

1. Individual Agents

Create autonomous agents with specific goals and capabilities:

// Create an agent with configuration
const researcher = new Agent({
  name: 'ResearchAgent',
  backstory: 'Expert at analyzing scientific papers and data',
  goal: 'Find and summarize relevant research',
  tools: [searchTool, analyzeTool],
  maxRetries: 3,
  maxSteps: 10,
  decideNextAction: (context) => {
    // Decision logic returns the next action
    return {
      type: 'tool',
      action: searchTool,
    };
  },
});

// Set context and execute
const result = await researcher.setContext({ topic: 'AI trends' }).execute();

// Access agent information
console.log(researcher.getName()); // 'ResearchAgent'
console.log(researcher.getBackstory()); // 'Expert at...'
console.log(researcher.getGoal()); // 'Find and summarize...'
console.log(researcher.getTools()); // [searchTool, analyzeTool]

Key features:

  • Goal-oriented behavior
  • Tool usage capabilities
  • Context management
  • Execution tracking
  • Configurable limits
  • Error handling

2. Agent Management

Coordinate multiple agents and delegate tasks:

// Create an agent manager
const manager = new AgentManager();

// Register agents with metadata
manager.registerAgent('researcher', researcher, {
  skills: ['data analysis', 'literature review'],
  expertise: ['machine learning', 'statistics'],
  description: 'Specializes in scientific research and analysis',
});

manager.registerAgent('writer', writer, {
  skills: ['content writing', 'editing'],
  expertise: ['technical writing', 'blogging'],
  description: 'Expert at creating engaging content',
});

// Find the best agent for a task
const { agent, confidence, reasoning } = await manager.findBestAgent(
  'Analyze recent papers on transformer architectures',
);

// Or automatically delegate and execute
const { result, selectedAgent } = await manager.delegateTask('Write a blog post about AI trends', {
  style: 'technical',
  length: 'long',
});

Key features:

  • Agent registration with metadata
  • AI-powered task delegation
  • Skill and expertise matching
  • Confidence scoring
  • Automatic agent selection
  • Team coordination
  • Task execution tracking

Both agents and the manager support:

  • Type safety with TypeScript
  • Method chaining
  • Error handling
  • State management
  • Execution statistics

Workflows

The WorkflowManager provides several powerful workflow patterns for orchestrating AI agents:

1. Prompt Chain Workflow

Sequential execution where each agent's output becomes context for the next:

const workflow = new WorkflowManager().createWorkflow({
  type: 'prompt-chain',
  agents: [researchAgent, analysisAgent, writingAgent],
  context: { topic: 'AI trends' },
});

2. Routing Workflow

Dynamically routes tasks to the most suitable agent based on capabilities:

const workflow = new WorkflowManager().createWorkflow({
  type: 'routing',
  agents: [techWriter, marketingWriter, academicWriter],
  context: {
    task: 'Write about quantum computing',
    style: 'technical',
  },
});

3. Parallel Workflow

Executes tasks concurrently across multiple agents:

const workflow = new WorkflowManager().createWorkflow({
  type: 'parallel',
  agents: [twitterAgent, linkedinAgent, facebookAgent],
  context: { content: 'Product launch announcement' },
});

4. Orchestrator-Workers Workflow

Hierarchical pattern with a coordinator managing specialized workers:

const workflow = new WorkflowManager().createWorkflow({
  type: 'orchestrator-workers',
  agents: [
    projectManager, // orchestrator
    researcher, // worker
    writer, // worker
    editor, // worker
  ],
  context: { project: 'Research paper' },
});

5. Evaluator-Optimizer Workflow

Iterative improvement through evaluation and optimization:

const workflow = new WorkflowManager().createWorkflow({
  type: 'evaluator-optimizer',
  agents: [
    contentGenerator, // generates content
    qualityEvaluator, // evaluates and provides feedback
  ],
  context: {
    topic: 'Machine Learning',
    evaluationCriteria: {
      accuracy: { weight: 0.4 },
      clarity: { weight: 0.3 },
      engagement: { weight: 0.3 },
    },
    targetScore: 0.9,
  },
});

6. Autonomous Agent Workflow

Self-directed execution by a single agent with goal-based evaluation:

const workflow = new WorkflowManager().createWorkflow({
  type: 'autonomous-agent',
  agents: [strategist],
  context: {
    goals: ['Research market opportunities', 'Identify target segments', 'Propose marketing strategy'],
  },
  maxSteps: 10,
});

Key Features:

  • Flexible workflow patterns for different use cases
  • Built-in progress tracking and statistics
  • Error handling and retry mechanisms
  • Context management between steps
  • Configurable execution limits
  • Real-time logging and monitoring

Task Context

The TaskContext provides state management for workflow executions:

// Create a workflow with context management
const workflow = new WorkflowManager().createWorkflow({
  type: 'prompt-chain',
  agents: [researchAgent, analysisAgent],
  context: {
    topic: 'AI trends',
    metadata: {
      importance: 'high',
      deadline: '2024-03-01',
    },
  },
});

// Access results and metadata during execution
const context = workflow.getContext();

// Get the last result from a specific agent
const lastResearch = context.getLastResultByType('researcher');

// Access specific output fields
const analysis = context.getPreviousOutput<Analysis>('analysis');

// Store workflow-wide metadata
context.setMetadata('status', 'in_progress');

// Get formatted context for prompts
const contextSummary = context.createPromptContext();

🛠️ Tool System

Tools are reusable components that provide specific functionality to agents. They can be created in two ways:

1. Using the ToolProvider Base Class

Create a tool provider class with decorated methods:

import { z } from 'zod';

import { ToolProvider, aiFunction } from '@agent_kit/core';

class SearchTools extends ToolProvider {
  @aiFunction({
    name: 'web_search',
    description: 'Search the web for information',
    inputSchema: z.object({
      query: z.string(),
      limit: z.number().optional(),
    }),
  })
  async webSearch(args: { query: string; limit?: number }) {
    // Implementation
    return `Results for: ${args.query}`;
  }

  @aiFunction({
    name: 'news_search',
    description: 'Search news articles',
    inputSchema: z.object({
      topic: z.string(),
      days: z.number().default(7),
    }),
  })
  async newsSearch(args: { topic: string; days: number }) {
    // Implementation
    return `News about ${args.topic} from last ${args.days} days`;
  }
}

// Register with ToolManager
const toolManager = new ToolManager();
const searchTools = new SearchTools();
searchTools.functions.forEach((tool) => toolManager.registerTool(tool));

2. Direct Tool Registration

Register individual tools directly with the ToolManager:

const searchTool = {
  name: 'search',
  description: 'Search knowledge base',
  parameters: z.object({
    query: z.string(),
    limit: z.number().optional(),
  }),
  execute: async ({ query, limit = 5 }) => {
    // Implementation
    return `Found ${limit} results for: ${query}`;
  },
};

toolManager.registerTool(searchTool);

Using Tools in Agents

Tools can be used in agents by providing them during agent creation:

const agent = new Agent({
  name: 'Researcher',
  backstory: 'Expert at finding information',
  goal: 'Research topics thoroughly',
  tools: searchTools.functions, // Pass all tools from provider
  decideNextAction: (context) => {
    // Decision logic
    return {
      type: 'tool',
      action: 'web_search',
      args: { query: context.topic },
    };
  },
});

Key features:

  • Type safety with TypeScript
  • Method chaining
  • Clear error messages
  • Reusability across prompts

Documentation

Full Documentation: AgentKit.co/docs

Supporters

License

MIT © Dan Schoonmaker

To stay up to date or learn more, follow @DanSchoonmaker on Twitter