import 'dotenv/config'
import { createAgent, defineTool } from '@agentlib/core'
import { openai } from '@agentlib/openai'
import { BufferMemory } from '@agentlib/memory'
import { createLogger } from '@agentlib/logger'
interface AppData {
userId: string
plan: 'free' | 'pro'
}
const getWeatherTool = defineTool({
schema: {
name: 'get_weather',
description: 'Get the current weather for a location.',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'The city' },
},
required: ['location'],
},
},
async execute({ location }) {
return { location, temperature: 22, condition: 'sunny' }
},
})
const agent = createAgent<AppData>({
name: 'assistant',
systemPrompt: 'You are a helpful assistant.',
data: { userId: 'default', plan: 'free' },
policy: {
maxSteps: 10,
tokenBudget: 10_000,
},
})
.provider(openai({
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-4o'
}))
.memory(new BufferMemory({ maxMessages: 20 }))
.tool(getWeatherTool)
.use(createLogger({ level: 'debug' }))
.use({
name: 'plan-guard',
scope: 'run:before',
async run(mCtx, next) {
if (mCtx.ctx.data.plan === 'free' && mCtx.ctx.input.length > 500) {
throw new Error('Input too long for free plan')
}
await next()
},
})
agent.on('run:start', ({ input }) => {
console.log(`[run:start] input="${input}"`)
})
agent.on('tool:after', ({ tool, result }) => {
console.log(`[tool:after] ${tool} →`, result)
})
const result = await agent.run({
input: 'What is the weather in Buenos Aires and Tokyo?',
data: { userId: 'user-123', plan: 'pro' },
})
console.log('\nFinal response:')
console.log(result.output)
console.log('\nToken usage:', result.state.usage)
console.log('Steps taken:', result.state.steps.length)