class ContextTaskClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.context.ai/api/v1';
}
async uploadFile(fileUrl) {
const response = await fetch(`${this.baseUrl}/files`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ url: fileUrl })
});
if (!response.ok) {
throw new Error(`File upload failed: ${response.statusText}`);
}
return response.json();
}
async createTask(options) {
const { namespace, prompt, fileIds, webhookUrl, model } = options;
const response = await fetch(`${this.baseUrl}/tasks`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
namespace,
delivery: {
type: 'webhook',
config: { endpoint: webhookUrl }
},
input: {
type: 'chat',
prompt,
fileIds,
model
}
})
});
if (!response.ok) {
throw new Error(`Task creation failed: ${response.statusText}`);
}
return response.json();
}
async getTaskStatus(taskId) {
const response = await fetch(`${this.baseUrl}/tasks/${taskId}`, {
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
});
if (!response.ok) {
throw new Error(`Failed to get task: ${response.statusText}`);
}
return response.json();
}
async pollUntilComplete(taskId, intervalMs = 5000, maxAttempts = 60) {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const task = await this.getTaskStatus(taskId);
if (task.status === 'success' || task.status === 'failure') {
return task;
}
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
throw new Error('Task polling timeout');
}
}
// Usage example
const client = new ContextTaskClient(process.env.CONTEXT_API_KEY);
async function analyzeDocument(documentUrl) {
// Upload the document
const { fileId } = await client.uploadFile(documentUrl);
console.log('File uploaded:', fileId);
// Create analysis task
const { taskId } = await client.createTask({
namespace: 'document-analysis',
prompt: 'Analyze this document and extract key insights, risks, and action items.',
fileIds: [fileId],
webhookUrl: 'https://yourcompany.com/webhooks/context'
});
console.log('Task created:', taskId);
// Poll for completion (or wait for webhook)
const result = await client.pollUntilComplete(taskId);
console.log('Task completed:', result.status);
if (result.status === 'success') {
console.log('Analysis:', result.output.text);
if (result.output.archive) {
console.log('Download results:', result.output.archive.presignedUrl);
}
}
return result;
}
analyzeDocument('https://yourbucket.s3.amazonaws.com/reports/q3-report.pdf')
.catch(console.error);