Skip to main content
Version: v5.0

IafAISvc

Use the IafAISvc API to create and manage the AISvc service resources, such as agents, tools, teams and creating conversations.

createAgents

Creates one or more Agent resource.

ParameterRequiredTypeDescription
agentsYesArray<Agent>Pass an array of Agent objects you define.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectPass a JSON object for optional query parameters.
Returns

Promise<Page<Agent>> - A promise with the created Agent objects.

Examples
const agents = [
{
_namespaces: ['building_1234'],
_name: 'HVAC Monitoring Agent',
_background: 'Monitors HVAC system performance and detects anomalies.',
_userType: 'hvac_monitor_agent',
_tools: ['temperature_sensor_tool', 'energy_usage_tool'],
_agentClass: 'HVACMonitoringAgent', // applicable only when Agent have custom source code
_config: {
_model: "gpt-4o",
_provider: "openai"
}
},
{
_namespaces: ['building_1234'],
_name: 'Lighting Optimization Agent',
_background: 'Optimizes lighting schedules based on occupancy and daylight levels.',
_userType: 'lighting_opt_agent',
_config: {
_model: "gpt-4o",
_provider: "openai"
}
},
];

IafAISvc.createAgents(agents, ctx, options);

createConversation

Creates a new conversation or continues an existing one.

ParameterRequiredTypeDescription
requestYesConversationCreateRequestThe conversation create request object.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsYesundefined
Returns

Promise<Conversation> - A promise with the Conversation object.

createKnowledgeBases

Creates one or more KnowledgeBase resources.

ParameterRequiredTypeDescription
knowledgeBasesYesundefined
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters (e.g., pagination or query hints).
knowledgeBaseYesKnowledgeBaseArray of KnowledgeBase objects to create.
Returns

Promise<Page<KnowledgeBase>> - A promise with the created KnowledgeBase objects.

Examples
const kbs = { _name: 'Warranty Docs', _fileId: '94a1eb2b-06bd-426e-a3ce-e7ab609ea231',_fileVersionId: '35a1ab2c-16bd-426e-b3ce-a7ab609ea482', _userType: 'warranty_documents', _namespaces: ['ws1'] };
await IafAISvc.createKnowledgeBases(kb, ctx);

createPermissions

Creates permissions for AISvc resources such as Agents, Tools, Teams, and Conversations.

ParameterRequiredTypeDescription
permissionsYesArray<Permission>Pass an array of Permission objects.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<CreatePermissionsResponse> - A CreatePermissionsResponse object that contains the successful and failed permissions in separate arrays.

createTeam

Creates a Team resource.

ParameterRequiredTypeDescription
teamYesTeamPass a Team object you define.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters, such as pagination options.
Returns

Promise<Team> - A promise with the created Team object.

Examples
const teamObj = {
"_name": "SP - Telemetry Fetcher Team - new",
"_agents": [
{ "_userType": "sp_telemetry_fetcher" },
{ "_userType": "sp_anamoly_pressure_checker" }
],
"_flow": [
{ "to": "sp_telemetry_fetcher", "from": "__start__" },
{ "to": "sp_anamoly_pressure_checker", "from": "sp_telemetry_fetcher" },
{ "to": "__end__", "from": "sp_anamoly_pressure_checker" }
],
"_namespaces": [
"Amoghtestworkspace_m8NrvPU3"
]
}

createTools

Creates one or more Tool resource.

ParameterRequiredTypeDescription
toolsYesArray<Tool>Pass an array of Tool objects you define.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectPass a JSON object for optional query parameters.
Returns

Promise<Page<Tool>> - A promise with the created Tool objects.

Examples
const tools = [
{
_namespaces: ['building_1234'],
_name: 'Temperature Sensor Tool',
_description: 'Provides real-time temperature readings.',
_userType: 'temperature_sensor_tool',
_toolClass: 'TemperatureSensorTool',
},
{
_namespaces: ['building_1234'],
_name: 'Energy Usage Tool',
_description: 'Calculates energy consumption patterns.',
_userType: 'energy_usage_tool',
},
];

IafAISvc.createTools(tools, ctx, options);

deleteAgent

Deletes an Agent resource .

ParameterRequiredTypeDescription
idYesStringPass the Agent's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteAgent('e8a53325-fbb5-4a2d-a955-ef5fa74591df', ctx);

