Skip to content

Commit 6ace6f1

Browse files
authored
feat: ai tool token optimizations (#9)
Add token cost optimizations when used as an AI tool
1 parent 5c57aa7 commit 6ace6f1

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

nodes/ApifyContentCrawler/resources/executeActor.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { IExecuteFunctions, INodeExecutionData, NodeApiError } from 'n8n-workflow';
2-
import { apiRequest, getResults, pollRunStatus } from './genericFunctions';
2+
import { apiRequest, getResults, isUsedAsAiTool, pollRunStatus } from './genericFunctions';
33

44
export async function getDefaultBuild(this: IExecuteFunctions, actorId: string) {
55
const defaultBuildResp = await apiRequest.call(this, {
@@ -63,5 +63,10 @@ export async function executeActorRunFlow(
6363
const datasetId = run.data.defaultDatasetId;
6464
const lastRunData = await pollRunStatus.call(this, runId);
6565
const resultData = await getResults.call(this, datasetId);
66+
67+
if (isUsedAsAiTool(this.getNode().type)) {
68+
return { json: { ...resultData } };
69+
}
70+
6671
return { json: { ...lastRunData, ...resultData } };
6772
}

nodes/ApifyContentCrawler/resources/genericFunctions.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,11 @@ export async function apiRequestAllItems(
120120
return combinedData;
121121
}
122122

123+
export function isUsedAsAiTool(nodeType: string): boolean {
124+
const parts = nodeType.split('.');
125+
return parts[parts.length - 1] === 'apifyContentCrawlerTool';
126+
}
127+
123128
export async function pollRunStatus(
124129
this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions,
125130
runId: string,
@@ -147,10 +152,16 @@ export async function pollRunStatus(
147152
}
148153

149154
export async function getResults(this: IExecuteFunctions, datasetId: string): Promise<any> {
150-
const results = await apiRequest.call(this, {
155+
let results = await apiRequest.call(this, {
151156
method: 'GET',
152157
uri: `/v2/datasets/${datasetId}/items`,
153158
});
154159

160+
// If used as a tool from an AI Agent, only return markdown results
161+
// This reduces the token amount more than half
162+
if (isUsedAsAiTool(this.getNode().type)) {
163+
results = results.map((item: any) => ({ markdown: item.markdown }));
164+
}
165+
155166
return this.helpers.returnJsonArray(results);
156167
}

0 commit comments

Comments
 (0)