Agent Class
Core agent initialization, configuration, and lifecycle management
The Agent class is the foundation of the Agentfield TypeScript SDK. Built on Express, it provides a chainable API for registering reasoners and skills while integrating with the Agentfield control plane for distributed workflows.
Constructor
import { Agent } from '@agentfield/sdk';
const agent = new Agent({
nodeId: 'my-agent',
agentFieldUrl: 'http://localhost:8080',
version: '1.0.0',
port: 8001,
aiConfig: {
model: 'gpt-4o',
temperature: 0.7
}
});Parameters
Prop
Type
Registering Reasoners
Register AI-powered functions with agent.reasoner(). Returns the agent for chaining.
agent.reasoner('analyze', async (ctx) => {
const result = await ctx.ai(`Analyze: ${ctx.input.text}`);
return { analysis: result };
}, {
description: 'Analyze text content',
tags: ['analysis', 'ai']
});Reasoner Options
Prop
Type
Registering Skills
Register deterministic utility functions with agent.skill(). Returns the agent for chaining.
agent.skill('format', async (ctx) => {
return JSON.stringify(ctx.input, null, 2);
}, {
description: 'Format data as JSON',
tags: ['utility']
});Skill Options
Prop
Type
Chainable API
All registration methods return the agent for fluent chaining:
const agent = new Agent({ nodeId: 'my-agent' })
.reasoner('analyze', async (ctx) => {
return await ctx.ai(ctx.input.prompt);
})
.reasoner('summarize', async (ctx) => {
return await ctx.ai(`Summarize: ${ctx.input.text}`);
})
.skill('format', async (ctx) => {
return JSON.stringify(ctx.input, null, 2);
});
await agent.serve();Core Methods
agent.serve()
Start the HTTP server with automatic Agentfield registration and heartbeat.
await agent.serve();
// Server starts on configured port (default 8001)agent.shutdown()
Gracefully stop the agent server.
await agent.shutdown();agent.handler()
Get a serverless handler function for Lambda/Cloud Functions.
const handler = agent.handler();
// AWS Lambda
export const lambdaHandler = handler;
// Usage in serverless event
const response = await handler({
action: 'execute',
reasoner: 'analyze',
input: { text: 'Hello world' }
});agent.call()
Execute a reasoner or skill on another agent.
const result = await agent.call('other-agent.analyze', {
text: 'Content to analyze'
});agent.includeRouter()
Import reasoners and skills from an AgentRouter.
import { AgentRouter } from '@agentfield/sdk';
const authRouter = new AgentRouter({ prefix: 'auth', tags: ['authentication'] });
authRouter.reasoner('login', async (ctx) => { /* ... */ });
authRouter.skill('validate', async (ctx) => { /* ... */ });
agent.includeRouter(authRouter);
// Creates: auth_login, auth_validateagent.watchMemory()
Watch for memory changes matching a pattern.
agent.watchMemory('user_*', async (event) => {
console.log(`Memory changed: ${event.key}`, event.data);
}, { scope: 'session' });
// Multiple patterns
agent.watchMemory(['order_*', 'cart_*'], async (event) => {
await notifyOrderSystem(event);
});agent.discover()
Discover capabilities of other agents.
const result = await agent.discover({
tags: ['analysis'],
includeDescriptions: true
});
console.log(result.json?.capabilities);Built-in Endpoints
The agent automatically exposes these HTTP endpoints:
| Endpoint | Method | Description |
|---|---|---|
/health | GET | Health check status |
/discover | GET | Agent discovery payload |
/status | GET | Combined health + reasoners/skills |
/reasoners | GET | List reasoner names |
/skills | GET | List skill names |
/reasoners/:name | POST | Execute a reasoner |
/skills/:name | POST | Execute a skill |
/execute/:name | POST | Serverless execution endpoint |
Deployment Patterns
import { Agent } from '@agentfield/sdk';
const agent = new Agent({
nodeId: 'dev-agent',
agentFieldUrl: 'http://localhost:8080',
devMode: true
});
agent.reasoner('test', async (ctx) => {
return await ctx.ai(ctx.input.prompt);
});
await agent.serve();FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
ENV AGENTFIELD_URL=http://af-server:8080
CMD ["node", "index.js"]// index.ts
const agent = new Agent({
nodeId: 'docker-agent',
agentFieldUrl: process.env.AGENTFIELD_URL,
publicUrl: process.env.AGENT_PUBLIC_URL
});
await agent.serve();When control plane runs in Docker but agent runs on host, set:
AGENT_PUBLIC_URL=http://host.docker.internal:8001
import { Agent } from '@agentfield/sdk';
const agent = new Agent({
nodeId: 'lambda-agent',
deploymentType: 'serverless'
});
agent.reasoner('process', async (ctx) => {
return await ctx.ai(`Process: ${JSON.stringify(ctx.input)}`);
});
// Serverless handler with adapter per platform (Lambda, Vercel, Supabase)
export const handler = agent.handler((event) => {
const body = typeof event?.body === 'string' ? JSON.parse(event.body || '{}') : event?.body;
return {
path: event?.rawPath || event?.path || '/execute',
headers: event?.headers ?? {},
target: event?.target ?? event?.reasoner,
input: body?.input ?? body ?? {},
executionContext: event?.executionContext ?? event?.execution_context,
};
});Event Format:
{
"action": "execute",
"reasoner": "process",
"input": { "data": "..." },
"executionContext": {
"executionId": "exec-123",
"workflowId": "wf-456"
}
}Accessing Services
Get direct access to underlying services:
// Get AI client for direct LLM calls
const aiClient = agent.getAIClient();
const response = await aiClient.generate('Hello');
// Get memory interface
const memory = agent.getMemoryInterface();
await memory.set('key', 'value');
// Get workflow reporter
const workflow = agent.getWorkflowReporter(metadata);
await workflow.progress(50, { status: 'processing' });
// Get DID interface for credentials
const did = agent.getDidInterface(metadata);
await did.generateCredential({ outputData: result });Related
- Configuration - All configuration options
- ReasonerContext - Context for reasoners
- SkillContext - Context for skills
- AgentRouter - Organize reasoners/skills