Documentation Index
Fetch the complete documentation index at: https://officellm.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
WorkerAgent Class
The WorkerAgent class represents specialized AI agents that perform specific types of work.
class WorkerAgent {
public config: WorkerConfig;
private provider: IProvider;
constructor(config: WorkerConfig)
execute(params: Record<string, any>): Promise<TaskResult>
getToolSchema(): Record<string, any>
}
Constructor
new WorkerAgent(config: WorkerConfig)
Creates a new worker agent instance.
Parameters:
config: Worker configuration object
Properties
config: The worker configuration object
provider: Internal LLM provider instance (private)
Methods
execute(params)
Execute a task with the given parameters.
Parameters:
params: Task parameters as key-value pairs
Returns: Promise<TaskResult> - Task execution result
Get the tool schema for this worker (used by managers).
Returns: Record<string, any> - JSON schema object
WorkerConfig Interface
Configuration object for worker agents.
interface WorkerConfig {
name: string;
description?: string;
provider: ProviderConfig;
systemPrompt: string;
tools: ToolDefinition[];
}
Properties
name: Unique identifier for the worker
description: Optional description of the worker’s specialty
provider: LLM provider configuration
systemPrompt: System prompt defining the worker’s behavior and expertise
tools: Array of tool definitions available to this worker
Task Execution
Workers execute tasks through their execute() method:
const result = await worker.execute({
task: 'Solve the equation x² + 5x + 6 = 0',
priority: 'high',
});
Workers can use tools to extend their capabilities:
const workerConfig = {
name: 'Math Solver',
provider: { type: 'openai', apiKey: '...', model: 'gpt-4' },
systemPrompt: 'You are a mathematical expert...',
tools: [
{
name: 'calculate',
description: 'Perform mathematical calculations',
parameters: z.object({
expression: z.string(),
}),
},
{
name: 'analyze_equation',
description: 'Analyze equation structure',
parameters: z.object({
equation: z.string(),
variables: z.array(z.string()).optional(),
}),
},
],
};
The getToolSchema() method generates a schema for manager integration:
const schema = worker.getToolSchema();
// Returns:
// {
// type: 'object',
// properties: {
// task: { type: 'string', description: 'The task to perform' },
// priority: {
// type: 'string',
// enum: ['low', 'medium', 'high'],
// description: 'Task priority level'
// }
// },
// required: ['task']
// }
Error Handling
Worker agents include built-in error handling:
- Provider Errors: Automatic retry with backoff
- Tool Failures: Graceful error reporting
- Invalid Parameters: Zod schema validation
- Network Issues: Timeout and retry logic
Usage Examples
Basic Worker Setup
import { WorkerAgent } from 'officellm';
import { z } from 'zod';
const mathWorker = new WorkerAgent({
name: 'Math Solver',
description: 'Specialized in mathematical calculations and problem solving',
provider: {
type: 'openai',
apiKey: process.env.OPENAI_API_KEY!,
model: 'gpt-4',
temperature: 0.1, // Low temperature for precision
},
systemPrompt: `You are a mathematical expert. Solve problems step by step and provide clear explanations.
Always show your work and double-check calculations.`,
tools: [
{
name: 'calculate',
description: 'Perform mathematical calculations',
parameters: z.object({
expression: z.string().describe('The mathematical expression to evaluate'),
}),
},
{
name: 'analyze_equation',
description: 'Analyze and solve equations',
parameters: z.object({
equation: z.string().describe('The equation to analyze'),
variables: z.array(z.string()).optional().describe('Variables in the equation'),
}),
},
],
});
Task Execution
// Execute a calculation task
const calcResult = await mathWorker.execute({
task: 'Calculate the area of a circle with radius 5',
priority: 'medium',
});
console.log(calcResult.content);
// Output: "The area of a circle with radius 5 is calculated as follows:
// A = πr² = π × 5² = π × 25 = 78.53981633974483
// So the area is approximately 78.54 square units."
// Execute with tool usage
const equationResult = await mathWorker.execute({
task: 'Solve: x² + 5x + 6 = 0',
priority: 'high',
});
console.log(equationResult.content);
// Output includes step-by-step solution using the analyze_equation tool
Specialized Workers
// Research worker
const researchWorker = new WorkerAgent({
name: 'Research Assistant',
description: 'Expert in information gathering and analysis',
provider: {
type: 'gemini',
apiKey: process.env.GEMINI_API_KEY!,
model: 'gemini-pro',
temperature: 0.3,
},
systemPrompt: `You are a research expert. Gather and synthesize information from multiple sources.
Always cite your sources and provide balanced analysis.`,
tools: [
{
name: 'web_search',
description: 'Search the web for information',
parameters: z.object({
query: z.string(),
limit: z.number().min(1).max(20).default(10),
}),
},
{
name: 'analyze_sources',
description: 'Analyze credibility and relevance of sources',
parameters: z.object({
sources: z.array(z.string()),
}),
},
],
});
// Content writer
const writerWorker = new WorkerAgent({
name: 'Content Writer',
description: 'Professional writer specializing in technical content',
provider: {
type: 'anthropic',
apiKey: process.env.ANTHROPIC_API_KEY!,
model: 'claude-3-haiku-20240307',
temperature: 0.7,
},
systemPrompt: `You are a professional technical writer. Create clear, engaging content.
Use appropriate technical language and provide examples where helpful.`,
tools: [
{
name: 'write_article',
description: 'Write an article on a technical topic',
parameters: z.object({
topic: z.string(),
audience: z.enum(['beginner', 'intermediate', 'expert']).default('intermediate'),
outline: z.array(z.string()).optional(),
}),
},
{
name: 'edit_content',
description: 'Edit and improve technical content',
parameters: z.object({
content: z.string(),
improvements: z.array(z.string()),
}),
},
],
});
Advanced Configuration
const advancedWorker = new WorkerAgent({
name: 'Code Analyst',
description: 'Expert in code analysis and improvement',
provider: {
type: 'openai',
apiKey: process.env.OPENAI_API_KEY!,
model: 'gpt-4-turbo',
temperature: 0.2, // Very low for consistent analysis
maxTokens: 2048,
},
systemPrompt: `You are an expert code analyst. Review code for:
- Performance issues
- Security vulnerabilities
- Code quality and maintainability
- Best practices compliance
Provide specific, actionable recommendations with code examples.`,
tools: [
{
name: 'analyze_complexity',
description: 'Analyze code complexity metrics',
parameters: z.object({
code: z.string(),
language: z.string(),
metrics: z.array(z.enum(['cyclomatic', 'cognitive', 'maintainability'])).default(['cyclomatic']),
}),
},
{
name: 'security_scan',
description: 'Scan code for security vulnerabilities',
parameters: z.object({
code: z.string(),
language: z.string(),
severity: z.enum(['low', 'medium', 'high', 'critical']).default('medium'),
}),
},
{
name: 'suggest_improvements',
description: 'Suggest code improvements',
parameters: z.object({
code: z.string(),
focus_areas: z.array(z.string()).optional(),
priority: z.enum(['low', 'medium', 'high']).default('medium'),
}),
},
],
});
Best Practices
System Prompt Design
// Good: Specific expertise and clear guidelines
systemPrompt: `
You are a mathematical expert specializing in algebra and calculus.
- Always show step-by-step solutions
- Use proper mathematical notation
- Explain concepts when introducing them
- Double-check calculations for accuracy
- Provide alternative solution methods when applicable
`
// Avoid: Generic or unclear instructions
systemPrompt: `Be helpful and solve problems.`
// Good: Well-defined, specific tools
tools: [
{
name: 'calculate_integral',
description: 'Calculate definite or indefinite integrals',
parameters: z.object({
expression: z.string().describe('The integral expression'),
bounds: z.object({
lower: z.number().optional(),
upper: z.number().optional(),
}).optional().describe('Integration bounds for definite integrals'),
method: z.enum(['symbolic', 'numeric']).default('symbolic'),
}),
},
]
// Avoid: Overly broad or poorly defined tools
tools: [
{
name: 'do_math',
description: 'Math stuff',
parameters: z.object({
input: z.any(), // Too vague
}),
},
]
Error Handling
try {
const result = await worker.execute(params);
if (!result.success) {
console.error('Worker execution failed:', result.error);
// Implement fallback logic
if (result.error?.includes('rate limit')) {
await delay(60000); // Wait before retry
return await worker.execute(params);
}
}
return result;
} catch (error) {
// Handle network or provider errors
console.error('Worker error:', error);
throw new Error(`Worker ${worker.config.name} failed: ${error.message}`);
}
// Use appropriate temperature for task type
const workerConfig = {
provider: {
type: 'openai',
model: 'gpt-4',
temperature: taskType === 'creative' ? 0.7 : 0.1, // Lower for analytical tasks
maxTokens: 1024, // Reasonable limit
},
// ... rest of config
};
// Cache results for deterministic tasks
const cache = new Map();
async function executeWithCache(worker: WorkerAgent, params: any) {
const key = JSON.stringify(params);
if (cache.has(key)) {
return cache.get(key);
}
const result = await worker.execute(params);
cache.set(key, result);
return result;
}