import express from 'express'
import { createAgent } from '@agentlib/core'
import { openai } from '@agentlib/openai'
import { BufferMemory } from '@agentlib/memory'
const app = express()
app.use(express.json())
// Create a single agent instance (reused across requests)
const memory = new BufferMemory({ maxMessages: 20 })
const agent = createAgent({
name: 'customer-support',
systemPrompt: 'You are a helpful customer support assistant.',
})
.provider(openai({
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-4o',
}))
.memory(memory)
// Chat endpoint
app.post('/api/chat', async (req, res) => {
try {
const { userId, message } = req.body
if (!userId || !message) {
return res.status(400).json({ error: 'Missing userId or message' })
}
// Use userId as sessionId for user-specific conversations
const result = await agent.run({
input: message,
sessionId: `user-${userId}`,
})
res.json({
response: result.output,
tokens: result.state.usage?.totalTokens,
steps: result.state.steps.length,
})
} catch (error) {
console.error('Chat error:', error)
res.status(500).json({ error: 'Internal server error' })
}
})
// Get conversation history
app.get('/api/history/:userId', async (req, res) => {
try {
const { userId } = req.params
const sessionId = `user-${userId}`
const entries = await memory.entries(sessionId)
res.json({
sessionId,
messages: entries[0]?.messages || [],
})
} catch (error) {
console.error('History error:', error)
res.status(500).json({ error: 'Internal server error' })
}
})
// Clear conversation
app.delete('/api/history/:userId', async (req, res) => {
try {
const { userId } = req.params
const sessionId = `user-${userId}`
await memory.clear(sessionId)
res.json({ success: true })
} catch (error) {
console.error('Clear error:', error)
res.status(500).json({ error: 'Internal server error' })
}
})
app.listen(3000, () => {
console.log('Server running on http://localhost:3000')
})