Examples
Advanced code examples and workflows for Agentset
Advanced Usage Examples
This page provides comprehensive examples and workflows to help you leverage Agentset’s full capabilities in your applications.
Financial Analysis Workflow
This example demonstrates analyzing multiple financial documents by creating an agent, uploading multiple reports, and performing comparative analysis:
import { Agentset } from 'agentset';
import { makeAgentsetTool, DEFAULT_SYSTEM_PROMPT } from '@agentset/ai-sdk';
import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
import fs from 'fs';
const openai = createOpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const model = openai('gpt-4o');
async function financialAnalysis() {
// Initialize with environment variable
const agentset = new Agentset({
apiKey: process.env.AGENTSET_API_KEY,
});
// Create a namespace for financial reports
const namespace = await agentset.namespaces.create({
name: "Financial Reports",
});
// Get a reference to the namespace
const ns = agentset.namespace(namespace.id);
// Upload documents one by one via ingest jobs
// Example: Create an ingest job for annual report
const annualReportJob = await ns.ingestion.create({
payload: {
type: "FILE",
fileUrl: "https://example.com/reports/annual-report-2024.pdf",
name: "Annual Report 2024"
},
config: {
metadata: {
documentType: "annual_report",
year: 2024
}
}
});
// Create ingest job for quarterly report
const quarterlyReportJob = await ns.ingestion.create({
payload: {
type: "FILE",
fileUrl: "https://example.com/reports/quarterly-report-q1-2024.pdf",
name: "Quarterly Report Q1 2024"
},
config: {
metadata: {
documentType: "quarterly_report",
year: 2024,
quarter: "Q1"
}
}
});
// Create ingest job for benchmarks
const benchmarksJob = await ns.ingestion.create({
payload: {
type: "FILE",
fileUrl: "https://example.com/reports/industry-benchmarks-2024.pdf",
name: "Industry Benchmarks 2024"
},
config: {
metadata: {
documentType: "benchmarks",
year: 2024
}
}
});
console.log(`Ingest jobs created with IDs: ${annualReportJob.id}, ${quarterlyReportJob.id}, ${benchmarksJob.id}`);
// Get all ingestion jobs and check their status
const { jobs } = await ns.ingestion.all();
console.log("All jobs:", jobs.map(job => ({ id: job.id, status: job.status })));
// Run comparative analysis using chat
const response = await generateText({
model,
systemPrompt: DEFAULT_SYSTEM_PROMPT,
tools: {
knowledgeBase: makeAgentsetTool(ns, {
topK: 15,
rerank: true
}),
},
messages: [
{
role: "user",
content: "Compare our Q1 2024 performance with annual projections and industry benchmarks. Highlight areas where we're outperforming or underperforming the industry."
}
],
});
console.log("Analysis:", response.text);
}
financialAnalysis().catch(console.error);
Legal Document Review Workflow
This example shows how to use Agentset to analyze legal contracts and extract key provisions:
import { Agentset } from 'agentset';
import { makeAgentsetTool, DEFAULT_SYSTEM_PROMPT } from '@agentset/ai-sdk';
import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
import fs from 'fs';
const openai = createOpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const model = openai('gpt-4o');
async function reviewContracts() {
const agentset = new Agentset({
apiKey: process.env.AGENTSET_API_KEY,
});
// Create namespace for legal contracts
const namespace = await agentset.namespaces.create({
name: "Legal Contracts"
});
// Get a reference to the namespace
const ns = agentset.namespace(namespace.id);
// Get list of contract files
const contractFiles = fs.readdirSync('./contracts')
.filter(file => file.endsWith('.pdf'));
// Upload each contract as a separate ingest job
const ingestJobs = [];
for (const file of contractFiles) {
// For each contract, create an ingest job
const ingestJob = await ns.ingestion.create({
payload: {
type: "FILE",
fileUrl: `https://example.com/contracts/${file}`, // In real implementation, you'd use a hosted file URL
name: file
},
config: {
metadata: {
documentType: "legal_contract",
filename: file
}
}
});
ingestJobs.push(ingestJob);
}
console.log(`Created ${ingestJobs.length} ingest jobs for contracts`);
// List all documents in the namespace
const { documents } = await ns.documents.all();
console.log(`Found ${documents.length} documents in the namespace`);
// Extract important clauses using chat
const response = await generateText({
model,
systemPrompt: DEFAULT_SYSTEM_PROMPT,
tools: {
knowledgeBase: makeAgentsetTool(ns, {
topK: 20,
rerank: true,
includeMetadata: true
}),
},
messages: [
{
role: "user",
content: "Identify all liability clauses, termination conditions, and payment terms across all contracts. Highlight any unusual or potentially problematic provisions."
}
]
});
return {
analysis: response.data.text
};
}
reviewContracts().catch(console.error);
Common Challenges & Solutions
When working with many documents, upload them in batches of 5-10 and increase processing wait time proportionally. Consider using a dedicated agent for each document category.
For complex analyses, specify a more capable model in the agent creation and structure your queries clearly. Break down complex questions into multiple targeted queries.
Large documents (>50 pages) may require extended processing time. For real-time applications, pre-process documents in advance and implement status checking before querying.