Skip to main content

Node.js Integration

Complete examples for integrating PrompTick agents in Node.js applications.

Installation

npm install axios
# or
npm install node-fetch

Basic Example

const axios = require('axios');

const PROMPTICK_API_KEY = process.env.PROMPTICK_API_KEY;
const AGENT_ID = 'agent_abc123';

async function executeAgent(variables) {
try {
// Execute agent
const response = await axios.post(
`https://api.promptick.ai/api/v1/agents/${AGENT_ID}/execute`,
{ variables },
{
headers: {
Authorization: `Bearer ${PROMPTICK_API_KEY}`,
'Content-Type': 'application/json',
},
}
);

const { jobId } = response.data;
console.log('Job created:', jobId);

// Poll for result
const result = await pollForResult(jobId);
return result;
} catch (error) {
console.error('Error:', error.response?.data || error.message);
throw error;
}
}

async function pollForResult(jobId, maxAttempts = 30) {
for (let i = 0; i < maxAttempts; i++) {
const response = await axios.get(
`https://api.promptick.ai/api/v1/agents/${AGENT_ID}/executions/${jobId}`,
{
headers: {
Authorization: `Bearer ${PROMPTICK_API_KEY}`,
},
}
);

const { status, result, error } = response.data;

if (status === 'completed') {
return result;
}

if (status === 'failed') {
throw new Error(error);
}

// Wait 2 seconds before next poll
await new Promise(resolve => setTimeout(resolve, 2000));
}

throw new Error('Execution timeout');
}

// Usage
(async () => {
const result = await executeAgent({
product_name: 'Smart Watch Pro',
target_audience: 'fitness enthusiasts',
});

console.log('Result:', result.response);
})();

With Retry Logic

async function executeWithRetry(variables, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await executeAgent(variables);
} catch (error) {
if (error.response?.status === 429) {
// Rate limit - use exponential backoff
const delay = Math.pow(2, i) * 1000;
console.log(`Rate limited. Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw error;
}
}
throw new Error('Max retries exceeded');
}

Express.js Integration

const express = require('express');
const app = express();

app.use(express.json());

app.post('/generate-description', async (req, res) => {
try {
const { productName, features } = req.body;

const result = await executeAgent({
product_name: productName,
features: features,
});

res.json({ description: result.response });
} catch (error) {
res.status(500).json({ error: error.message });
}
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});