deleteKnowledgeBase

Deletes a KnowledgeBase resource.

ParameterRequiredTypeDescription
idYesStringThe KnowledgeBase id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - ok:204 response.

Examples
await IafAISvc.deleteKnowledgeBase('94a1eb2b-06bd-426e-a3ce-e7ab609ea231', ctx);

deletePermission

Deletes a permission when you pass its id.

ParameterRequiredTypeDescription
idYesStringThe Permission object's id.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<String> - ok:204 response.

deleteTeam

Deletes a Team resource.

ParameterRequiredTypeDescription
idYesStringPass the Team's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

deleteTool

Deletes a Tool resource.

ParameterRequiredTypeDescription
idYesStringPass the Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteTool('a8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getAgent

Gets an Agent resource object by its id.

ParameterRequiredTypeDescription
idYesStringPass the Agent's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Agent> - A promise with the Agent object.

Examples
const agent = await IafAISvc.getAgent('e8a53325-fbb5-4a2d-a955-ef5fa74591df', ctx);

getAgents

Gets Agent resource objects that match your criteria in the namespace, It also lists down system agents as well

ParameterRequiredTypeDescription
criteriaNoAgentCriteriaPass a JSON object with filter parameters, such as "_userType" or "query".
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsPass a JSON object for optional control parameters, such as pagination options.
Returns

Promise<Page<Agent>> - A promise with a page that contains the Agent objects.

Examples
// Get all agents
const allAgents = await IafAISvc.getAgents({}, ctx);

// Get agents by userType
const hvacAgents = await IafAISvc.getAgents({ _userType: 'hvac_monitor_agent' }, ctx, { _pageSize: 50 });

getAgentSourceCode

Retrieves source code for an Agent resource.

ParameterRequiredTypeDescription
agentIdYesStringThe Agent's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<SourceCode> - A Promise resolving to the Agent's SourceCode.

Examples
const agentCode = await IafAISvc.getAgentSourceCode('1201ae31-d2c3-4428-8122-17cd4ce802f3', ctx);

getConversation

Gets a Conversation resource by its id.

ParameterRequiredTypeDescription
idYesStringPass the Conversation's id.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoConversationOptionsJSON object for optional query parameters.
Returns

Promise<Conversation> - A promise with the Conversation object.

getConversations

Gets Conversation objects in the namespace

ParameterRequiredTypeDescription
criteriaNoJSONPass a JSON object with filter parameters, Currently no criteria supported
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsPass a JSON object for optional control parameters, such as pagination options.
Returns

Promise<Page<Conversation>> - A promise with a page that contains the Agent objects.

Examples
// Get all conversations
const conversations = await IafAISvc.getConversations({ }, ctx, { _pageSize: 50 });

getKnowledgeBase

Gets a KnowledgeBase resource by its id.

ParameterRequiredTypeDescription
idYesStringThe KnowledgeBase id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<KnowledgeBase> - A promise with the KnowledgeBase object.

Examples
const kb = await IafAISvc.getKnowledgeBase('94a1eb2b-06bd-426e-a3ce-e7ab609ea231', ctx);

getKnowledgeBases

Gets KnowledgeBase resources matching criteria.

ParameterRequiredTypeDescription
criteriaNoKnowledgeBaseCriteriaFilter parameters (e.g., _userType, _vectorizedStatus).
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsOptional control parameters like pagination.
Returns

Promise<Page<KnowledgeBase>> - A promise with a page of KnowledgeBase objects.

Examples
const page = await IafAISvc.getKnowledgeBases({ _userType: 'warranty_documents' }, ctx, { _pageSize: 50 });

getPermissions

Gets permissions for AISvc resources.

ParameterRequiredTypeDescription
criteriaYesPermissionCriteriaPass a PermissionCriteria object with the properties and values to filter your search.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<Page<Permission>> - A Page object with the Permission objects you want.

getTeam

Gets a Team resource object by its id.

ParameterRequiredTypeDescription
idYesStringPass the Team's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Team> - A promise with the Team object.

getTeams

Gets Team resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoTeamCriteriaPass a JSON object with filter parameters, such as "_name" or "query".
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsControl parameters, such as pagination options.
Returns

Promise<Page<Team>> - A promise with a page that contains the Team objects.

getTool

Gets a Tool resource object by its id.

ParameterRequiredTypeDescription
idYesStringPass the Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Tool> - A promise with the Tool object.

Examples
const tool = await IafAISvc.getTool('a8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getTools

Gets Tool resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoToolCriteriaPass a JSON object with filter parameters, such as "_userType" or "query".
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsPass a JSON object for optional control parameters, such as pagination options.
Returns

Promise<Page<Tool>> - A promise with a page that contains the Tool objects.

Examples
// Get all tools
const allTools = await IafAISvc.getTools({}, ctx);

// Get tools by userType
const sensorTools = await IafAISvc.getTools({ _userType: 'temperature_sensor_tool' }, ctx, { _pageSize: 50 });

getToolSourceCode

Retrieves source code for a Tool resource.

ParameterRequiredTypeDescription
toolIdYesStringThe Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<SourceCode> - A Promise resolving to the Tool's SourceCode.

Examples
const toolCode = await IafAISvc.getToolSourceCode('tool-id-1234', ctx);

updateAgent

Updates an existing Agent resource. Editable fields: _name, _background, _userType, _tools, _agentClass.

ParameterRequiredTypeDescription
idYesStringPass the Agent's id.
agentYesAgentPass an Agent object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Agent> - A promise with the updated Agent object.

Examples
const updates = {
_name: 'Updated Agent Name',
_background: 'Updated background context.',
_tools: ['new_tool_type'],
_config: {
_model: "gpt-4o",
_provider: "openai"
}
};
const updatedAgent = await IafAISvc.updateAgent('e8a53325-fbb5-4a2d-a955-ef5fa74591df', updates, ctx);

updateKnowledgeBase

Updates an existing KnowledgeBase resource. Editable fields: _name, _userType.

ParameterRequiredTypeDescription
idYesStringThe KnowledgeBase id.
knowledgeBaseYesKnowledgeBaseKnowledgeBase object with updated properties.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<KnowledgeBase> - A promise with the updated KnowledgeBase object.

Examples
const updates = { _name: 'Updated Name',_fileId: '15a1ac2b-96ba-626e-b3ce-e7ab609ea612', _fileVersionId: '55a1bc2a-06bb-923e-a3cd-a7ab609ea609'};
await IafAISvc.updateKnowledgeBase('94a1eb2b-06bd-426e-a3ce-e7ab609ea231', updates, ctx);

updatePermissions

Updates permissions for AISvc resources. If a permission you pass doesn't exist, the method creates the permission.

ParameterRequiredTypeDescription
permissionsYesArray<Permission>Pass an array of Permission objects.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<CreatePermissionsResponse> -

updateTeam

Updates an existing Team resource. Editable fields: _name, _agents, _flow.

ParameterRequiredTypeDescription
idYesStringPass the Team's id.
teamYesObjectPass a Team object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Team> - A promise with the updated Team object.

updateTool

Updates an existing Tool resource. Editable fields: _name, _description, _userType, _toolClass.

ParameterRequiredTypeDescription
idYesStringPass the Tool's id.
toolYesToolPass a Tool object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Tool> - A promise with the updated Tool object.

Examples
const updates = {
_description: 'Updated description.',
_toolClass: 'AdvancedEnergyTool',
};
const updatedTool = await IafAISvc.updateTool('a8a53325-dbb5-4a2d-a655-ef5fa74591d3', updates, ctx);

uploadAgentSourceCode

Uploads source code for an Agent resource.

ParameterRequiredTypeDescription
agentIdYesStringThe Agent's id.
sourceCodeYesSourceCodeObject containing source code (_content and optional _id).
ctxNoCtxContext, such as namespaces and authentication token information.
optionsYesundefined
Returns

Promise<SourceCode> - A Promise resolving to the uploaded SourceCode.

Examples
//Upload source code as string
const sourceCode = { "_content": "import { Agent } from '@dtplatform/agent-core';\nimport { IafItemSvc } from '@dtplatform/platform-api';\n\ninterface ChillerRequest {\n chillerId: string;\n capacityKw: number;\n metric: string; // e.g. \"chiller_load_kw\"\n thresholdPct: number; // e.g. 0.9 for 90%\n lookbackDays?: number;\n}\n\ntype Reading = {\n _id: string;\n _ts: string; // timestamp in UTC\n chiller_load_kw: number;\n chiller_load_pct: number;\n};\n\ntype Data = {\n _list: Reading[];\n};\n\nexport default class ChillerForecastAgent extends Agent {\n requestContext: any = {}\n constructor(options: any, requestContext: any) {\n super(options);\n this.requestContext = requestContext;\n }\n\n async processRequest(\n type: string,\n state?: any,\n prompt?: string,\n tools?: any[],\n userId?: string,\n sessionId?: string,\n chatHistory?: [],\n additionalParams?: Record<string, string>,\n ): Promise<any> {\n\n // ------------------------------\n // 1. Interpret prompt (simple parsing via LLM)\n // ------------------------------\n const llmRes: any = await this.simpleCall(`Extract structured JSON from the following prompt. \n Fields: chillerId and lookbackDays (optional).\n Prompt: ${prompt}`);\n\n //console.log(llmRes, \">>llmRes\")\n console.log(llmRes?.content, \">>llmRes?.content\")\n\n let chillerReq: ChillerRequest;\n\n try {\n let rawContent: string = llmRes?.content || \"\";\n\n // Remove Markdown code fences if they exist\n rawContent = rawContent.replace(/```json|```/gi, \"\").trim();\n\n // Try to extract JSON block if extra text is present\n const jsonMatch = rawContent.match(/\{[\s\S]*\}/);\n if (jsonMatch) {\n rawContent = jsonMatch[0];\n }\n\n chillerReq = JSON.parse(rawContent);\n\n } catch (err) {\n console.error(\"Failed to parse chiller request:\", err);\n return {\n messages: [\n {\n role: \"assistant\",\n content: JSON.stringify({ error: \"Invalid LLM JSON response\", raw: llmRes })\n }\n ]\n };\n }\n\n const lookback = chillerReq.lookbackDays ?? 90;\n const startDate = new Date();\n startDate.setDate(startDate.getDate() - lookback);\n\n const aggs = [\n {\n $match: {\n \"_tsMetadata._sourceId\": { \"$regex\": `.*${chillerReq.chillerId}.*` } ,\n \"_ts\": { $gte: startDate.toISOString() }\n }\n },\n { $sort: { ts: 1 } },\n { $limit: 10 }\n\n ];\n\n console.log('Aggs::', JSON.stringify(aggs))\n \n let res = await IafItemSvc.aggregateReadings('68c50a58993fee0ea750db6f', aggs, this.requestContext, {});\n let finalRes = this.predictChiller90(res);\n console.log(finalRes, 'finalRes')\n return {\n messages: [\n {\n role: \"assistant\",\n content: `Chiller will cross 90% load around:\", ${finalRes}`\n }\n ]\n };\n }\n\n\n predictChiller90(data: Data): Date | null {\n // Step 1: clean duplicates by unique timestamp\n const readings: Reading[] = Object.values(\n data._list.reduce<Record<string, Reading>>((acc, item) => {\n acc[item._ts] = item; // overwrite duplicates\n return acc;\n }, {})\n );\n\n if (readings.length < 2) return null; // not enough data to predict\n\n // Step 2: sort by timestamp\n readings.sort((a, b) => new Date(a._ts).getTime() - new Date(b._ts).getTime());\n\n // Step 3: convert timestamps to epoch ms\n const points = readings.map(r => ({\n ts: new Date(r._ts).getTime(),\n load: r.chiller_load_pct\n }));\n\n // Step 4: calculate slope & intercept (linear regression)\n const n = points.length;\n const sumX = points.reduce((s, p) => s + p.ts, 0);\n const sumY = points.reduce((s, p) => s + p.load, 0);\n const sumXY = points.reduce((s, p) => s + p.ts * p.load, 0);\n const sumX2 = points.reduce((s, p) => s + p.ts * p.ts, 0);\n\n const denominator = n * sumX2 - sumX * sumX;\n if (denominator === 0) return null; // avoid division by zero\n\n const slope = (n * sumXY - sumX * sumY) / denominator;\n const intercept = (sumY - slope * sumX) / n;\n\n // Step 5: solve for timestamp when load = 0.9\n const targetLoad = 0.9;\n const targetTs = (targetLoad - intercept) / slope;\n\n if (isNaN(targetTs) || !isFinite(targetTs)) return null;\n\n return new Date(targetTs);\n }\n\n}\n"};
await IafAISvc.uploadAgentSourceCode('1201ae31-d2c3-4428-8122-17cd4ce802f3', sourceCode, ctx);

//Upload source code as file
const sourceCode = {_file:fileStream};
await IafAISvc.uploadAgentSourceCode('1201ae31-d2c3-4428-8122-17cd4ce802f3', sourceCode, ctx);

uploadToolSourceCode

Uploads source code for a Tool resource.

ParameterRequiredTypeDescription
toolIdYesStringThe Tool's id.
sourceCodeYesSourceCodeObject containing source code (_content and optional _id).
ctxNoCtxContext, such as namespaces and authentication token information.
optionsYesundefined
Returns

Promise<SourceCode> - A Promise resolving to the uploaded SourceCode.

Examples
//Upload source code as String
const sourceCode = { _content: "import { AbstractTool } from '@dtplatform/agent-core';\nimport * as PlatformAPI from '@dtplatform/platform-api';\nconst { IafItemSvc } = PlatformAPI;\nimport { z } from 'zod';\n\nconst toolSchema = z.object({\n name: z.string().optional().nullable().describe('Filter by asset name. Supports regex'),\n dtCategory: z.string().optional().nullable().describe('Filter by the dtCategory property. Supports regex'),\n dtType: z.string().optional().nullable().describe('Filter by dtType property. Supports regex'),\n _pageSize: z.string().optional().nullable().describe('Sets the number of results to return per Page in the response'),\n _offset: z.string().optional().nullable().describe('Sets the number of results to skip in the Page response. For example, set to `10` to skip the first 10 results.')\n});\n\nexport default class GetAssetsTool extends AbstractTool {\n name: string = 'GetAssetsTool';\n description: string = 'Helps to retrieve Assets based on the provided criteria.';\n requestContext: any = {};\n schema: any = toolSchema;\n\n constructor(...args: any[]) {\n super(...args);\n const [{ requestContext }] = args;\n this.requestContext = requestContext;\n }\n\n async _call(args: z.infer<typeof toolSchema>) {\n let criteria: any = { '$or': [] };\n let options: any = {};\n let response: any = {};\n\n if (args.name || args.dtCategory || args.dtType) {\n if (args.name) {\n criteria['$or'].push({\n 'Asset Name': {\n '$regex': this.toRegexString(args.name),\n '$options': 'i'\n }\n });\n }\n if (args.dtCategory) {\n criteria['$or'].push({\n 'properties.dtCategory.val': {\n '$regex': this.toRegexString(args.dtCategory),\n '$options': 'i'\n }\n });\n }\n if (args.dtType) {\n criteria['$or'].push({\n 'properties.dtType.val': {\n '$regex': this.toRegexString(args.dtType),\n '$options': 'i'\n }\n });\n }\n\n if (args._pageSize) {\n options['_pageSize'] = parseInt(args._pageSize, 10);\n }\n if (args._offset) {\n options['_offset'] = parseInt(args._offset, 10);\n }\n\n let colQuery = {\n query: {\n _userType: 'iaf_ext_asset_coll',\n _itemClass: 'NamedUserCollection'\n }\n };\n\n const colOptions = {\n project: { _userType: 1, _itemClass: 1 },\n sort: { _name: 1 },\n page: { _offset: 0, _pageSize: 1 }\n };\n\n const colResponse = await IafItemSvc.getNamedUserItems(\n colQuery,\n this.requestContext,\n colOptions\n );\n\n\n\n let assetCollection: any = null;\n if (colResponse && Array.isArray(colResponse._list) && colResponse._list.length > 0) {\n assetCollection = colResponse._list[0];\n if (assetCollection && assetCollection._id) {\n response = await IafItemSvc.getRelatedItems(\n assetCollection._id,\n {query: criteria},\n this.requestContext,\n options \n );\n }\n }\n }\n return response;\n }\n\n toRegexString(str) {\n const quoted = str.match(/^'(.*)'$/);\n if (quoted) {\n const escaped = quoted[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');\n return `.*(${escaped}).*`;\n }\n const terms = str\n .split(/\s+/)\n .map(term => term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));\n return `.*(${terms.join('|')}).*`;\n }\n}\n" };
await IafAISvc.uploadToolSourceCode('5202ae41-a2c4-1429-7126-17ab4dc80245', sourceCode, ctx);

//Upload source code as file
const sourceCode = {_file: fileStream}
await IafAISvc.uploadToolSourceCode('5202ae41-a2c4-1429-7126-17ab4dc80245', sourceCode, ctx);