├── SGR_Example.png ├── eslint.config.mjs ├── .gitignore ├── nodes ├── SGR │ ├── core │ │ ├── index.ts │ │ ├── logger.ts │ │ ├── context.ts │ │ ├── commands.ts │ │ └── toolConverter.ts │ ├── agents │ │ ├── index.ts │ │ ├── BaseAgent.ts │ │ └── ToolCallingAgent.ts │ ├── tools │ │ ├── index.ts │ │ ├── generatePlan.ts │ │ ├── finalAnswer.ts │ │ ├── adaptPlan.ts │ │ ├── clarification.ts │ │ ├── reasoning.ts │ │ └── createReport.ts │ ├── SgrToolCalling.node.json │ ├── types │ │ ├── tools.ts │ │ ├── messages.ts │ │ └── index.ts │ ├── prompts │ │ └── index.ts │ ├── SGR.svg │ └── SgrToolCalling.node.ts ├── SGRTavilySearchTool │ ├── SgrTavilySearchTool.node.json │ ├── tavily.svg │ └── SgrTavilySearchTool.node.ts └── SGRCustomFinalAnswer │ ├── SgrCustomFinalAnswer.node.json │ └── SgrCustomFinalAnswer.node.ts ├── .eslintrc.js ├── .github └── workflows │ └── ci.yml ├── tsconfig.json ├── .npmignore ├── credentials ├── TavilyApi.credentials.ts └── SgrApi.credentials.ts ├── .prettierrc.js ├── Makefile ├── icons ├── github.svg └── github.dark.svg ├── package.json ├── COMMERCIAL_LICENSE.md ├── CHANGELOG.md ├── scripts └── obfuscate.js ├── README.md ├── SGR_Example.json └── LICENSE /SGR_Example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/HEAD/SGR_Example.png -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import { config } from '@n8n/node-cli/eslint'; 2 | 3 | export default config; 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | test 4 | .vscode/ 5 | custom_modules/ 6 | n8n-nodes-sgr-tool-calling-*.tgz -------------------------------------------------------------------------------- /nodes/SGR/core/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Export core components 3 | */ 4 | 5 | export { AgentContext } from './context'; 6 | -------------------------------------------------------------------------------- /nodes/SGR/agents/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Export all agents 3 | */ 4 | 5 | export { BaseAgent, AgentConfig } from './BaseAgent'; 6 | export { ToolCallingAgent } from './ToolCallingAgent'; 7 | -------------------------------------------------------------------------------- /nodes/SGR/tools/index.ts: -------------------------------------------------------------------------------- 1 | export { reasoningTool } from './reasoning'; 2 | export { finalAnswerTool } from './finalAnswer'; 3 | export { createReportTool, createReportToolWithContext } from './createReport'; 4 | export { clarificationTool } from './clarification'; 5 | export { generatePlanTool } from './generatePlan'; 6 | export { adaptPlanTool } from './adaptPlan'; 7 | -------------------------------------------------------------------------------- /nodes/SGRTavilySearchTool/SgrTavilySearchTool.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "node": "n8n-nodes-sgr-tool-calling.sgrTavilySearchTool", 3 | "nodeVersion": "1.0", 4 | "codexVersion": "1.0", 5 | "categories": ["AI"], 6 | "subcategories": { 7 | "AI": ["Tools", "Agents"] 8 | }, 9 | "resources": { 10 | "primaryDocumentation": [ 11 | { 12 | "url": "https://tavily.com/" 13 | } 14 | ] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /nodes/SGR/SgrToolCalling.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "node": "n8n-nodes-sgr-tool-calling.sgrToolCalling", 3 | "nodeVersion": "1.0", 4 | "codexVersion": "1.0", 5 | "categories": ["AI"], 6 | "subcategories": { 7 | "AI": ["Agents", "Root Nodes"] 8 | }, 9 | "resources": { 10 | "primaryDocumentation": [ 11 | { 12 | "url": "https://github.com/MiXaiLL76/sgr_tool_calling" 13 | } 14 | ] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /nodes/SGRCustomFinalAnswer/SgrCustomFinalAnswer.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "node": "n8n-nodes-sgr-tool-calling.sgrCustomFinalAnswer", 3 | "nodeVersion": "1.0", 4 | "codexVersion": "1.0", 5 | "categories": ["AI"], 6 | "subcategories": { 7 | "AI": ["Tools", "Agents"] 8 | }, 9 | "resources": { 10 | "primaryDocumentation": [ 11 | { 12 | "url": "https://github.com/MiXaiLL76/sgr_tool_calling" 13 | } 14 | ] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parser: '@typescript-eslint/parser', 4 | parserOptions: { 5 | ecmaVersion: 2020, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint'], 9 | extends: [ 10 | 'eslint:recommended', 11 | 'plugin:@typescript-eslint/recommended', 12 | ], 13 | rules: { 14 | '@typescript-eslint/no-explicit-any': 'off', 15 | '@typescript-eslint/no-unused-vars': 'off', 16 | '@typescript-eslint/ban-ts-comment': 'off', 17 | }, 18 | }; 19 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - main 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Use Node.js 17 | uses: actions/setup-node@v4 18 | with: 19 | node-version: '22' 20 | 21 | - name: Install dependencies 22 | run: 'npm ci' 23 | 24 | - name: Run lint 25 | run: 'npm run lint' 26 | 27 | - name: Run build 28 | run: 'npm run build' 29 | -------------------------------------------------------------------------------- /nodes/SGR/types/tools.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Tool types for agent tool calling 3 | */ 4 | 5 | export interface ToolParameter { 6 | type: string; 7 | description?: string; 8 | properties?: Record; 9 | required?: string[]; 10 | } 11 | 12 | export interface ToolFunction { 13 | name: string; 14 | description: string; 15 | parameters: ToolParameter; 16 | } 17 | 18 | export interface Tool { 19 | type: 'function'; 20 | function: ToolFunction; 21 | } 22 | 23 | /** 24 | * Connected n8n AI Tool 25 | */ 26 | export interface ConnectedTool { 27 | name: string; 28 | description: string; 29 | schema?: ToolParameter; 30 | call: (args: Record) => Promise; 31 | } 32 | -------------------------------------------------------------------------------- /nodes/SGR/types/messages.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Message types for agent conversation 3 | */ 4 | 5 | // Support both OpenAI format and n8n format 6 | export interface ToolCall { 7 | id: string; 8 | type?: 'function' | 'tool_call'; 9 | // OpenAI format 10 | function?: { 11 | name: string; 12 | arguments: string | Record; 13 | }; 14 | // n8n format 15 | name?: string; 16 | args?: Record; 17 | } 18 | 19 | export interface Message { 20 | role: 'system' | 'user' | 'assistant' | 'tool'; 21 | content: string | null; 22 | tool_calls?: ToolCall[]; 23 | tool_call_id?: string; 24 | name?: string; 25 | } 26 | 27 | export interface AIModelResponse { 28 | content?: string | null; 29 | tool_calls?: ToolCall[]; 30 | } 31 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "module": "commonjs", 5 | "moduleResolution": "node", 6 | "target": "es2019", 7 | "lib": ["es2019", "es2020", "es2022.error"], 8 | "removeComments": true, 9 | "useUnknownInCatchVariables": false, 10 | "forceConsistentCasingInFileNames": true, 11 | "noImplicitAny": true, 12 | "noImplicitReturns": true, 13 | "noUnusedLocals": true, 14 | "strictNullChecks": true, 15 | "preserveConstEnums": true, 16 | "esModuleInterop": true, 17 | "resolveJsonModule": true, 18 | "incremental": true, 19 | "declaration": true, 20 | "sourceMap": false, 21 | "skipLibCheck": true, 22 | "outDir": "./dist/" 23 | }, 24 | "include": ["credentials/**/*", "nodes/**/*", "nodes/**/*.json", "package.json"] 25 | } 26 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Source files - only publish dist/ 2 | nodes/**/*.ts 3 | credentials/**/*.ts 4 | !dist/** 5 | 6 | # Development files 7 | *.log 8 | *.lock 9 | .DS_Store 10 | .vscode/ 11 | .idea/ 12 | *.swp 13 | *.swo 14 | *~ 15 | 16 | # Testing 17 | coverage/ 18 | .nyc_output/ 19 | test/ 20 | tests/ 21 | **/*.spec.ts 22 | **/*.test.ts 23 | 24 | # Documentation (optional - remove if you want to include) 25 | ARCHITECTURE.md 26 | README_DEV.md 27 | REFACTORING_SUMMARY.md 28 | docs/ 29 | 30 | # Build artifacts 31 | tsconfig.tsbuildinfo 32 | *.tgz 33 | 34 | # Environment 35 | .env 36 | .env.* 37 | 38 | # Git 39 | .git/ 40 | .gitignore 41 | .gitattributes 42 | 43 | # CI/CD 44 | .github/ 45 | .gitlab-ci.yml 46 | .travis.yml 47 | 48 | # Package managers 49 | node_modules/ 50 | npm-debug.log* 51 | yarn-debug.log* 52 | yarn-error.log* 53 | pnpm-debug.log* 54 | 55 | # Makefile and development 56 | Makefile 57 | -------------------------------------------------------------------------------- /credentials/TavilyApi.credentials.ts: -------------------------------------------------------------------------------- 1 | import { 2 | IAuthenticateGeneric, 3 | ICredentialTestRequest, 4 | ICredentialType, 5 | INodeProperties, 6 | } from 'n8n-workflow'; 7 | 8 | export class TavilyApi implements ICredentialType { 9 | name = 'tavilyApi'; 10 | displayName = 'Tavily API'; 11 | documentationUrl = 'https://tavily.com/'; 12 | icon = 'file:../nodes/SGRTavilySearchTool/tavily.svg' as const; 13 | properties: INodeProperties[] = [ 14 | { 15 | displayName: 'API Key', 16 | name: 'apiKey', 17 | type: 'string', 18 | typeOptions: { password: true }, 19 | default: '', 20 | required: true, 21 | description: 'The API key for Tavily API. Get it from https://app.tavily.com/', 22 | }, 23 | ]; 24 | 25 | authenticate: IAuthenticateGeneric = { 26 | type: 'generic', 27 | properties: {}, 28 | }; 29 | 30 | test: ICredentialTestRequest = { 31 | request: { 32 | baseURL: 'https://api.tavily.com', 33 | url: '/search', 34 | method: 'POST', 35 | body: { 36 | api_key: '={{$credentials.apiKey}}', 37 | query: 'test', 38 | max_results: 1, 39 | }, 40 | }, 41 | }; 42 | } 43 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | /** 3 | * https://prettier.io/docs/en/options.html#semicolons 4 | */ 5 | semi: true, 6 | 7 | /** 8 | * https://prettier.io/docs/en/options.html#trailing-commas 9 | */ 10 | trailingComma: 'all', 11 | 12 | /** 13 | * https://prettier.io/docs/en/options.html#bracket-spacing 14 | */ 15 | bracketSpacing: true, 16 | 17 | /** 18 | * https://prettier.io/docs/en/options.html#tabs 19 | */ 20 | useTabs: true, 21 | 22 | /** 23 | * https://prettier.io/docs/en/options.html#tab-width 24 | */ 25 | tabWidth: 2, 26 | 27 | /** 28 | * https://prettier.io/docs/en/options.html#arrow-function-parentheses 29 | */ 30 | arrowParens: 'always', 31 | 32 | /** 33 | * https://prettier.io/docs/en/options.html#quotes 34 | */ 35 | singleQuote: true, 36 | 37 | /** 38 | * https://prettier.io/docs/en/options.html#quote-props 39 | */ 40 | quoteProps: 'as-needed', 41 | 42 | /** 43 | * https://prettier.io/docs/en/options.html#end-of-line 44 | */ 45 | endOfLine: 'lf', 46 | 47 | /** 48 | * https://prettier.io/docs/en/options.html#print-width 49 | */ 50 | printWidth: 100, 51 | }; 52 | -------------------------------------------------------------------------------- /nodes/SGR/types/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Export all types 3 | */ 4 | 5 | export * from './messages'; 6 | export * from './tools'; 7 | 8 | export enum AgentState { 9 | RESEARCHING = 'RESEARCHING', 10 | WAITING_FOR_CLARIFICATION = 'WAITING_FOR_CLARIFICATION', 11 | COMPLETED = 'COMPLETED', 12 | FAILED = 'FAILED', 13 | MAX_ITERATIONS_REACHED = 'MAX_ITERATIONS_REACHED', 14 | } 15 | 16 | export interface ExecutionLogEntry { 17 | iteration: number; 18 | timestamp?: string; 19 | type: 'tool_call' | 'tool_result' | 'reasoning'; 20 | tool?: string; 21 | arguments?: Record; 22 | result?: unknown; 23 | } 24 | 25 | /** 26 | * Data about a research source 27 | * Port from Python SourceData model 28 | */ 29 | export interface SourceData { 30 | number: number; 31 | title?: string; 32 | url: string; 33 | snippet?: string; 34 | full_content?: string; 35 | char_count?: number; 36 | } 37 | 38 | /** 39 | * Search result with query, answer, and sources 40 | * Port from Python SearchResult model 41 | */ 42 | export interface SearchResult { 43 | query: string; 44 | answer?: string; 45 | citations: SourceData[]; 46 | timestamp: string; 47 | } 48 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Default target 2 | .DEFAULT_GOAL := help 3 | 4 | # Colors for output 5 | CYAN := \033[0;36m 6 | GREEN := \033[0;32m 7 | YELLOW := \033[1;33m 8 | RED := \033[0;31m 9 | NC := \033[0m # No Color 10 | 11 | install: ## Install dependencies 12 | @echo "$(GREEN)Installing dependencies...$(NC)" 13 | npm install 14 | @echo "$(GREEN)✓ Dependencies installed$(NC)" 15 | 16 | build: ## Build the project 17 | @echo "$(GREEN)Building project...$(NC)" 18 | export N8N_CUSTOM_EXTENSIONS="~/sgr_tool_calling" 19 | npm run build 20 | npm link 21 | npm link n8n-nodes-sgr-tool-calling 22 | @echo "$(GREEN)✓ Build complete$(NC)" 23 | 24 | format: ## Format code with prettier 25 | @echo "$(GREEN)Formatting code...$(NC)" 26 | npx prettier --write "**/*.{ts,json,md}" 27 | @echo "$(GREEN)✓ Code formatted$(NC)" 28 | 29 | npm run lint 30 | 31 | clean: ## Clean build artifacts 32 | @echo "$(GREEN)Cleaning build artifacts...$(NC)" 33 | rm -rf dist/ 34 | rm -rf node_modules/.cache 35 | @echo "$(GREEN)✓ Clean complete$(NC)" 36 | 37 | prod: clean 38 | @echo "$(GREEN)Building prod project...$(NC)" 39 | npm run build:prod 40 | npm pack 41 | @echo "$(GREEN)✓ Build prod complete$(NC)" 42 | -------------------------------------------------------------------------------- /nodes/SGR/tools/generatePlan.ts: -------------------------------------------------------------------------------- 1 | export const generatePlanTool = { 2 | name: 'generate_plan_tool', 3 | description: `Generate research plan. 4 | 5 | Useful to split complex request into manageable steps.`, 6 | schema: { 7 | type: 'object', 8 | properties: { 9 | reasoning: { 10 | type: 'string', 11 | description: 'Justification for research approach', 12 | }, 13 | research_goal: { 14 | type: 'string', 15 | description: 'Primary research objective', 16 | }, 17 | planned_steps: { 18 | type: 'array', 19 | items: { type: 'string' }, 20 | description: 'List of 3-4 planned steps', 21 | minItems: 3, 22 | maxItems: 4, 23 | }, 24 | search_strategies: { 25 | type: 'array', 26 | items: { type: 'string' }, 27 | description: 'Information search strategies', 28 | minItems: 2, 29 | maxItems: 3, 30 | }, 31 | }, 32 | required: ['reasoning', 'research_goal', 'planned_steps', 'search_strategies'], 33 | }, 34 | call: async (args: Record) => { 35 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 36 | const { reasoning, ...output } = args; 37 | return JSON.stringify(output, null, 2); 38 | }, 39 | }; 40 | -------------------------------------------------------------------------------- /nodes/SGR/tools/finalAnswer.ts: -------------------------------------------------------------------------------- 1 | // https://github.com/vamplabAI/sgr-agent-core/blob/main/sgr_deep_research/core/tools/final_answer_tool.py 2 | 3 | export const finalAnswerTool = { 4 | name: 'final_answer_tool', 5 | description: `Finalize research task and complete agent execution after all steps are completed. 6 | 7 | Usage: Call after you complete research task`, 8 | schema: { 9 | type: 'object', 10 | properties: { 11 | reasoning: { 12 | type: 'string', 13 | description: 'Why task is now complete and how answer was verified', 14 | }, 15 | completed_steps: { 16 | type: 'array', 17 | items: { type: 'string' }, 18 | description: 'Summary of completed steps including verification', 19 | minItems: 1, 20 | maxItems: 5, 21 | }, 22 | answer: { 23 | type: 'string', 24 | description: 25 | 'Comprehensive final answer with EXACT factual details (dates, numbers, names)', 26 | }, 27 | status: { 28 | type: 'string', 29 | enum: ['COMPLETED', 'FAILED'], 30 | description: 'Task completion status', 31 | }, 32 | }, 33 | required: ['reasoning', 'completed_steps', 'answer', 'status'], 34 | }, 35 | call: async (args: Record) => { 36 | return JSON.stringify(args, null, 2); 37 | }, 38 | }; 39 | -------------------------------------------------------------------------------- /icons/github.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /icons/github.dark.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /nodes/SGR/tools/adaptPlan.ts: -------------------------------------------------------------------------------- 1 | // https://github.com/vamplabAI/sgr-agent-core/blob/main/sgr_deep_research/core/tools/adapt_plan_tool.py 2 | export const adaptPlanTool = { 3 | name: 'adapt_plan_tool', 4 | description: 'Adapt research plan based on new findings.', 5 | schema: { 6 | type: 'object', 7 | properties: { 8 | reasoning: { 9 | type: 'string', 10 | description: 'Why plan needs adaptation based on new data', 11 | }, 12 | original_goal: { 13 | type: 'string', 14 | description: 'Original research goal', 15 | }, 16 | new_goal: { 17 | type: 'string', 18 | description: 'Updated research goal', 19 | }, 20 | plan_changes: { 21 | type: 'array', 22 | items: { type: 'string' }, 23 | description: 'Specific changes made to plan', 24 | minItems: 1, 25 | maxItems: 3, 26 | }, 27 | next_steps: { 28 | type: 'array', 29 | items: { type: 'string' }, 30 | description: 'Updated remaining steps', 31 | minItems: 2, 32 | maxItems: 4, 33 | }, 34 | }, 35 | required: ['reasoning', 'original_goal', 'new_goal', 'plan_changes', 'next_steps'], 36 | }, 37 | call: async (args: Record) => { 38 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 39 | const { reasoning, ...output } = args; 40 | return JSON.stringify(output, null, 2); 41 | }, 42 | }; 43 | -------------------------------------------------------------------------------- /credentials/SgrApi.credentials.ts: -------------------------------------------------------------------------------- 1 | import { 2 | IAuthenticateGeneric, 3 | ICredentialTestRequest, 4 | ICredentialType, 5 | INodeProperties, 6 | } from 'n8n-workflow'; 7 | 8 | export class SgrApi implements ICredentialType { 9 | name = 'sgrApi'; 10 | displayName = 'SGR OpenAI API'; 11 | documentationUrl = 'https://platform.openai.com/docs/api-reference'; 12 | icon = 'file:../nodes/SGR/SGR.svg' as const; 13 | properties: INodeProperties[] = [ 14 | { 15 | displayName: 'API Key', 16 | name: 'apiKey', 17 | type: 'string', 18 | typeOptions: { password: true }, 19 | default: '', 20 | required: true, 21 | }, 22 | { 23 | displayName: 'Base URL', 24 | name: 'baseUrl', 25 | type: 'string', 26 | default: 'https://api.openai.com/v1', 27 | description: 'The base URL for OpenAI API (or compatible endpoint)', 28 | }, 29 | { 30 | displayName: 'Model', 31 | name: 'model', 32 | type: 'string', 33 | default: 'gpt-4-turbo-preview', 34 | description: 'The model to use for chat completions', 35 | }, 36 | ]; 37 | 38 | authenticate: IAuthenticateGeneric = { 39 | type: 'generic', 40 | properties: { 41 | headers: { 42 | Authorization: '=Bearer {{$credentials.apiKey}}', 43 | }, 44 | }, 45 | }; 46 | 47 | test: ICredentialTestRequest = { 48 | request: { 49 | baseURL: '={{$credentials.baseUrl}}', 50 | url: '/models', 51 | }, 52 | }; 53 | } 54 | -------------------------------------------------------------------------------- /nodes/SGR/tools/clarification.ts: -------------------------------------------------------------------------------- 1 | // https://github.com/vamplabAI/sgr-agent-core/blob/main/sgr_deep_research/core/tools/clarification_tool.py 2 | export const clarificationTool = { 3 | name: 'clarification_tool', 4 | description: `Ask clarifying questions when facing ambiguous request. 5 | 6 | Keep all fields concise - brief reasoning, short terms, and clear questions.`, 7 | schema: { 8 | type: 'object', 9 | properties: { 10 | reasoning: { 11 | type: 'string', 12 | description: 'Why clarification is needed (1-2 sentences MAX)', 13 | maxLength: 200, 14 | }, 15 | unclear_terms: { 16 | type: 'array', 17 | items: { type: 'string' }, 18 | description: 'List of unclear terms (brief, 1-3 words each)', 19 | minItems: 1, 20 | maxItems: 3, 21 | }, 22 | assumptions: { 23 | type: 'array', 24 | items: { type: 'string' }, 25 | description: 'Possible interpretations (short, 1 sentence each)', 26 | minItems: 2, 27 | maxItems: 3, 28 | }, 29 | questions: { 30 | type: 'array', 31 | items: { type: 'string' }, 32 | description: '3 specific clarifying questions (short and direct)', 33 | minItems: 3, 34 | maxItems: 3, 35 | }, 36 | }, 37 | required: ['reasoning', 'unclear_terms', 'assumptions', 'questions'], 38 | }, 39 | call: async (args: Record) => { 40 | return (args.questions as string[]).join('\n'); 41 | }, 42 | }; 43 | -------------------------------------------------------------------------------- /nodes/SGR/core/logger.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Logger wrapper with configurable log levels 3 | */ 4 | import type { Logger, LogMetadata } from 'n8n-workflow'; 5 | 6 | export type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'debug'; 7 | 8 | const LOG_LEVELS: Record = { 9 | none: 0, 10 | error: 1, 11 | warn: 2, 12 | info: 3, 13 | debug: 4, 14 | }; 15 | 16 | export class ConfigurableLogger { 17 | private logger: Logger; 18 | private level: LogLevel; 19 | 20 | constructor(logger: Logger, level: LogLevel = 'error') { 21 | this.logger = logger; 22 | this.level = level; 23 | } 24 | 25 | setLevel(level: LogLevel): void { 26 | this.level = level; 27 | } 28 | 29 | getLevel(): LogLevel { 30 | return this.level; 31 | } 32 | 33 | private shouldLog(messageLevel: LogLevel): boolean { 34 | return LOG_LEVELS[messageLevel] <= LOG_LEVELS[this.level]; 35 | } 36 | 37 | debug(message: string, metadata?: LogMetadata): void { 38 | if (this.shouldLog('debug')) { 39 | this.logger.debug(message, metadata); 40 | } 41 | } 42 | 43 | info(message: string, metadata?: LogMetadata): void { 44 | if (this.shouldLog('info')) { 45 | this.logger.info(message, metadata); 46 | } 47 | } 48 | 49 | warn(message: string, metadata?: LogMetadata): void { 50 | if (this.shouldLog('warn')) { 51 | this.logger.warn(message, metadata); 52 | } 53 | } 54 | 55 | error(message: string, metadata?: LogMetadata): void { 56 | if (this.shouldLog('error')) { 57 | this.logger.error(message, metadata); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /nodes/SGRTavilySearchTool/tavily.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "n8n-nodes-sgr-tool-calling", 3 | "version": "0.1.11", 4 | "description": "n8n node for SGR AI Agent with Tool Calling capabilities and Tavily Search integration", 5 | "license": "MIT", 6 | "homepage": "", 7 | "keywords": [ 8 | "n8n-community-node-package", 9 | "sgr-tool-calling", 10 | "tool-calling", 11 | "sgr" 12 | ], 13 | "author": { 14 | "name": "MiXaiLL76", 15 | "email": "mike.milos@yandex.ru" 16 | }, 17 | "repository": { 18 | "type": "git", 19 | "url": "https://github.com/MiXaiLL76/sgr_tool_calling.git" 20 | }, 21 | "scripts": { 22 | "build": "n8n-node build", 23 | "build:watch": "tsc --watch", 24 | "build:prod": "n8n-node build && node scripts/obfuscate.js", 25 | "dev": "n8n-node dev", 26 | "lint": "n8n-node lint", 27 | "lint:fix": "n8n-node lint --fix", 28 | "release": "npm run build:prod && n8n-node release", 29 | "prepublishOnly": "npm run build:prod && n8n-node prerelease" 30 | }, 31 | "files": [ 32 | "dist" 33 | ], 34 | "n8n": { 35 | "n8nNodesApiVersion": 1, 36 | "strict": true, 37 | "credentials": [ 38 | "dist/credentials/SgrApi.credentials.js", 39 | "dist/credentials/TavilyApi.credentials.js" 40 | ], 41 | "nodes": [ 42 | "dist/nodes/SGR/SgrToolCalling.node.js", 43 | "dist/nodes/SGRTavilySearchTool/SgrTavilySearchTool.node.js", 44 | "dist/nodes/SGRCustomFinalAnswer/SgrCustomFinalAnswer.node.js" 45 | ] 46 | }, 47 | "devDependencies": { 48 | "@n8n/node-cli": "*", 49 | "eslint": "9.32.0", 50 | "javascript-obfuscator": "^4.1.1", 51 | "prettier": "3.6.2", 52 | "release-it": "^19.0.4", 53 | "typescript": "5.9.2" 54 | }, 55 | "peerDependencies": { 56 | "n8n-workflow": "*" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /nodes/SGR/tools/reasoning.ts: -------------------------------------------------------------------------------- 1 | // https://github.com/vamplabAI/sgr-agent-core/blob/main/sgr_deep_research/core/tools/reasoning_tool.py 2 | 3 | export const reasoningTool = { 4 | name: 'reasoning_tool', 5 | description: `Agent core logic, determines next reasoning step with adaptive planning by schema-guided-reasoning capabilities. Keep all text fields concise and focused. 6 | 7 | Usage: Required tool use this tool before execution tool, and after execution`, 8 | schema: { 9 | type: 'object', 10 | properties: { 11 | reasoning_steps: { 12 | type: 'array', 13 | items: { type: 'string' }, 14 | description: 'Step-by-step reasoning (brief, 1 sentence each)', 15 | minItems: 2, 16 | maxItems: 3, 17 | }, 18 | current_situation: { 19 | type: 'string', 20 | description: 'Current research situation (2-3 sentences MAX)', 21 | maxLength: 300, 22 | }, 23 | plan_status: { 24 | type: 'string', 25 | description: 'Status of current plan (1 sentence)', 26 | maxLength: 150, 27 | }, 28 | enough_data: { 29 | type: 'boolean', 30 | description: 'Sufficient data collected for comprehensive report?', 31 | default: false, 32 | }, 33 | remaining_steps: { 34 | type: 'array', 35 | items: { type: 'string' }, 36 | description: '1-3 remaining steps (brief, action-oriented)', 37 | minItems: 1, 38 | maxItems: 3, 39 | }, 40 | task_completed: { 41 | type: 'boolean', 42 | description: 'Is the research task finished?', 43 | }, 44 | }, 45 | required: [ 46 | 'reasoning_steps', 47 | 'current_situation', 48 | 'plan_status', 49 | 'remaining_steps', 50 | 'task_completed', 51 | ], 52 | }, 53 | call: async (args: Record) => { 54 | return JSON.stringify(args, null, 2); 55 | }, 56 | }; 57 | -------------------------------------------------------------------------------- /nodes/SGR/core/context.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Agent execution context 3 | * Similar to ResearchContext from Python version 4 | */ 5 | 6 | import { AgentState, type ExecutionLogEntry, type SourceData, type SearchResult } from '../types'; 7 | 8 | export class AgentContext { 9 | iteration: number = 0; 10 | state: AgentState = AgentState.RESEARCHING; 11 | clarifications_used: number = 0; 12 | searches_used: number = 0; 13 | executionLog: ExecutionLogEntry[] = []; 14 | 15 | // Research data from Python ResearchContext 16 | sources: Map = new Map(); 17 | searches: SearchResult[] = []; 18 | 19 | constructor() { 20 | this.reset(); 21 | } 22 | 23 | reset(): void { 24 | this.iteration = 0; 25 | this.state = AgentState.RESEARCHING; 26 | this.clarifications_used = 0; 27 | this.searches_used = 0; 28 | this.executionLog = []; 29 | this.sources = new Map(); 30 | this.searches = []; 31 | } 32 | 33 | logToolCall(toolName: string, args: Record): void { 34 | this.executionLog.push({ 35 | iteration: this.iteration, 36 | timestamp: new Date().toISOString(), 37 | type: 'tool_call', 38 | tool: toolName, 39 | arguments: args, 40 | }); 41 | } 42 | 43 | logToolResult(toolName: string, result: unknown): void { 44 | this.executionLog.push({ 45 | iteration: this.iteration, 46 | timestamp: new Date().toISOString(), 47 | type: 'tool_result', 48 | tool: toolName, 49 | result, 50 | }); 51 | } 52 | 53 | incrementSearches(): void { 54 | this.searches_used += 1; 55 | } 56 | 57 | incrementClarifications(): void { 58 | this.clarifications_used += 1; 59 | } 60 | 61 | complete(): void { 62 | this.state = AgentState.COMPLETED; 63 | } 64 | 65 | fail(): void { 66 | this.state = AgentState.FAILED; 67 | } 68 | 69 | maxIterationsReached(): void { 70 | this.state = AgentState.MAX_ITERATIONS_REACHED; 71 | } 72 | 73 | isFinished(): boolean { 74 | return ( 75 | this.state === AgentState.COMPLETED || 76 | this.state === AgentState.FAILED || 77 | this.state === AgentState.MAX_ITERATIONS_REACHED 78 | ); 79 | } 80 | 81 | /** 82 | * Add a source to the context 83 | */ 84 | addSource(url: string, sourceData: SourceData): void { 85 | this.sources.set(url, sourceData); 86 | } 87 | 88 | /** 89 | * Add a search result to the context 90 | */ 91 | addSearch(searchResult: SearchResult): void { 92 | this.searches.push(searchResult); 93 | } 94 | 95 | /** 96 | * Get sources as formatted string for report 97 | */ 98 | getSourcesAsString(): string { 99 | const sourcesArray = Array.from(this.sources.values()); 100 | if (sourcesArray.length === 0) { 101 | return ''; 102 | } 103 | 104 | return sourcesArray 105 | .map((source) => `[${source.number}] ${source.title || 'Untitled'} - ${source.url}`) 106 | .join('\n'); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /COMMERCIAL_LICENSE.md: -------------------------------------------------------------------------------- 1 | # Commercial License for n8n-nodes-sgr-tool-calling 2 | 3 | ## Overview 4 | 5 | This software is dual-licensed: 6 | 7 | - **Open Source License:** AGPL-3.0 (free for compliant use cases) 8 | - **Commercial License:** Available for proprietary/closed-source use 9 | 10 | ## When Do You Need a Commercial License? 11 | 12 | You need a commercial license if you want to: 13 | 14 | ### ❌ Use Cases Requiring Commercial License 15 | 16 | 1. **Proprietary Integration** 17 | - Integrate into closed-source software 18 | - Modify without releasing source code 19 | - Bundle with proprietary products 20 | 21 | 2. **Managed Services** 22 | - Provide as SaaS without open-sourcing 23 | - Offer hosted service to customers 24 | - Build commercial API service 25 | 26 | 3. **Internal Corporate Use** 27 | - Use in enterprise without GPL compliance burden 28 | - Avoid AGPL requirements for corporate infrastructure 29 | 30 | ### ✅ Free Use Cases (AGPL-3.0) 31 | 32 | No commercial license needed for: 33 | 34 | - Personal projects 35 | - Educational/research purposes 36 | - Open-source projects (AGPL-3.0 compliant) 37 | - Non-commercial use 38 | 39 | **Important:** If you deploy as a network service under AGPL-3.0, you **must** provide source code to users. 40 | 41 | ## AGPL-3.0 Requirements 42 | 43 | Under AGPL-3.0, if you: 44 | 45 | - Modify this software 46 | - Run it as a network service (web app, API, SaaS, etc.) 47 | 48 | Then you **must**: 49 | 50 | - Make your modified source code available to users 51 | - License your modifications under AGPL-3.0 52 | - Include copyright and license notices 53 | 54 | ## Commercial License Benefits 55 | 56 | A commercial license allows you to: 57 | 58 | - ✅ Keep modifications private 59 | - ✅ Integrate into proprietary software 60 | - ✅ Provide as managed service without open-sourcing 61 | - ✅ Avoid AGPL compliance requirements 62 | - ✅ Receive priority support (optional) 63 | 64 | ## Pricing & Contact 65 | 66 | **For commercial licensing inquiries:** 67 | 68 | 📧 Email: [mike.milos@yandex.ru](mailto:mike.milos@yandex.ru) 69 | 70 | Please include: 71 | 72 | - Company name and size 73 | - Intended use case 74 | - Deployment scope (users, instances, etc.) 75 | 76 | We offer flexible pricing based on: 77 | 78 | - Company size (startup, SMB, enterprise) 79 | - Use case (internal tools, SaaS, embedded) 80 | - Number of deployments 81 | - Support requirements 82 | 83 | ## FAQ 84 | 85 | **Q: Can I try the software before buying a commercial license?** 86 | A: Yes! Use it under AGPL-3.0 for evaluation. Contact us when ready for commercial deployment. 87 | 88 | **Q: What if I'm unsure which license I need?** 89 | A: Contact us! We'll help determine the best option for your use case. 90 | 91 | **Q: Do you offer source code escrow?** 92 | A: Yes, available for enterprise customers. 93 | 94 | **Q: Is there a trial period for commercial licenses?** 95 | A: Contact us to discuss trial arrangements. 96 | 97 | --- 98 | 99 | **Copyright (C) 2025 MiXaiLL76** 100 | 101 | For questions, contact: [mike.milos@yandex.ru](mailto:mike.milos@yandex.ru) 102 | -------------------------------------------------------------------------------- /nodes/SGR/prompts/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Default prompt templates for SGR Tool Calling Agent 3 | */ 4 | 5 | export const DEFAULT_SYSTEM_PROMPT = ` 6 | You are an expert researcher with adaptive planning and schema-guided-reasoning capabilities. You get the research task and you neeed to do research and genrete answer 7 | 8 | 9 | 10 | PAY ATTENTION TO THE DATE INSIDE THE USER REQUEST 11 | DATE FORMAT: YYYY-MM-DD HH:MM:SS (ISO 8601) 12 | IMPORTANT: The date above is in YYYY-MM-DD format (Year-Month-Day). For example, 2025-10-03 means October 3rd, 2025, NOT March 10th. 13 | 14 | 15 | : Detect the language from user request and use this LANGUAGE for all responses, searches, and result finalanswertool 16 | LANGUAGE ADAPTATION: Always respond and create reports in the SAME LANGUAGE as the user's request. 17 | If user writes in Russian - respond in Russian, if in English - respond in English. 18 | : 19 | 20 | : 21 | 1. Memorize plan you generated in first step and follow the task inside your plan. 22 | 1. Adapt plan when new data contradicts initial assumptions 23 | 2. Search queries in SAME LANGUAGE as user request 24 | 3. Final Answer ENTIRELY in SAME LANGUAGE as user request 25 | 26 | 27 | 28 | ADAPTIVITY: Actively change plan when discovering new data. 29 | ANALYSIS EXTRACT DATA: Always analyze data that you took in extractpagecontenttool 30 | 31 | 32 | 33 | CRITICAL FOR FACTUAL ACCURACY: 34 | When answering questions about specific dates, numbers, versions, or names: 35 | 1. EXACT VALUES: Extract the EXACT value from sources (day, month, year for dates; precise numbers for quantities) 36 | 2. VERIFY YEAR: If question mentions a specific year (e.g., "in 2022"), verify extracted content is about that SAME year 37 | 3. CROSS-VERIFICATION: When sources provide contradictory information, prefer: 38 | - Official sources and primary documentation over secondary sources 39 | - Search result snippets that DIRECTLY answer the question over extracted page content 40 | - Multiple independent sources confirming the same fact 41 | 4. DATE PRECISION: Pay special attention to exact dates - day matters (October 21 ≠ October 22) 42 | 5. NUMBER PRECISION: For numbers/versions, exact match required (6.88b ≠ 6.88c, Episode 31 ≠ Episode 32) 43 | 6. SNIPPET PRIORITY: If search snippet clearly states the answer, trust it unless extract proves it wrong 44 | 7. TEMPORAL VALIDATION: When extracting page content, check if the page shows data for correct time period 45 | 46 | 47 | : 48 | {available_tools} 49 | `; 50 | 51 | export const DEFAULT_INITIAL_USER_REQUEST = `Current Date: {current_date} (Year-Month-Day ISO format: YYYY-MM-DD HH:MM:SS) 52 | ORIGINAL USER REQUEST: 53 | 54 | {task}`; 55 | 56 | export const DEFAULT_CLARIFICATION_RESPONSE = `Current Date: {current_date} (Year-Month-Day ISO format: YYYY-MM-DD HH:MM:SS) 57 | 58 | CLARIFICATIONS: 59 | 60 | {clarifications}`; 61 | 62 | /** 63 | * Format a template string with variables 64 | */ 65 | export function formatPrompt(template: string, variables: Record): string { 66 | let result = template; 67 | for (const [key, value] of Object.entries(variables)) { 68 | result = result.replace(new RegExp(`\\{${key}\\}`, 'g'), value); 69 | } 70 | return result; 71 | } 72 | 73 | /** 74 | * Get current date in ISO format 75 | */ 76 | export function getCurrentDate(): string { 77 | return new Date().toISOString().replace('T', ' ').substring(0, 19); 78 | } 79 | -------------------------------------------------------------------------------- /nodes/SGR/tools/createReport.ts: -------------------------------------------------------------------------------- 1 | // https://github.com/vamplabAI/sgr-agent-core/blob/main/sgr_deep_research/core/tools/create_report_tool.py 2 | import type { AgentContext } from '../core/context'; 3 | import type { Logger } from 'n8n-workflow'; 4 | 5 | export const createReportTool = { 6 | name: 'create_report_tool', 7 | description: `Create comprehensive detailed report with citations as a final step of research. 8 | 9 | CRITICAL: Every factual claim in content MUST have inline citations [1], [2], [3]. 10 | Citations must be integrated directly into sentences, not just listed at the end.`, 11 | schema: { 12 | type: 'object', 13 | properties: { 14 | reasoning: { 15 | type: 'string', 16 | description: 'Why ready to create report now', 17 | }, 18 | title: { 19 | type: 'string', 20 | description: 'Report title', 21 | }, 22 | user_request_language_reference: { 23 | type: 'string', 24 | description: 'Copy of original user request to ensure language consistency', 25 | }, 26 | content: { 27 | type: 'string', 28 | description: 29 | 'Write comprehensive research report. Use the SAME LANGUAGE as user_request_language_reference. MANDATORY: Include inline citations [1], [2], [3] after EVERY factual claim.', 30 | }, 31 | confidence: { 32 | type: 'string', 33 | enum: ['high', 'medium', 'low'], 34 | description: 'Confidence in findings', 35 | }, 36 | }, 37 | required: ['reasoning', 'title', 'user_request_language_reference', 'content', 'confidence'], 38 | }, 39 | call: async (args: Record) => { 40 | return JSON.stringify( 41 | { 42 | title: args.title, 43 | content: args.content, 44 | confidence: args.confidence, 45 | word_count: (args.content as string).split(/\s+/).length, 46 | timestamp: new Date().toISOString(), 47 | }, 48 | null, 49 | 2, 50 | ); 51 | }, 52 | }; 53 | 54 | /** 55 | * Create contextual version of createReportTool with access to AgentContext 56 | * This is used by ToolCallingAgent to provide full functionality from Python version 57 | */ 58 | export function createReportToolWithContext(context: AgentContext, logger?: Logger) { 59 | return { 60 | ...createReportTool, 61 | call: async (args: Record) => { 62 | const title = args.title as string; 63 | const content = args.content as string; 64 | const confidence = args.confidence as string; 65 | const reasoning = args.reasoning as string; 66 | const userRequestLanguageReference = args.user_request_language_reference as string; 67 | 68 | // Build full report content similar to Python version 69 | let fullContent = `# ${title}\n\n`; 70 | fullContent += `*Created: ${new Date().toISOString().replace('T', ' ').substring(0, 19)}*\n\n`; 71 | fullContent += content + '\n\n'; 72 | 73 | // Add sources reference section if sources exist 74 | const sourcesArray = Array.from(context.sources.values()); 75 | if (sourcesArray.length > 0) { 76 | fullContent += '---\n\n'; 77 | fullContent += '## Источники / Sources\n\n'; 78 | fullContent += context.getSourcesAsString(); 79 | } 80 | 81 | const wordCount = content.split(/\s+/).length; 82 | const sourcesCount = sourcesArray.length; 83 | 84 | // Detailed logging like Python version 85 | if (logger) { 86 | logger.info( 87 | `📝 CREATE REPORT FULL DEBUG:\n` + 88 | ` 🌍 Language Reference: '${userRequestLanguageReference}'\n` + 89 | ` 📊 Title: '${title}'\n` + 90 | ` 🔍 Reasoning: '${reasoning.substring(0, 150)}...'\n` + 91 | ` 📈 Confidence: ${confidence}\n` + 92 | ` 📄 Content Preview: '${content.substring(0, 200)}...'\n` + 93 | ` 📊 Words: ${wordCount}, Sources: ${sourcesCount}\n`, 94 | ); 95 | } 96 | 97 | const report = { 98 | title, 99 | content, 100 | full_content: fullContent, 101 | confidence, 102 | sources_count: sourcesCount, 103 | word_count: wordCount, 104 | timestamp: new Date().toISOString(), 105 | }; 106 | 107 | return JSON.stringify(report, null, 2); 108 | }, 109 | }; 110 | } 111 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ### Changelog 2 | 3 | All notable changes to this project will be documented in this file. Dates are displayed in UTC. 4 | 5 | Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). 6 | 7 | #### [0.1.11](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/compare/0.1.10...0.1.11) 8 | 9 | - include default schema [`8fc2c9c`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/8fc2c9c9b2e89e4ea0ab5df84f28ea4453ef829e) 10 | 11 | #### [0.1.10](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/compare/0.1.8...0.1.10) 12 | 13 | > 5 December 2025 14 | 15 | - Release 0.1.9 [`c0b9e92`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/c0b9e92200c8fa6cda8ee7643cff30a352250cdf) 16 | - Release 0.1.10 [`c04dfbf`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/c04dfbf5805c23a1356775a91f1fdafeaf8b63a1) 17 | - restore SgrCustomFinalAnswer [`e20f290`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/e20f290cfe5e6484b5a35d9b2712cf3bffd6cd5d) 18 | 19 | #### [0.1.8](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/compare/0.1.7...0.1.8) 20 | 21 | > 5 December 2025 22 | 23 | - Release 0.1.8 [`e0ac904`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/e0ac904242edfd7507e9f2981cb0928109d5031d) 24 | - fix file names [`8b0f965`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/8b0f965cdc9cd5f79f23e79791a6b6dcd6a38d12) 25 | 26 | #### [0.1.7](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/compare/0.1.6...0.1.7) 27 | 28 | > 5 December 2025 29 | 30 | - Release 0.1.7 [`c2b3619`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/c2b361916c775573f343e24a23676341e94ab42a) 31 | - remove SgrCustomFinalAnswerTool [`31213ef`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/31213ef853b44dc230646c782070175db5ca6fbd) 32 | 33 | #### [0.1.6](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/compare/0.1.5...0.1.6) 34 | 35 | > 5 December 2025 36 | 37 | - Release 0.1.6 [`eae5ecf`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/eae5ecf2f27288f682e2523cb1d374eb02cd4beb) 38 | - fix all lint errors with name [`5e6165d`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/5e6165d6747cb8e120cdb67cdcffbfaf799b96d3) 39 | - fix tool name [`6d02410`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/6d024107943393bf629e063ee4ff9a9df66d0555) 40 | 41 | #### [0.1.5](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/compare/0.1.4...0.1.5) 42 | 43 | > 5 December 2025 44 | 45 | - fix clarification_tool [`cfe4d06`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/cfe4d062f6bf45d8f239ff87851d278c3384088c) 46 | - add sgrCustomFinalAnswerTool [`25f5222`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/25f522214f4154421b3297d95ab820621a6bc354) 47 | - Release 0.1.5 [`5f20144`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/5f20144e0b86e18a2f9171dc4bd9074c1a2c6c99) 48 | 49 | #### [0.1.4](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/compare/0.1.3...0.1.4) 50 | 51 | > 26 October 2025 52 | 53 | - return dist [`75d3894`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/75d389415bf599f8e90068183f0a9dfb2bb7506d) 54 | - Release 0.1.4 [`aaa007e`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/aaa007e578c878b2599a9fe7af851b00a968b80a) 55 | 56 | #### [0.1.3](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/compare/0.1.2...0.1.3) 57 | 58 | > 26 October 2025 59 | 60 | - Release 0.1.3 [`c7662be`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/c7662be2dfc04d5d98bebd84e12609b225f582d4) 61 | - fix nodes classes [`14a35a3`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/14a35a36e18a54519718831218266c62237269c3) 62 | - fix [`5da20c5`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/5da20c595a76e9d082c66b825cff8fd37bd5bef6) 63 | 64 | #### [0.1.2](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/compare/0.1.1...0.1.2) 65 | 66 | > 24 October 2025 67 | 68 | - Fix console logging [`#2`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/pull/2) 69 | - prepare for work [`#1`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/pull/1) 70 | - fix logging [`b2d5f2e`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/b2d5f2e6ff7bf5fdf639a72f9ca2cb1114d29b2f) 71 | - fix LICENSE [`55b155f`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/55b155fcb30642052614376f1754af92fec0d407) 72 | - update core [`3642687`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/36426874830cc67e46215e90dc641aa4bc2c0fb1) 73 | 74 | #### 0.1.1 75 | 76 | > 22 October 2025 77 | 78 | - init [`f9eb313`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/f9eb313471a556426d3ded2949507f55cb80814d) 79 | - fix lint [`5b5230d`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/5b5230d443a6bd1f3c79f99b1e62cdff3a16db67) 80 | - Release 0.1.1 [`bee7b18`](https://github.com/MiXaiLL76/n8n-nodes-sgr-tool-calling/commit/bee7b18ca71d0458272613b802fa9451e80dc017) 81 | -------------------------------------------------------------------------------- /scripts/obfuscate.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Script to obfuscate JavaScript files in dist folder 3 | * This makes the code harder to read and reverse-engineer 4 | */ 5 | const JavaScriptObfuscator = require('javascript-obfuscator'); 6 | const fs = require('fs'); 7 | const path = require('path'); 8 | 9 | // Configuration for obfuscation 10 | // Balance between protection and performance 11 | const obfuscationOptions = { 12 | // String encoding 13 | stringArray: true, 14 | stringArrayEncoding: ['base64'], 15 | stringArrayThreshold: 0.75, 16 | 17 | // Control flow flattening (makes code logic harder to follow) 18 | controlFlowFlattening: true, 19 | controlFlowFlatteningThreshold: 0.5, 20 | 21 | // Dead code injection (adds fake code) 22 | deadCodeInjection: true, 23 | deadCodeInjectionThreshold: 0.2, 24 | 25 | // Variable name obfuscation 26 | identifierNamesGenerator: 'hexadecimal', 27 | renameGlobals: false, // Don't rename globals (n8n needs them) 28 | 29 | // Compact code (remove whitespace) 30 | compact: true, 31 | 32 | // Self-defending (breaks if someone tries to beautify) 33 | selfDefending: false, // Can cause issues with n8n, disable if needed 34 | 35 | // Debug protection (slows down debuggers) 36 | debugProtection: false, // Disable for n8n compatibility 37 | 38 | // Performance 39 | target: 'node', 40 | 41 | // Source maps (disable for production) 42 | sourceMap: false, 43 | 44 | // Keep important things working 45 | unicodeEscapeSequence: false, 46 | }; 47 | 48 | // Directories and files to obfuscate 49 | const distDir = path.join(__dirname, '..', 'dist'); 50 | 51 | // Function to recursively find all .js files in dist folder 52 | const findJsFiles = (dir, fileList = []) => { 53 | const files = fs.readdirSync(dir, { withFileTypes: true }); 54 | 55 | files.forEach((file) => { 56 | const fullPath = path.join(dir, file.name); 57 | 58 | if (file.isDirectory()) { 59 | findJsFiles(fullPath, fileList); 60 | } else if (file.name.endsWith('.js') && !file.name.endsWith('.js.map')) { 61 | // Add relative path from distDir 62 | const relativePath = path.relative(distDir, fullPath); 63 | 64 | // Skip node and credential files - they need to be readable by n8n 65 | if (file.name.endsWith('.node.js') || file.name.endsWith('.credentials.js')) { 66 | console.log(`⏭️ Skipping ${relativePath} (node/credential file - must stay readable for n8n)`); 67 | return; 68 | } 69 | 70 | fileList.push(relativePath); 71 | } 72 | }); 73 | 74 | return fileList; 75 | }; 76 | 77 | // Get all .js files to obfuscate 78 | const nodesToObfuscate = findJsFiles(distDir); 79 | 80 | console.log('🔒 Starting code obfuscation...'); 81 | console.log(`📁 Found ${nodesToObfuscate.length} JavaScript files in dist folder\n`); 82 | 83 | let successCount = 0; 84 | let errorCount = 0; 85 | 86 | // Obfuscate each file 87 | nodesToObfuscate.forEach((relativePath) => { 88 | const filePath = path.join(distDir, relativePath); 89 | 90 | try { 91 | // Check if file exists 92 | if (!fs.existsSync(filePath)) { 93 | console.log(`⚠️ Skipping ${relativePath} (not found)`); 94 | return; 95 | } 96 | 97 | // Read original file 98 | const originalCode = fs.readFileSync(filePath, 'utf8'); 99 | const originalSize = originalCode.length; 100 | 101 | // Obfuscate 102 | const obfuscatedResult = JavaScriptObfuscator.obfuscate(originalCode, obfuscationOptions); 103 | const obfuscatedCode = obfuscatedResult.getObfuscatedCode(); 104 | const obfuscatedSize = obfuscatedCode.length; 105 | 106 | // Write obfuscated code back 107 | fs.writeFileSync(filePath, obfuscatedCode, 'utf8'); 108 | 109 | // Calculate size increase 110 | const sizeIncrease = ((obfuscatedSize - originalSize) / originalSize * 100).toFixed(1); 111 | 112 | console.log(`✅ Obfuscated: ${relativePath}`); 113 | console.log(` Original: ${(originalSize / 1024).toFixed(1)} KB`); 114 | console.log(` Obfuscated: ${(obfuscatedSize / 1024).toFixed(1)} KB (${sizeIncrease > 0 ? '+' : ''}${sizeIncrease}%)`); 115 | console.log(); 116 | 117 | successCount++; 118 | } catch (error) { 119 | console.error(`❌ Error obfuscating ${relativePath}:`, error.message); 120 | console.log(); 121 | errorCount++; 122 | } 123 | }); 124 | 125 | // Remove source maps (they reveal original code) 126 | console.log('🗑️ Removing source maps...'); 127 | const removeSourceMaps = (dir) => { 128 | const files = fs.readdirSync(dir, { withFileTypes: true }); 129 | 130 | files.forEach((file) => { 131 | const fullPath = path.join(dir, file.name); 132 | 133 | if (file.isDirectory()) { 134 | removeSourceMaps(fullPath); 135 | } else if (file.name.endsWith('.js.map')) { 136 | fs.unlinkSync(fullPath); 137 | console.log(` Removed: ${path.relative(distDir, fullPath)}`); 138 | } 139 | }); 140 | }; 141 | 142 | try { 143 | removeSourceMaps(distDir); 144 | } catch (error) { 145 | console.error('Error removing source maps:', error.message); 146 | } 147 | 148 | // Summary 149 | console.log('\n' + '='.repeat(60)); 150 | console.log(`📊 Obfuscation complete!`); 151 | console.log(` ✅ Success: ${successCount} files`); 152 | if (errorCount > 0) { 153 | console.log(` ❌ Errors: ${errorCount} files`); 154 | } 155 | console.log('='.repeat(60)); 156 | 157 | if (errorCount > 0) { 158 | process.exit(1); 159 | } 160 | -------------------------------------------------------------------------------- /nodes/SGR/SGR.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Layer 1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | SGR 51 | 52 | 53 | -------------------------------------------------------------------------------- /nodes/SGR/core/commands.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Special Commands Handler for SGR Agent 3 | * Handles /help, /tools, /clear, /new commands 4 | */ 5 | 6 | import type { IExecuteFunctions, INodeExecutionData, IDataObject } from 'n8n-workflow'; 7 | import type { AgentConfig } from '../agents/BaseAgent'; 8 | import { ToolCallingAgent } from '../agents'; 9 | 10 | export const HELP_MESSAGE = `**SGR Deep Research Agent - Help** 11 | 12 | **Special Commands:** 13 | - **/help** - Show this help message 14 | - **/tools** - List all available tools and configuration 15 | - **/clear** or **/new** - Clear chat history and start fresh 16 | 17 | **How to use:** 18 | 1. Ask any research question 19 | 2. Agent will use tools to find information 20 | 3. You'll get a detailed answer with sources 21 | 22 | **Examples:** 23 | - "Who are dinosaurs?" 24 | - "Create a detailed report on AI development in 2024" 25 | - "Explain how quantum computers work" 26 | 27 | **Features:** 28 | - Multi-step reasoning 29 | - Web search integration 30 | - Automatic planning for complex tasks 31 | - Memory across conversation 32 | - Source citations in reports 33 | 34 | Type **/tools** to see what tools are available.`; 35 | 36 | export const CLEAR_MESSAGE = `Chat history has been cleared. Starting fresh! 37 | 38 | Type **/tools** to see available tools.`; 39 | 40 | /** 41 | * Handle /help command 42 | */ 43 | export function handleHelpCommand(itemIndex: number, answerOnly: boolean): INodeExecutionData[][] { 44 | return [ 45 | [ 46 | { 47 | json: (answerOnly 48 | ? { message: HELP_MESSAGE } 49 | : { 50 | task: 'Show help', 51 | state: 'INFO', 52 | answer: HELP_MESSAGE, 53 | }) as IDataObject, 54 | pairedItem: { item: itemIndex }, 55 | }, 56 | ], 57 | ]; 58 | } 59 | 60 | /** 61 | * Handle /tools command 62 | */ 63 | export function handleToolsCommand( 64 | executeFunctions: IExecuteFunctions, 65 | config: AgentConfig, 66 | aiModel: { invoke: (messages: unknown[]) => Promise; [key: string]: unknown }, 67 | itemIndex: number, 68 | answerOnly: boolean, 69 | ): INodeExecutionData[][] { 70 | // Get all tools that would be available 71 | const tempAgent = new ToolCallingAgent(executeFunctions, config, aiModel); 72 | const availableTools = tempAgent['prepareTools'](); // Access protected method 73 | 74 | // Categorize tools 75 | const builtInTools = availableTools 76 | .filter( 77 | (t) => 78 | t.function.name.includes('_tool') && 79 | !t.function.name.includes('tavily') && 80 | !t.function.name.includes('mcp'), 81 | ) 82 | .map((t) => ({ 83 | name: t.function.name, 84 | description: t.function.description, 85 | type: 'built-in', 86 | schema: t.function.parameters, 87 | })); 88 | 89 | const externalTools = availableTools 90 | .filter( 91 | (t) => 92 | !t.function.name.includes('_tool') || 93 | t.function.name.includes('tavily') || 94 | t.function.name.includes('mcp'), 95 | ) 96 | .map((t) => ({ 97 | name: t.function.name, 98 | description: t.function.description, 99 | type: t.function.name.includes('tavily') ? 'search' : 'external', 100 | schema: t.function.parameters, 101 | })); 102 | 103 | const allTools = [...builtInTools, ...externalTools]; 104 | 105 | const toolsOutput = answerOnly 106 | ? { 107 | message: `Available ${allTools.length} tools (${builtInTools.length} built-in, ${externalTools.length} external). Use /help for more info.`, 108 | } 109 | : { 110 | task: 'Show available tools', 111 | state: 'INFO', 112 | total_tools: allTools.length, 113 | built_in_tools_count: builtInTools.length, 114 | external_tools_count: externalTools.length, 115 | configuration: { 116 | max_iterations: config.maxIterations, 117 | max_searches: config.maxSearches, 118 | max_clarifications: config.maxClarifications, 119 | }, 120 | tools: allTools, 121 | answer: `Available ${allTools.length} tools (${builtInTools.length} built-in, ${externalTools.length} external). Use /help for more info.`, 122 | }; 123 | 124 | return [ 125 | [ 126 | { 127 | json: toolsOutput as IDataObject, 128 | pairedItem: { item: itemIndex }, 129 | }, 130 | ], 131 | ]; 132 | } 133 | 134 | /** 135 | * Handle /clear or /new command 136 | */ 137 | export async function handleClearCommand( 138 | memory: { clear?: () => Promise; [key: string]: unknown } | undefined, 139 | logger: { info: (msg: string) => void; warn: (msg: string) => void }, 140 | itemIndex: number, 141 | answerOnly: boolean, 142 | ): Promise { 143 | try { 144 | if (memory && typeof memory.clear === 'function') { 145 | await memory.clear(); 146 | logger.info('🗑️ Memory cleared for new session'); 147 | } 148 | } catch (error) { 149 | logger.warn(`⚠️ Failed to clear memory: ${(error as Error).message}`); 150 | } 151 | 152 | return [ 153 | [ 154 | { 155 | json: answerOnly 156 | ? { message: CLEAR_MESSAGE } 157 | : { 158 | task: 'Memory cleared', 159 | state: 'CLEARED', 160 | answer: CLEAR_MESSAGE, 161 | }, 162 | pairedItem: { item: itemIndex }, 163 | }, 164 | ], 165 | ]; 166 | } 167 | 168 | /** 169 | * Check if task is a special command and return command name 170 | */ 171 | export function getCommandName(task: string): string | null { 172 | const lowerTask = task.toLowerCase().trim(); 173 | 174 | if (lowerTask === '/help') return 'help'; 175 | if (lowerTask === '/tools') return 'tools'; 176 | if (lowerTask === '/clear' || lowerTask === '/new') return 'clear'; 177 | 178 | return null; 179 | } 180 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # n8n-nodes-sgr-tool-calling 2 | 3 | ![SGR Example](./SGR_Example.png) 4 | 5 | AI research agent with OpenAI function calling for n8n. Port of [sgr-agent-core](https://github.com/vamplabAI/sgr-agent-core) Python project. 6 | 7 | **Copyright (C) 2025 MiXaiLL76 (mike.milos@yandex.ru)** 8 | 9 | [n8n](https://n8n.io/) is a [fair-code licensed](https://docs.n8n.io/reference/license/) workflow automation platform. 10 | 11 | ## Installation 12 | 13 | Follow the [installation guide](https://docs.n8n.io/integrations/community-nodes/installation/) in the n8n community nodes documentation. 14 | 15 | ## Quick Start 16 | 17 | 1. Add **SGR Agent** node to your workflow 18 | 2. Connect **AI Language Model** (OpenAI, Anthropic, etc.) 19 | 3. Connect **AI Tools** (optional): search, MCP, LangChain tools 20 | 4. Connect **Memory** (optional): for conversation history 21 | 22 | ### Example Workflow 23 | 24 | ``` 25 | Chat Trigger → SGR Agent → Output 26 | ↓ ↓ ↓ ↓ 27 | [Model][Tools][Memory] 28 | ``` 29 | 30 | Import **[SGR_Example.json](https://github.com/MiXaiLL76/sgr_tool_calling/blob/main//SGR_Example.json)** to get started. 31 | 32 | ## Features 33 | 34 | ### Built-in Tools 35 | 36 | Agent uses 6 system tools for research tasks: 37 | 38 | - `reasoning_tool` - analyze task and plan next steps 39 | - `final_answer_tool` - complete task execution 40 | - `create_report_tool` - generate detailed reports with citations 41 | - `clarification_tool` - ask clarifying questions 42 | - `generate_plan_tool` - create research plans 43 | - `adapt_plan_tool` - adjust plans based on findings 44 | 45 | All tools can be enabled/disabled in node settings. 46 | 47 | ### Connected Tools 48 | 49 | Connect any n8n AI Tool: 50 | 51 | - **SGR Tavily Search** - web search (included) 52 | - **SGR Custom Final Answer Tool** - customizable final answer schema (included) 53 | - **MCP Client Tool** - Model Context Protocol integrations 54 | - **LangChain Tools** - calculators, code interpreters, etc. 55 | - Supports the `/tools` command to display all connected tools 56 | 57 | Agent automatically highlights connected tools when they execute. 58 | 59 | #### SGR Custom Final Answer Tool 60 | 61 | Allows you to customize the JSON schema for the final answer tool: 62 | 63 | - Define your own schema structure using JSON Schema format 64 | - Default schema imported from `nodes/SGR/tools/finalAnswer.ts` 65 | - Automatically disables built-in Final Answer and Clarification tools when connected 66 | - Built-in schema validation ensures proper format 67 | - Supports both full JSON return or field extraction 68 | - Perfect for custom report formats with specific fields like citations, confidence scores, metadata, etc. 69 | 70 | ### Memory 71 | 72 | Connect n8n Memory node for conversation history: 73 | 74 | - Remembers previous interactions within session 75 | - Automatically clears when `sessionId` changes 76 | - Supports `/clear` and `/new` commands 77 | - Only stores user questions and final answers (not internal reasoning) 78 | - **Clarification Support**: preserves conversation context when agent requests clarifications 79 | 80 | ### Clarification Flow 81 | 82 | When agent needs clarification, it uses the `clarification_tool` to ask questions: 83 | 84 | 1. **Agent Requests Clarification** 85 | - Agent analyzes the task and identifies ambiguous terms 86 | - Calls `clarification_tool` with 3 specific questions 87 | - Conversation history (including questions) is saved to Memory 88 | - Execution pauses with state `WAITING_FOR_CLARIFICATION` 89 | 90 | 2. **User Provides Answers** 91 | - Send answers via `clarificationAnswers` field in input 92 | - Agent loads conversation history from Memory 93 | - Continues research with full context 94 | 95 | ### Limits 96 | 97 | Configure resource constraints: 98 | 99 | - **Max Iterations** (default: 10) - reasoning cycles before stopping 100 | - **Max Searches** (default: 4) - web search limit 101 | - **Max Clarifications** (default: 3) - clarification request limit 102 | 103 | ### Custom Prompts 104 | 105 | Override default prompts: 106 | 107 | - **System Prompt** - agent behavior instructions 108 | - **Initial User Request Template** - format task presentation 109 | - **Clarification Response Template** - format clarification responses 110 | 111 | ## Resources 112 | 113 | - [n8n community nodes documentation](https://docs.n8n.io/integrations/#community-nodes) 114 | - [SGR Deep Research (Original Python Project)](https://github.com/vamplabAI/sgr-agent-core) 115 | - [n8n AI Agents Documentation](https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.agent/) 116 | 117 | ## License 118 | 119 | This project is licensed under **AGPL-3.0** - see the [LICENSE](LICENSE) file for details. 120 | 121 | ### Commercial Licensing 122 | 123 | **AGPL-3.0** requires you to open-source your modifications and provide source code to users if you run this software as a network service. 124 | 125 | **For commercial use** where you want to: 126 | 127 | - Keep your modifications private 128 | - Integrate into proprietary software 129 | - Provide as a managed service without open-sourcing 130 | 131 | **Contact for a commercial license:** [mike.milos@yandex.ru](mailto:mike.milos@yandex.ru) 132 | 133 | ### Free Use Cases 134 | 135 | This software is **free** for: 136 | 137 | - ✅ Personal use 138 | - ✅ Educational purposes 139 | - ✅ Research projects 140 | - ✅ Open-source projects (compliant with AGPL-3.0) 141 | 142 | If you modify and deploy this software as a network service, you must provide source code to your users under AGPL-3.0 terms. 143 | -------------------------------------------------------------------------------- /nodes/SGRCustomFinalAnswer/SgrCustomFinalAnswer.node.ts: -------------------------------------------------------------------------------- 1 | import type { 2 | INodeType, 3 | INodeTypeDescription, 4 | ISupplyDataFunctions, 5 | SupplyData, 6 | } from 'n8n-workflow'; 7 | 8 | const DEFAULT_DESCRIPTION = `Finalize research task and complete agent execution after all steps are completed. 9 | 10 | Usage: Call after you complete research task 11 | 12 | NOTE: When using this custom tool, the built-in "Final Answer Tool" and "Clarification Tool" 13 | are automatically disabled in SGR Agent to avoid conflicts.`; 14 | 15 | const DEFAULT_SCHEMA = { 16 | type: 'object', 17 | properties: { 18 | reasoning: { 19 | type: 'string', 20 | description: 'Why task is now complete and how answer was verified', 21 | }, 22 | completed_steps: { 23 | type: 'array', 24 | items: { type: 'string' }, 25 | description: 'Summary of completed steps including verification', 26 | minItems: 1, 27 | maxItems: 5, 28 | }, 29 | answer: { 30 | type: 'string', 31 | description: 'Comprehensive final answer with EXACT factual details (dates, numbers, names)', 32 | }, 33 | status: { 34 | type: 'string', 35 | enum: ['COMPLETED', 'FAILED'], 36 | description: 'Task completion status', 37 | }, 38 | }, 39 | required: ['reasoning', 'completed_steps', 'answer', 'status'], 40 | }; 41 | 42 | export class SgrCustomFinalAnswer implements INodeType { 43 | description: INodeTypeDescription = { 44 | displayName: 'SGR Custom Final Answer Tool', 45 | name: 'sgrCustomFinalAnswer', 46 | icon: 'file:../SGR/SGR.svg', 47 | group: ['transform'], 48 | version: 1, 49 | description: 'Custom configurable Final Answer tool for SGR Agent', 50 | usableAsTool: true, 51 | defaults: { 52 | name: 'Custom Final Answer', 53 | }, 54 | inputs: [], 55 | outputs: ['ai_tool'], 56 | outputNames: ['Tool'], 57 | properties: [ 58 | // { 59 | // displayName: 'Tool Name', 60 | // name: 'toolName', 61 | // type: 'string', 62 | // default: 'custom_final_answer_tool', 63 | // description: 64 | // 'Name of the tool. Use "final_answer_tool" to replace the built-in tool (auto-disabled when this tool is connected).', 65 | // required: true, 66 | // }, 67 | { 68 | displayName: 'Description', 69 | name: 'description', 70 | type: 'string', 71 | typeOptions: { 72 | rows: 5, 73 | }, 74 | default: DEFAULT_DESCRIPTION, 75 | description: 'Description of what the tool does (shown to the AI model)', 76 | required: true, 77 | }, 78 | { 79 | displayName: 'JSON Schema', 80 | name: 'jsonSchema', 81 | type: 'json', 82 | default: JSON.stringify(DEFAULT_SCHEMA, null, 2), 83 | description: 'JSON Schema defining the structure of tool parameters', 84 | required: true, 85 | validateType: 'object', 86 | }, 87 | ], 88 | }; 89 | 90 | async supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise { 91 | // Import NodeOperationError inside the function to avoid top-level runtime imports 92 | const { NodeOperationError } = await import('n8n-workflow'); 93 | 94 | const toolName = 'custom_final_answer_tool'; // this.getNodeParameter('toolName', itemIndex) as string; 95 | const description = this.getNodeParameter('description', itemIndex) as string; 96 | const jsonSchemaParam = this.getNodeParameter('jsonSchema', itemIndex); 97 | 98 | // Parse and validate schema 99 | let schema: Record; 100 | 101 | // Handle both string and object types 102 | if (typeof jsonSchemaParam === 'string') { 103 | // Check for invalid object-to-string conversion 104 | if (jsonSchemaParam === '[object Object]') { 105 | throw new NodeOperationError( 106 | this.getNode(), 107 | 'Invalid JSON schema: received "[object Object]" instead of valid JSON. Please ensure the JSON Schema field contains valid JSON string.', 108 | ); 109 | } 110 | 111 | try { 112 | schema = JSON.parse(jsonSchemaParam); 113 | } catch (error) { 114 | throw new NodeOperationError( 115 | this.getNode(), 116 | `Invalid JSON schema: ${(error as Error).message}`, 117 | ); 118 | } 119 | } else if (typeof jsonSchemaParam === 'object' && jsonSchemaParam !== null) { 120 | // n8n may pass already parsed object 121 | schema = jsonSchemaParam as Record; 122 | } else { 123 | throw new NodeOperationError( 124 | this.getNode(), 125 | `Invalid JSON schema: expected string or object, got ${typeof jsonSchemaParam}`, 126 | ); 127 | } 128 | 129 | // Validate schema is an object 130 | if (typeof schema !== 'object' || schema === null || Array.isArray(schema)) { 131 | throw new NodeOperationError(this.getNode(), 'JSON schema must be a valid object'); 132 | } 133 | 134 | // Basic schema validation 135 | if (schema.type !== 'object') { 136 | throw new NodeOperationError( 137 | this.getNode(), 138 | 'JSON schema must have type "object" at root level', 139 | ); 140 | } 141 | 142 | if (!schema.properties || typeof schema.properties !== 'object') { 143 | throw new NodeOperationError(this.getNode(), 'JSON schema must have "properties" object'); 144 | } 145 | 146 | // Auto-generate required array if missing or empty 147 | const properties = schema.properties as Record; 148 | const propertyKeys = Object.keys(properties); 149 | 150 | if (!schema.required || !Array.isArray(schema.required) || schema.required.length === 0) { 151 | schema.required = propertyKeys; 152 | } 153 | 154 | // Auto-generate descriptions for fields that don't have them 155 | for (const [fieldName, fieldSchema] of Object.entries(properties)) { 156 | if (typeof fieldSchema === 'object' && fieldSchema !== null && !fieldSchema.description) { 157 | // Convert field name to human-readable format 158 | // e.g., "person" -> "Person", "user_name" -> "User name", "dateOfBirth" -> "Date of birth" 159 | const humanReadable = fieldName 160 | .replace(/_/g, ' ') 161 | .replace(/([A-Z])/g, ' $1') 162 | .trim() 163 | .toLowerCase() 164 | .replace(/^\w/, (c) => c.toUpperCase()); 165 | 166 | fieldSchema.description = `Provide the ${humanReadable} value based on your research and findings`; 167 | } 168 | } 169 | 170 | const tool = { 171 | name: toolName, 172 | description, 173 | schema, 174 | call: async (args: Record) => { 175 | return JSON.stringify(args, null, 2); 176 | }, 177 | }; 178 | 179 | return { 180 | response: tool, 181 | }; 182 | } 183 | } 184 | -------------------------------------------------------------------------------- /nodes/SGRTavilySearchTool/SgrTavilySearchTool.node.ts: -------------------------------------------------------------------------------- 1 | import { 2 | type INodeType, 3 | type INodeTypeDescription, 4 | type ISupplyDataFunctions, 5 | type SupplyData, 6 | } from 'n8n-workflow'; 7 | 8 | export class SgrTavilySearchTool implements INodeType { 9 | description: INodeTypeDescription = { 10 | displayName: 'SGR Tavily Search Tool', 11 | name: 'sgrTavilySearchTool', 12 | icon: 'file:tavily.svg', 13 | group: ['transform'], 14 | version: 1, 15 | description: 'Web search tool using Tavily API for SGR Agent', 16 | usableAsTool: true, 17 | defaults: { 18 | name: 'SGR Tavily Search', 19 | }, 20 | inputs: [], 21 | outputs: ['ai_tool'], 22 | outputNames: ['Tool'], 23 | credentials: [ 24 | { 25 | name: 'tavilyApi', 26 | required: true, 27 | }, 28 | ], 29 | properties: [ 30 | { 31 | displayName: 'Max Results', 32 | name: 'maxResults', 33 | type: 'number', 34 | default: 5, 35 | description: 'Maximum number of search results to return', 36 | typeOptions: { 37 | minValue: 1, 38 | maxValue: 10, 39 | }, 40 | }, 41 | { 42 | displayName: 'Search Depth', 43 | name: 'searchDepth', 44 | type: 'options', 45 | options: [ 46 | { 47 | name: 'Basic', 48 | value: 'basic', 49 | description: 'Fast search with basic results', 50 | }, 51 | { 52 | name: 'Advanced', 53 | value: 'advanced', 54 | description: 'Detailed search with more comprehensive results', 55 | }, 56 | ], 57 | default: 'basic', 58 | description: 'The depth of the search', 59 | }, 60 | { 61 | displayName: 'Include Answer', 62 | name: 'includeAnswer', 63 | type: 'boolean', 64 | default: true, 65 | description: 'Whether to include a summarized answer in the response', 66 | }, 67 | { 68 | displayName: 'Include Raw Content', 69 | name: 'includeRawContent', 70 | type: 'boolean', 71 | default: false, 72 | description: 'Whether to include raw HTML content', 73 | }, 74 | ], 75 | }; 76 | 77 | async supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise { 78 | const maxResults = this.getNodeParameter('maxResults', itemIndex) as number; 79 | const searchDepth = this.getNodeParameter('searchDepth', itemIndex) as string; 80 | const includeAnswer = this.getNodeParameter('includeAnswer', itemIndex) as boolean; 81 | const includeRawContent = this.getNodeParameter('includeRawContent', itemIndex) as boolean; 82 | 83 | const credentials = await this.getCredentials('tavilyApi'); 84 | const apiKey = credentials.apiKey as string; 85 | 86 | const tool = { 87 | name: 'tavily_search', 88 | description: `Search the web for real-time information about any topic. 89 | Use this tool when you need up-to-date information that might not be available in your training data. 90 | The search results will include relevant snippets and URLs from web pages. 91 | 92 | Usage: 93 | - Use SPECIFIC terms and context in queries 94 | - Search queries in SAME LANGUAGE as user request 95 | - For date/number questions, include specific year/context in query 96 | 97 | Returns: Page titles, URLs, snippets, and optionally a summarized answer`, 98 | schema: { 99 | type: 'object', 100 | properties: { 101 | query: { 102 | type: 'string', 103 | description: 'Search query in same language as user request', 104 | }, 105 | reasoning: { 106 | type: 'string', 107 | description: 'Why this search is needed and what to expect', 108 | }, 109 | }, 110 | required: ['query', 'reasoning'], 111 | }, 112 | call: async (args: { query: string; reasoning: string }) => { 113 | const { query } = args; 114 | try { 115 | const response = await this.helpers.httpRequest({ 116 | method: 'POST', 117 | url: 'https://api.tavily.com/search', 118 | headers: { 119 | 'Content-Type': 'application/json', 120 | }, 121 | body: { 122 | api_key: apiKey, 123 | query, 124 | max_results: maxResults, 125 | search_depth: searchDepth, 126 | include_answer: includeAnswer, 127 | include_raw_content: includeRawContent, 128 | }, 129 | }); 130 | 131 | const data = response as { 132 | answer?: string; 133 | results?: Array<{ 134 | title: string; 135 | url: string; 136 | content?: string; 137 | raw_content?: string; 138 | }>; 139 | }; 140 | 141 | // Build sources metadata for AgentContext 142 | interface SourceData { 143 | number: number; 144 | title: string; 145 | url: string; 146 | snippet: string; 147 | full_content: string; 148 | char_count: number; 149 | } 150 | 151 | const sources: SourceData[] = []; 152 | if (data.results && Array.isArray(data.results)) { 153 | data.results.forEach((result, index: number) => { 154 | const source: SourceData = { 155 | number: index + 1, 156 | title: result.title || 'Untitled', 157 | url: result.url, 158 | snippet: result.content || '', 159 | full_content: result.raw_content || '', 160 | char_count: (result.raw_content || '').length, 161 | }; 162 | sources.push(source); 163 | }); 164 | } 165 | 166 | // Format the response 167 | let formattedResult = `Search Query: ${query}\n\n`; 168 | 169 | if (data.answer && includeAnswer) { 170 | formattedResult += `Summary Answer:\n${data.answer}\n\n`; 171 | } 172 | 173 | formattedResult += 'Search Results:\n\n'; 174 | 175 | if (data.results && Array.isArray(data.results)) { 176 | data.results.forEach((result, index: number) => { 177 | formattedResult += `[${index + 1}] ${result.title}\n`; 178 | formattedResult += `URL: ${result.url}\n`; 179 | if (result.content) { 180 | const snippet = 181 | result.content.length > 200 182 | ? result.content.substring(0, 200) + '...' 183 | : result.content; 184 | formattedResult += `Snippet: ${snippet}\n`; 185 | } 186 | formattedResult += '\n'; 187 | }); 188 | } 189 | 190 | // Return result with embedded sources metadata as JSON 191 | // This allows ToolCallingAgent to extract sources and add them to context 192 | const resultWithMetadata = { 193 | formatted: formattedResult, 194 | query, 195 | answer: data.answer || '', 196 | sources, 197 | }; 198 | 199 | return JSON.stringify(resultWithMetadata, null, 2); 200 | } catch (error) { 201 | return `Error executing Tavily search: ${(error as Error).message}`; 202 | } 203 | }, 204 | }; 205 | 206 | return { 207 | response: tool, 208 | }; 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /SGR_Example.json: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": [ 3 | { 4 | "parameters": { 5 | "options": {} 6 | }, 7 | "type": "@n8n/n8n-nodes-langchain.chatTrigger", 8 | "typeVersion": 1.3, 9 | "position": [0, 0], 10 | "id": "c811e616-fbf4-4bb8-8012-531346f59b80", 11 | "name": "When chat message received", 12 | "webhookId": "a05f316a-661d-43c8-ab9c-5a86d2af2968" 13 | }, 14 | { 15 | "parameters": { 16 | "logLevel": "error", 17 | "builtInTools": { 18 | "enableAdaptPlan": true, 19 | "enableClarification": true, 20 | "enableCreateReport": true, 21 | "enableFinalAnswer": true, 22 | "enableGeneratePlan": true, 23 | "enableReasoning": true 24 | }, 25 | "prompts": { 26 | "systemPrompt": "\nYou are an expert researcher with adaptive planning and schema-guided-reasoning capabilities. You get the research task and you neeed to do research and genrete answer\n\n\n\nPAY ATTENTION TO THE DATE INSIDE THE USER REQUEST\nDATE FORMAT: YYYY-MM-DD HH:MM:SS (ISO 8601)\nIMPORTANT: The date above is in YYYY-MM-DD format (Year-Month-Day). For example, 2025-10-03 means October 3rd, 2025, NOT March 10th.\n\n\n: Detect the language from user request and use this LANGUAGE for all responses, searches, and result finalanswertool\nLANGUAGE ADAPTATION: Always respond and create reports in the SAME LANGUAGE as the user's request.\nIf user writes in Russian - respond in Russian, if in English - respond in English.\n:\n\n:\n1. Memorize plan you generated in first step and follow the task inside your plan.\n1. Adapt plan when new data contradicts initial assumptions\n2. Search queries in SAME LANGUAGE as user request\n3. Final Answer ENTIRELY in SAME LANGUAGE as user request\n\n\n\nADAPTIVITY: Actively change plan when discovering new data.\nANALYSIS EXTRACT DATA: Always analyze data that you took in extractpagecontenttool\n\n\n\nCRITICAL FOR FACTUAL ACCURACY:\nWhen answering questions about specific dates, numbers, versions, or names:\n1. EXACT VALUES: Extract the EXACT value from sources (day, month, year for dates; precise numbers for quantities)\n2. VERIFY YEAR: If question mentions a specific year (e.g., \"in 2022\"), verify extracted content is about that SAME year\n3. CROSS-VERIFICATION: When sources provide contradictory information, prefer:\n - Official sources and primary documentation over secondary sources\n - Search result snippets that DIRECTLY answer the question over extracted page content\n - Multiple independent sources confirming the same fact\n4. DATE PRECISION: Pay special attention to exact dates - day matters (October 21 ≠ October 22)\n5. NUMBER PRECISION: For numbers/versions, exact match required (6.88b ≠ 6.88c, Episode 31 ≠ Episode 32)\n6. SNIPPET PRIORITY: If search snippet clearly states the answer, trust it unless extract proves it wrong\n7. TEMPORAL VALIDATION: When extracting page content, check if the page shows data for correct time period\n\n\n:\n{available_tools}\n", 27 | "initialUserRequest": "Current Date: {current_date} (Year-Month-Day ISO format: YYYY-MM-DD HH:MM:SS)\nORIGINAL USER REQUEST:\n\n{task}", 28 | "clarificationResponse": "Current Date: {current_date} (Year-Month-Day ISO format: YYYY-MM-DD HH:MM:SS)\n\nCLARIFICATIONS:\n\n{clarifications}" 29 | }, 30 | "additionalTools": { 31 | "tools": [] 32 | }, 33 | "options": {} 34 | }, 35 | "type": "n8n-nodes-sgr-tool-calling.sgrToolCalling", 36 | "typeVersion": 1, 37 | "position": [208, 0], 38 | "id": "c179a12d-f90a-49d8-adff-38ab74ed1703", 39 | "name": "SGR Agent" 40 | }, 41 | { 42 | "parameters": { 43 | "model": { 44 | "__rl": true, 45 | "value": "openai/gpt-4.1-mini", 46 | "mode": "list", 47 | "cachedResultName": "openai/gpt-4.1-mini" 48 | }, 49 | "options": {} 50 | }, 51 | "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi", 52 | "typeVersion": 1.2, 53 | "position": [16, 208], 54 | "id": "b754af75-1c19-41dd-a325-5fc202eae11a", 55 | "name": "OpenAI Chat Model", 56 | "credentials": { 57 | "openAiApi": { 58 | "id": "ADiovoX5nrP8iXIZ", 59 | "name": "OpenAi account" 60 | } 61 | } 62 | }, 63 | { 64 | "parameters": {}, 65 | "type": "n8n-nodes-sgr-tool-calling.sgrTavilySearchTool", 66 | "typeVersion": 1, 67 | "position": [160, 336], 68 | "id": "b36f417a-faec-486d-95ea-0423c992bb28", 69 | "name": "SGR Tavily Search", 70 | "credentials": { 71 | "tavilyApi": { 72 | "id": "5rQLQHJ8SpNU1big", 73 | "name": "Tavily account" 74 | } 75 | } 76 | }, 77 | { 78 | "parameters": {}, 79 | "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow", 80 | "typeVersion": 1.3, 81 | "position": [576, 336], 82 | "id": "61829a58-1118-4a1d-bfc9-e0a7436e7c90", 83 | "name": "Simple Memory" 84 | }, 85 | { 86 | "parameters": { 87 | "endpointUrl": "https://mcp.context7.com/mcp", 88 | "options": {} 89 | }, 90 | "type": "@n8n/n8n-nodes-langchain.mcpClientTool", 91 | "typeVersion": 1.2, 92 | "position": [288, 336], 93 | "id": "dd86c162-d82b-4ef9-a899-936aa134a52a", 94 | "name": "MCP context7" 95 | }, 96 | { 97 | "parameters": { 98 | "endpointUrl": "https://mcp.deepwiki.com/mcp", 99 | "options": {} 100 | }, 101 | "type": "@n8n/n8n-nodes-langchain.mcpClientTool", 102 | "typeVersion": 1.2, 103 | "position": [432, 336], 104 | "id": "e9405a32-9b2e-41a3-b66c-d07200ee0370", 105 | "name": "MCP deepwiki" 106 | }, 107 | { 108 | "parameters": {}, 109 | "type": "@n8n/n8n-nodes-langchain.toolCalculator", 110 | "typeVersion": 1, 111 | "position": [816, 336], 112 | "id": "6d17f55c-f6a1-4a18-8e62-1590394cf926", 113 | "name": "Calculator" 114 | }, 115 | { 116 | "parameters": {}, 117 | "type": "@n8n/n8n-nodes-langchain.toolWikipedia", 118 | "typeVersion": 1, 119 | "position": [704, 336], 120 | "id": "6426bfb1-920e-4ca9-baa1-c51726caa082", 121 | "name": "Wikipedia" 122 | } 123 | ], 124 | "connections": { 125 | "When chat message received": { 126 | "main": [ 127 | [ 128 | { 129 | "node": "SGR Agent", 130 | "type": "main", 131 | "index": 0 132 | } 133 | ] 134 | ] 135 | }, 136 | "OpenAI Chat Model": { 137 | "ai_languageModel": [ 138 | [ 139 | { 140 | "node": "SGR Agent", 141 | "type": "ai_languageModel", 142 | "index": 0 143 | } 144 | ] 145 | ] 146 | }, 147 | "SGR Tavily Search": { 148 | "ai_tool": [ 149 | [ 150 | { 151 | "node": "SGR Agent", 152 | "type": "ai_tool", 153 | "index": 0 154 | } 155 | ] 156 | ] 157 | }, 158 | "Simple Memory": { 159 | "ai_memory": [ 160 | [ 161 | { 162 | "node": "SGR Agent", 163 | "type": "ai_memory", 164 | "index": 0 165 | } 166 | ] 167 | ] 168 | }, 169 | "MCP context7": { 170 | "ai_tool": [ 171 | [ 172 | { 173 | "node": "SGR Agent", 174 | "type": "ai_tool", 175 | "index": 0 176 | } 177 | ] 178 | ] 179 | }, 180 | "MCP deepwiki": { 181 | "ai_tool": [ 182 | [ 183 | { 184 | "node": "SGR Agent", 185 | "type": "ai_tool", 186 | "index": 0 187 | } 188 | ] 189 | ] 190 | }, 191 | "Calculator": { 192 | "ai_tool": [ 193 | [ 194 | { 195 | "node": "SGR Agent", 196 | "type": "ai_tool", 197 | "index": 0 198 | } 199 | ] 200 | ] 201 | }, 202 | "Wikipedia": { 203 | "ai_tool": [ 204 | [ 205 | { 206 | "node": "SGR Agent", 207 | "type": "ai_tool", 208 | "index": 0 209 | } 210 | ] 211 | ] 212 | } 213 | }, 214 | "pinData": {}, 215 | "meta": { 216 | "instanceId": "c8f2c278dffe2afeb32ae7530b0e166ca09cfdac5bb04acbf389aa8bf564b5eb" 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /nodes/SGR/SgrToolCalling.node.ts: -------------------------------------------------------------------------------- 1 | import { 2 | NodeConnectionTypes, 3 | NodeOperationError, 4 | type IDataObject, 5 | type IExecuteFunctions, 6 | type INodeExecutionData, 7 | type INodeType, 8 | type INodeTypeDescription, 9 | } from 'n8n-workflow'; 10 | 11 | import { ToolCallingAgent } from './agents'; 12 | import type { AgentConfig, AdditionalToolConfig } from './agents/BaseAgent'; 13 | import { 14 | convertN8nToolsToInternal, 15 | createLoggedToolWrapper, 16 | type N8nAITool, 17 | } from './core/toolConverter'; 18 | import { 19 | DEFAULT_SYSTEM_PROMPT, 20 | DEFAULT_INITIAL_USER_REQUEST, 21 | DEFAULT_CLARIFICATION_RESPONSE, 22 | } from './prompts'; 23 | import { 24 | getCommandName, 25 | handleHelpCommand, 26 | handleToolsCommand, 27 | handleClearCommand, 28 | } from './core/commands'; 29 | import { ConfigurableLogger, type LogLevel } from './core/logger'; 30 | 31 | // Type definitions for n8n AI components 32 | interface N8nAiLanguageModel { 33 | invoke: (messages: unknown[]) => Promise; 34 | [key: string]: unknown; 35 | } 36 | 37 | interface N8nAiTool { 38 | name: string; 39 | description: string; 40 | schema?: unknown; 41 | call?: (args: unknown) => Promise; 42 | [key: string]: unknown; 43 | } 44 | 45 | interface N8nAiMemory { 46 | getChatMessages?: () => Promise; 47 | addMessage?: (message: unknown) => Promise; 48 | clear?: () => Promise; 49 | [key: string]: unknown; 50 | } 51 | 52 | interface BuiltInToolsConfig { 53 | enableReasoning?: boolean; 54 | enableFinalAnswer?: boolean; 55 | enableCreateReport?: boolean; 56 | enableClarification?: boolean; 57 | enableGeneratePlan?: boolean; 58 | enableAdaptPlan?: boolean; 59 | } 60 | 61 | interface PromptsConfig { 62 | systemPrompt?: string; 63 | initialUserRequest?: string; 64 | clarificationResponse?: string; 65 | } 66 | 67 | interface OptionsConfig { 68 | returnFullLog?: boolean; 69 | answerOnly?: boolean; 70 | } 71 | 72 | export class SgrToolCalling implements INodeType { 73 | description: INodeTypeDescription = { 74 | displayName: 'SGR Agent', 75 | name: 'sgrToolCalling', 76 | icon: 'file:SGR.svg', 77 | group: ['transform'], 78 | version: 1, 79 | subtitle: 'AI Agent with Tool Calling', 80 | description: 'SGR Research Agent with OpenAI Tool Calling', 81 | usableAsTool: true, 82 | defaults: { 83 | name: 'SGR Agent', 84 | }, 85 | inputs: [ 86 | NodeConnectionTypes.Main, 87 | { 88 | displayName: 'Chat Model', 89 | maxConnections: 1, 90 | type: NodeConnectionTypes.AiLanguageModel, 91 | required: true, 92 | }, 93 | { 94 | displayName: 'Tools', 95 | maxConnections: undefined, 96 | type: NodeConnectionTypes.AiTool, 97 | required: false, 98 | }, 99 | { 100 | displayName: 'Memory', 101 | maxConnections: 1, 102 | type: NodeConnectionTypes.AiMemory, 103 | required: false, 104 | }, 105 | ], 106 | outputs: [NodeConnectionTypes.Main], 107 | properties: [ 108 | { 109 | displayName: 'Log Level', 110 | name: 'logLevel', 111 | type: 'options', 112 | default: 'error', 113 | description: 'Set the logging level for the agent', 114 | options: [ 115 | { 116 | name: 'Debug', 117 | value: 'debug', 118 | description: 'All messages including debug info', 119 | }, 120 | { 121 | name: 'Error', 122 | value: 'error', 123 | description: 'Only error messages', 124 | }, 125 | { 126 | name: 'Info', 127 | value: 'info', 128 | description: 'Info, warnings and errors', 129 | }, 130 | { 131 | name: 'None', 132 | value: 'none', 133 | description: 'No logging output', 134 | }, 135 | { 136 | name: 'Warning', 137 | value: 'warn', 138 | description: 'Warnings and errors', 139 | }, 140 | ], 141 | }, 142 | { 143 | displayName: 'Built-in Tools', 144 | name: 'builtInTools', 145 | type: 'collection', 146 | placeholder: 'Configure Built-in Tools', 147 | default: { 148 | enableReasoning: true, 149 | enableFinalAnswer: true, 150 | enableCreateReport: true, 151 | enableClarification: true, 152 | enableGeneratePlan: true, 153 | enableAdaptPlan: true, 154 | }, 155 | description: 'Enable or disable built-in SGR tools', 156 | options: [ 157 | { 158 | displayName: 'Adapt Plan Tool', 159 | name: 'enableAdaptPlan', 160 | type: 'boolean', 161 | default: true, 162 | description: 'Whether to enable tool to adapt research plans based on findings', 163 | }, 164 | { 165 | displayName: 'Clarification Tool', 166 | name: 'enableClarification', 167 | type: 'boolean', 168 | default: true, 169 | description: 'Whether to enable tool to ask clarifying questions', 170 | }, 171 | { 172 | displayName: 'Create Report Tool', 173 | name: 'enableCreateReport', 174 | type: 'boolean', 175 | default: true, 176 | description: 'Whether to enable tool to create comprehensive reports with citations', 177 | }, 178 | { 179 | displayName: 'Final Answer Tool', 180 | name: 'enableFinalAnswer', 181 | type: 'boolean', 182 | default: true, 183 | description: 'Whether to enable tool to finalize research and complete execution', 184 | }, 185 | { 186 | displayName: 'Generate Plan Tool', 187 | name: 'enableGeneratePlan', 188 | type: 'boolean', 189 | default: true, 190 | description: 'Whether to enable tool to generate research plans', 191 | }, 192 | { 193 | displayName: 'Reasoning Tool', 194 | name: 'enableReasoning', 195 | type: 'boolean', 196 | default: true, 197 | description: 'Whether to enable agent core reasoning tool for determining next steps', 198 | }, 199 | ], 200 | }, 201 | { 202 | displayName: 'Max Iterations', 203 | name: 'maxIterations', 204 | type: 'number', 205 | default: 10, 206 | description: 'Maximum number of iterations before forcing completion', 207 | }, 208 | { 209 | displayName: 'Max Searches', 210 | name: 'maxSearches', 211 | type: 'number', 212 | default: 4, 213 | description: 'Maximum number of web searches allowed', 214 | }, 215 | { 216 | displayName: 'Max Clarifications', 217 | name: 'maxClarifications', 218 | type: 'number', 219 | default: 3, 220 | description: 'Maximum number of clarification requests', 221 | }, 222 | { 223 | displayName: 'Prompts', 224 | name: 'prompts', 225 | type: 'collection', 226 | placeholder: 'Configure Prompts', 227 | default: { 228 | systemPrompt: DEFAULT_SYSTEM_PROMPT, 229 | initialUserRequest: DEFAULT_INITIAL_USER_REQUEST, 230 | clarificationResponse: DEFAULT_CLARIFICATION_RESPONSE, 231 | }, 232 | description: 233 | 'Configure system prompts and templates (defaults from nodes/SGR/prompts/index.ts)', 234 | options: [ 235 | { 236 | displayName: 'System Prompt', 237 | name: 'systemPrompt', 238 | type: 'string', 239 | default: DEFAULT_SYSTEM_PROMPT, 240 | description: 241 | 'Main system prompt for the agent. Default value from nodes/SGR/prompts/index.ts.', 242 | typeOptions: { 243 | rows: 10, 244 | }, 245 | }, 246 | { 247 | displayName: 'Initial User Request Template', 248 | name: 'initialUserRequest', 249 | type: 'string', 250 | default: DEFAULT_INITIAL_USER_REQUEST, 251 | description: 252 | 'Template for initial user request from nodes/SGR/prompts/index.ts. Use {task} and {current_date} placeholders.', 253 | typeOptions: { 254 | rows: 5, 255 | }, 256 | }, 257 | { 258 | displayName: 'Clarification Response Template', 259 | name: 'clarificationResponse', 260 | type: 'string', 261 | default: DEFAULT_CLARIFICATION_RESPONSE, 262 | description: 263 | 'Template for clarification responses from nodes/SGR/prompts/index.ts. Use {clarifications} and {current_date} placeholders.', 264 | typeOptions: { 265 | rows: 5, 266 | }, 267 | }, 268 | ], 269 | }, 270 | { 271 | displayName: 'Additional Tools', 272 | name: 'additionalTools', 273 | type: 'fixedCollection', 274 | placeholder: 'Add Tool', 275 | default: { tools: [] }, 276 | description: 'Additional custom tools to use alongside system tools', 277 | typeOptions: { 278 | multipleValues: true, 279 | }, 280 | options: [ 281 | { 282 | displayName: 'Tools', 283 | name: 'tools', 284 | values: [ 285 | { 286 | displayName: 'Tool Name', 287 | name: 'toolName', 288 | type: 'string', 289 | default: '', 290 | description: 'Name of the tool', 291 | }, 292 | { 293 | displayName: 'Description', 294 | name: 'description', 295 | type: 'string', 296 | typeOptions: { 297 | rows: 3, 298 | }, 299 | default: '', 300 | description: 'Description of what the tool does', 301 | }, 302 | { 303 | displayName: 'Schema (JSON)', 304 | name: 'schema', 305 | type: 'json', 306 | default: '{\n "type": "object",\n "properties": {},\n "required": []\n}', 307 | description: 'JSON Schema for tool parameters', 308 | }, 309 | ], 310 | }, 311 | ], 312 | }, 313 | { 314 | displayName: 'Options', 315 | name: 'options', 316 | type: 'collection', 317 | placeholder: 'Add Option', 318 | default: {}, 319 | options: [ 320 | { 321 | displayName: 'Return Full Log', 322 | name: 'returnFullLog', 323 | type: 'boolean', 324 | default: false, 325 | description: 'Whether to return the full execution log', 326 | }, 327 | { 328 | displayName: 'Answer Only', 329 | name: 'answerOnly', 330 | type: 'boolean', 331 | default: false, 332 | description: 333 | 'Whether to return only the answer text without metadata (useful for chat responses)', 334 | }, 335 | ], 336 | }, 337 | ], 338 | }; 339 | 340 | async execute(this: IExecuteFunctions): Promise { 341 | const items = this.getInputData(); 342 | const returnData: INodeExecutionData[] = []; 343 | 344 | // Get AI Language Model from input 345 | const aiModel = (await this.getInputConnectionData( 346 | NodeConnectionTypes.AiLanguageModel, 347 | 0, 348 | )) as N8nAiLanguageModel; 349 | 350 | if (!aiModel) { 351 | throw new NodeOperationError( 352 | this.getNode(), 353 | 'AI Language Model must be connected to the "Chat Model" input', 354 | ); 355 | } 356 | 357 | // Get connected AI Tools (like Tavily Search, MCP, LangChain tools, etc.) 358 | // Note: n8n automatically highlights tool nodes when they execute via call() 359 | const rawConnectedTools = (await this.getInputConnectionData(NodeConnectionTypes.AiTool, 0)) as 360 | | N8nAiTool[] 361 | | undefined; 362 | 363 | // Track session ID changes to clear memory when needed 364 | let lastSessionId: string | undefined; 365 | 366 | for (let itemIndex = 0; itemIndex < items.length; itemIndex++) { 367 | // Get log level configuration and create logger wrapper 368 | const logLevel = this.getNodeParameter('logLevel', itemIndex, 'error') as LogLevel; 369 | const logger = new ConfigurableLogger(this.logger, logLevel); 370 | 371 | // Log session ID and input data for debugging 372 | const sessionId = items[itemIndex].json.sessionId as string | undefined; 373 | logger.info(`🔑 Session ID: ${sessionId || 'NOT PROVIDED'}`); 374 | logger.debug(`📦 Input keys: ${Object.keys(items[itemIndex].json).join(', ')}`); 375 | 376 | // Get connected Memory (optional) - PER ITEM to support different session IDs 377 | // Memory node uses sessionId from $json.sessionId which can be different for each item 378 | const memory = (await this.getInputConnectionData( 379 | NodeConnectionTypes.AiMemory, 380 | itemIndex, 381 | )) as N8nAiMemory | undefined; 382 | 383 | if (memory) { 384 | logger.debug(`💾 Memory connected for this item`); 385 | 386 | // Check if session ID changed - if yes, clear memory for fresh start 387 | if (lastSessionId && sessionId && lastSessionId !== sessionId) { 388 | logger.info(`🔄 Session ID changed: ${lastSessionId} → ${sessionId}, clearing memory`); 389 | try { 390 | if (typeof memory.clear === 'function') { 391 | await memory.clear(); 392 | logger.info('🗑️ Memory cleared for new session'); 393 | } 394 | } catch (error) { 395 | logger.warn(`⚠️ Failed to clear memory: ${(error as Error).message}`); 396 | } 397 | } 398 | 399 | lastSessionId = sessionId; 400 | } else { 401 | logger.debug(`📭 No memory connected`); 402 | } 403 | 404 | try { 405 | // Check if this is a clarification response 406 | const clarificationAnswers = String( 407 | items[itemIndex].json.clarificationAnswers || 408 | items[itemIndex].json.clarification || 409 | items[itemIndex].json.answers || 410 | '', 411 | ); 412 | 413 | // Get task from input item (from Chat Trigger or previous node) 414 | // If clarification answers provided, task can be empty (will be restored from memory) 415 | const task = String( 416 | items[itemIndex].json.chatInput || 417 | items[itemIndex].json.input || 418 | items[itemIndex].json.message || 419 | items[itemIndex].json.text || 420 | items[itemIndex].json.task || 421 | '', 422 | ); 423 | 424 | // If no clarification answers, task is required 425 | if (!clarificationAnswers && !task) { 426 | throw new NodeOperationError( 427 | this.getNode(), 428 | 'No task found in input. Make sure the previous node provides chatInput, input, message, text, or task field.', 429 | ); 430 | } 431 | 432 | // Get parameters early for command processing 433 | const builtInTools = this.getNodeParameter('builtInTools', itemIndex, { 434 | enableReasoning: true, 435 | enableFinalAnswer: true, 436 | enableCreateReport: true, 437 | enableClarification: true, 438 | enableGeneratePlan: true, 439 | enableAdaptPlan: true, 440 | }) as BuiltInToolsConfig; 441 | const maxIterations = this.getNodeParameter('maxIterations', itemIndex) as number; 442 | const maxSearches = this.getNodeParameter('maxSearches', itemIndex) as number; 443 | const maxClarifications = this.getNodeParameter('maxClarifications', itemIndex) as number; 444 | const prompts = this.getNodeParameter('prompts', itemIndex, { 445 | systemPrompt: DEFAULT_SYSTEM_PROMPT, 446 | initialUserRequest: DEFAULT_INITIAL_USER_REQUEST, 447 | clarificationResponse: DEFAULT_CLARIFICATION_RESPONSE, 448 | }) as PromptsConfig; 449 | const additionalTools = this.getNodeParameter('additionalTools', itemIndex, { 450 | tools: [], 451 | }) as { tools: unknown[] }; 452 | const options = this.getNodeParameter('options', itemIndex, {}) as OptionsConfig; 453 | 454 | // Convert connected tools to internal format 455 | const connectedTools = rawConnectedTools 456 | ? convertN8nToolsToInternal(rawConnectedTools as unknown as N8nAITool[], logger).map( 457 | (tool) => createLoggedToolWrapper(tool, logger), 458 | ) 459 | : []; 460 | 461 | logger.info( 462 | `🔧 Converted ${connectedTools.length} external tools: ${connectedTools.map((t) => t.name).join(', ')}`, 463 | ); 464 | 465 | // Create agent configuration for commands 466 | const config: AgentConfig = { 467 | task: task || 'Continue research', // Use placeholder if clarification answers provided 468 | systemPrompt: prompts.systemPrompt || undefined, 469 | initialUserRequest: prompts.initialUserRequest || undefined, 470 | clarificationResponse: prompts.clarificationResponse || undefined, 471 | clarificationAnswers: clarificationAnswers || undefined, 472 | maxIterations, 473 | maxSearches, 474 | maxClarifications, 475 | builtInTools, 476 | additionalTools: (additionalTools.tools as AdditionalToolConfig[]) || [], 477 | connectedTools, 478 | memory: memory || undefined, 479 | logger, 480 | }; 481 | 482 | // Check for special commands 483 | const commandName = getCommandName(task); 484 | 485 | // Handle /help command 486 | if (commandName === 'help') { 487 | return handleHelpCommand(itemIndex, options.answerOnly || false); 488 | } 489 | 490 | // Handle /tools command 491 | if (commandName === 'tools') { 492 | return handleToolsCommand(this, config, aiModel, itemIndex, options.answerOnly || false); 493 | } 494 | 495 | // Handle /clear or /new command 496 | if (commandName === 'clear') { 497 | return await handleClearCommand(memory, logger, itemIndex, options.answerOnly || false); 498 | } 499 | 500 | // Handle clearMemory via JSON input (for compatibility) 501 | const shouldClearMemory = 502 | items[itemIndex].json.clearMemory === true || items[itemIndex].json.action === 'clear'; 503 | 504 | if (shouldClearMemory && memory) { 505 | try { 506 | if (typeof memory.clear === 'function') { 507 | await memory.clear(); 508 | logger.info('🗑️ Memory cleared for new session'); 509 | } 510 | } catch (error) { 511 | logger.warn(`⚠️ Failed to clear memory: ${(error as Error).message}`); 512 | } 513 | } 514 | 515 | // Create agent 516 | const agent = new ToolCallingAgent(this, config, aiModel); 517 | 518 | // Initialize agent (load memory if available) 519 | await agent.initialize(); 520 | 521 | // Execute agent 522 | await agent.execute(); 523 | 524 | // Save conversation to memory for next run 525 | await agent.saveToMemory(); 526 | 527 | // Get agent output 528 | const output = agent.getOutput() as IDataObject; 529 | 530 | // Filter output based on options 531 | if (!options.returnFullLog) { 532 | delete output.log; 533 | delete output.conversation; 534 | } 535 | 536 | // Return only answer text if answerOnly option is enabled 537 | if (options.answerOnly || false) { 538 | returnData.push({ 539 | json: { 540 | message: output.answer || output.final_message || '', 541 | }, 542 | pairedItem: itemIndex, 543 | }); 544 | } else { 545 | returnData.push({ 546 | json: output, 547 | pairedItem: itemIndex, 548 | }); 549 | } 550 | } catch (error) { 551 | if (this.continueOnFail()) { 552 | returnData.push({ 553 | json: { 554 | error: (error as Error).message, 555 | }, 556 | pairedItem: itemIndex, 557 | }); 558 | continue; 559 | } 560 | throw error; 561 | } 562 | } 563 | 564 | return [returnData]; 565 | } 566 | } 567 | -------------------------------------------------------------------------------- /nodes/SGR/core/toolConverter.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Universal Tool Converter for n8n AI Tools (LangChain, MCP, etc.) 3 | * Converts any n8n AI Tool to our internal tool format 4 | */ 5 | /* eslint-disable @typescript-eslint/ban-ts-comment */ 6 | // @ts-nocheck 7 | import type { Logger } from 'n8n-workflow'; 8 | 9 | export interface N8nAITool { 10 | name: string; 11 | description: string; 12 | schema?: Record | { parse?: (args: unknown) => unknown; [key: string]: unknown }; 13 | call?: (args: Record) => Promise; 14 | // LangChain DynamicTool interface 15 | func?: (input: string) => Promise; 16 | // LangChain Tool interface (wrapped by logWrapper) 17 | _call?: (query: string) => Promise; 18 | // Additional metadata 19 | [key: string]: unknown; 20 | } 21 | 22 | export interface ConvertedTool { 23 | name: string; 24 | description: string; 25 | schema: Record; 26 | call: (args: Record) => Promise; 27 | } 28 | 29 | /** 30 | * Normalize tool name to lowercase with underscores 31 | * Example: "MCP Client Tool" -> "mcp_client_tool" 32 | */ 33 | function normalizeToolName(name: string): string { 34 | if (!name) return 'unknown_tool'; 35 | 36 | return name 37 | .toLowerCase() 38 | .replace(/[^a-z0-9]+/g, '_') // Replace non-alphanumeric with underscore 39 | .replace(/^_+|_+$/g, '') // Remove leading/trailing underscores 40 | .replace(/_+/g, '_'); // Replace multiple underscores with single 41 | } 42 | 43 | /** 44 | * Extract JSON Schema from Zod schema 45 | * Zod schemas have _def property with the actual schema definition 46 | */ 47 | function extractSchemaFromZod(zodSchema: unknown, logger?: Logger): Record | null { 48 | if (!zodSchema || typeof zodSchema !== 'object') { 49 | return null; 50 | } 51 | 52 | // Check if it's a Zod schema with _def 53 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 54 | const schema = zodSchema as any; 55 | if (schema._def) { 56 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 57 | const def = schema._def as any; 58 | 59 | // For ZodEffects (wrapped schemas with transformations), unwrap to get the underlying schema 60 | if (def.typeName === 'ZodEffects' && def.schema) { 61 | logger?.debug('[extractSchemaFromZod] Unwrapping ZodEffects to extract underlying schema'); 62 | return extractSchemaFromZod(def.schema, logger); 63 | } 64 | 65 | // For ZodObject, extract shape 66 | if (def.typeName === 'ZodObject') { 67 | const shape = typeof def.shape === 'function' ? def.shape() : def.shape; 68 | 69 | if (!shape || Object.keys(shape).length === 0) { 70 | logger?.debug('[extractSchemaFromZod] ZodObject has empty shape, returning null'); 71 | return null; 72 | } 73 | 74 | const properties: Record = {}; 75 | const required: string[] = []; 76 | 77 | for (const [key, value] of Object.entries(shape)) { 78 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 79 | const fieldDef = (value as any)._def; 80 | 81 | // Extract field info 82 | const fieldSchema: Record = {}; 83 | 84 | // Determine type 85 | if (fieldDef.typeName === 'ZodString') { 86 | fieldSchema.type = 'string'; 87 | } else if (fieldDef.typeName === 'ZodNumber') { 88 | fieldSchema.type = 'number'; 89 | } else if (fieldDef.typeName === 'ZodBoolean') { 90 | fieldSchema.type = 'boolean'; 91 | } else if (fieldDef.typeName === 'ZodArray') { 92 | fieldSchema.type = 'array'; 93 | } else if (fieldDef.typeName === 'ZodObject') { 94 | fieldSchema.type = 'object'; 95 | } 96 | 97 | // Check if optional 98 | const isOptional = fieldDef.typeName === 'ZodOptional' || fieldDef.isOptional; 99 | if (!isOptional) { 100 | required.push(key); 101 | } 102 | 103 | // Add description if available 104 | if (fieldDef.description) { 105 | fieldSchema.description = fieldDef.description; 106 | } 107 | 108 | properties[key] = fieldSchema; 109 | } 110 | 111 | logger?.debug( 112 | `[extractSchemaFromZod] Extracted from ZodObject: ${JSON.stringify({ properties, required }, null, 2)}`, 113 | ); 114 | 115 | return { 116 | type: 'object', 117 | properties, 118 | required: required.length > 0 ? required : undefined, 119 | }; 120 | } 121 | } 122 | 123 | return null; 124 | } 125 | 126 | /** 127 | * Clean up schema by removing library-specific metadata fields 128 | * Removes Zod internal fields: _def, _cached, ~standard, etc. 129 | */ 130 | function cleanSchemaMetadata(schema: unknown, logger?: Logger): Record { 131 | if (!schema || typeof schema !== 'object') { 132 | return schema as Record; 133 | } 134 | 135 | // First, try to extract from Zod 136 | const zodExtracted = extractSchemaFromZod(schema, logger); 137 | if (zodExtracted) { 138 | return zodExtracted; 139 | } 140 | 141 | // List of metadata keys to remove (Zod, other libraries) 142 | const metadataKeys = ['_def', '_cached', '~standard', '_type', '_output', '_input', 'parse']; 143 | 144 | // Create clean copy without metadata 145 | const cleaned: Record = {}; 146 | for (const key in schema as Record) { 147 | if (!metadataKeys.includes(key) && !key.startsWith('_') && !key.startsWith('~')) { 148 | cleaned[key] = (schema as Record)[key]; 149 | } 150 | } 151 | 152 | // Recursively clean nested objects 153 | if (cleaned.properties && typeof cleaned.properties === 'object') { 154 | const cleanedProps: Record = {}; 155 | for (const prop in cleaned.properties as Record) { 156 | cleanedProps[prop] = cleanSchemaMetadata( 157 | (cleaned.properties as Record)[prop], 158 | logger, 159 | ); 160 | } 161 | cleaned.properties = cleanedProps; 162 | } 163 | 164 | // Clean items in arrays 165 | if (cleaned.items) { 166 | cleaned.items = cleanSchemaMetadata(cleaned.items, logger); 167 | } 168 | 169 | return cleaned; 170 | } 171 | 172 | /** 173 | * Validate and fix JSON Schema for OpenAI function calling 174 | * OpenAI requires schema to be 'type: object' 175 | * For Structured Outputs, adds strict mode and additionalProperties: false 176 | */ 177 | function validateAndFixSchema( 178 | schema: unknown, 179 | enableStrictMode: boolean = false, 180 | logger?: Logger, 181 | ): Record { 182 | // First, clean metadata fields 183 | const cleanedSchema = cleanSchemaMetadata(schema, logger); 184 | 185 | if (!cleanedSchema || Object.keys(cleanedSchema).length === 0) { 186 | return { 187 | type: 'object', 188 | properties: {}, 189 | additionalProperties: enableStrictMode ? false : undefined, 190 | }; 191 | } 192 | 193 | // If schema is not an object or doesn't have type, fix it 194 | if (typeof cleanedSchema !== 'object') { 195 | return { 196 | type: 'object', 197 | properties: {}, 198 | additionalProperties: enableStrictMode ? false : undefined, 199 | }; 200 | } 201 | 202 | // Fix invalid type values 203 | if ( 204 | cleanedSchema.type === 'None' || 205 | cleanedSchema.type === null || 206 | cleanedSchema.type === undefined 207 | ) { 208 | cleanedSchema.type = 'object'; 209 | } 210 | 211 | // Ensure it's type: object (OpenAI requirement) 212 | if (cleanedSchema.type !== 'object') { 213 | return { 214 | type: 'object', 215 | properties: { 216 | input: cleanedSchema, 217 | }, 218 | additionalProperties: enableStrictMode ? false : undefined, 219 | }; 220 | } 221 | 222 | // Ensure properties exist 223 | if (!cleanedSchema.properties) { 224 | cleanedSchema.properties = {}; 225 | } 226 | 227 | // Add additionalProperties: false for strict mode (OpenAI Structured Outputs) 228 | if (enableStrictMode && cleanedSchema.additionalProperties === undefined) { 229 | cleanedSchema.additionalProperties = false; 230 | } 231 | 232 | return cleanedSchema; 233 | } 234 | 235 | /** 236 | * Convert n8n AI Tool to our internal format 237 | */ 238 | export function convertN8nToolToInternal(tool: N8nAITool, logger?: Logger): ConvertedTool { 239 | logger?.debug(`[toolConverter] Converting tool: ${tool.name}`); 240 | logger?.debug(`[toolConverter] Has _call: ${!!tool._call}`); 241 | logger?.debug(`[toolConverter] Has call: ${!!tool.call}`); 242 | logger?.debug(`[toolConverter] Has func: ${!!tool.func}`); 243 | logger?.debug(`[toolConverter] Has invoke: ${!!('invoke' in tool)}`); 244 | logger?.debug(`[toolConverter] Has getTools: ${!!('getTools' in tool)}`); 245 | 246 | // Case 1: LangChain Tool wrapped by logWrapper (has _call method) 247 | // This is the most common case for n8n built-in tools like Calculator, Code Tool, etc. 248 | // IMPORTANT: Check if it's also a DynamicStructuredTool (has both _call and func with Zod schema) 249 | // MCP tools are wrapped by logWrapper, so they have _call, but also have func and schema 250 | if (tool._call && typeof tool._call === 'function') { 251 | // Check if this is a wrapped DynamicStructuredTool (MCP tools) 252 | const hasFunc = tool.func && typeof tool.func === 'function'; 253 | const hasZodSchema = 254 | tool.schema && 255 | typeof tool.schema === 'object' && 256 | ('_def' in tool.schema || 'parse' in tool.schema); 257 | 258 | logger?.debug(`[toolConverter] Tool ${tool.name} has _call method`); 259 | logger?.debug(`[toolConverter] Also has func: ${hasFunc}`); 260 | logger?.debug(`[toolConverter] Also has Zod schema: ${hasZodSchema}`); 261 | 262 | // If it has both _call and func with Zod schema, it's a wrapped DynamicStructuredTool 263 | if (hasFunc && hasZodSchema) { 264 | logger?.debug(`[toolConverter] -> Treating as wrapped DynamicStructuredTool (MCP tool)`); 265 | const toolName = normalizeToolName(tool.name); 266 | 267 | const extractedSchema = validateAndFixSchema(tool.schema, false, logger); 268 | logger?.debug( 269 | `[toolConverter] Extracted schema:`, 270 | JSON.stringify(extractedSchema, null, 2), 271 | ); 272 | 273 | return { 274 | name: toolName, 275 | description: tool.description || 'No description provided', 276 | schema: extractedSchema, 277 | call: async (args: Record) => { 278 | // Debug: log what we're about to call the tool with 279 | logger?.debug(`[toolConverter] Calling wrapped DynamicStructuredTool ${toolName}:`); 280 | logger?.debug(`[toolConverter] args: ${JSON.stringify(args, null, 2)}`); 281 | 282 | // IMPORTANT: Don't use _call! The logWrapper's _call expects a string. 283 | // Instead, use func or invoke which expect objects for DynamicStructuredTool 284 | if (tool.func) { 285 | logger?.debug(`[toolConverter] Using tool.func (bypassing logWrapper)`); 286 | 287 | // Call tool.func directly without Zod validation 288 | // The tool's internal implementation will handle validation 289 | // Zod validation can be too strict (e.g., strict mode rejects extra fields) 290 | // while our JSON schema might allow them 291 | return await tool.func!(args); 292 | } else if ('invoke' in tool && typeof tool.invoke === 'function') { 293 | logger?.debug(`[toolConverter] Using tool.invoke`); 294 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 295 | return await (tool as any).invoke(args); 296 | } else { 297 | // Fallback to _call (shouldn't happen for MCP tools) 298 | logger?.debug(`[toolConverter] WARNING: Falling back to _call (may fail)`); 299 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 300 | return await tool._call!(args as any); 301 | } 302 | }, 303 | }; 304 | } 305 | 306 | // Regular tool with _call that expects string input 307 | logger?.debug(`[toolConverter] -> Treating as regular string-based tool`); 308 | logger?.debug(`[toolConverter] Original schema: ${JSON.stringify(tool.schema, null, 2)}`); 309 | 310 | // Determine the appropriate default schema based on tool name 311 | let defaultSchema = { 312 | type: 'object', 313 | properties: { 314 | input: { 315 | type: 'string', 316 | description: 'Tool input', 317 | }, 318 | }, 319 | required: ['input'], 320 | }; 321 | 322 | // Calculator-specific schema 323 | if (tool.name && tool.name.toLowerCase().includes('calculator')) { 324 | defaultSchema = { 325 | type: 'object', 326 | properties: { 327 | input: { 328 | type: 'string', 329 | description: 'A mathematical expression to evaluate (e.g., "2+2", "10*5", "sqrt(16)")', 330 | }, 331 | }, 332 | required: ['input'], 333 | }; 334 | } 335 | 336 | // First, try to extract schema from tool.schema (if it's Zod) 337 | let extractedSchema = tool.schema ? validateAndFixSchema(tool.schema, false, logger) : null; 338 | 339 | // If extracted schema is empty (no properties), use default schema 340 | if ( 341 | !extractedSchema || 342 | !extractedSchema.properties || 343 | Object.keys(extractedSchema.properties).length === 0 344 | ) { 345 | logger?.debug(`[toolConverter] Extracted schema is empty, using default schema`); 346 | extractedSchema = defaultSchema; 347 | } 348 | 349 | const finalSchema = extractedSchema; 350 | logger?.debug(`[toolConverter] Final schema: ${JSON.stringify(finalSchema, null, 2)}`); 351 | 352 | return { 353 | name: normalizeToolName(tool.name), 354 | description: tool.description || 'No description provided', 355 | schema: finalSchema, 356 | call: async (args: Record) => { 357 | logger?.debug(`[toolConverter] Calling regular _call tool: ${tool.name}`); 358 | logger?.debug(`[toolConverter] args: ${JSON.stringify(args, null, 2)}`); 359 | logger?.debug(`[toolConverter] args keys:`, Object.keys(args)); 360 | 361 | // LangChain tools wrapped by logWrapper expect string input 362 | // Try to extract the actual query/expression from args 363 | let input: string; 364 | 365 | if (typeof args === 'string') { 366 | input = args; 367 | } else if (args.input && typeof args.input === 'string') { 368 | input = args.input; 369 | } else if (args.query && typeof args.query === 'string') { 370 | input = args.query; 371 | } else if (args.expression && typeof args.expression === 'string') { 372 | input = args.expression; 373 | } else if (args.question && typeof args.question === 'string') { 374 | input = args.question; 375 | } else { 376 | // If we can't find a string field, use the first string value or JSON stringify 377 | const firstStringValue = Object.values(args).find((v) => typeof v === 'string'); 378 | input = (firstStringValue as string) || JSON.stringify(args); 379 | } 380 | 381 | logger?.debug(`[toolConverter] Extracted input:`, input); 382 | const result = await tool._call!(input); 383 | logger?.debug(`[toolConverter] Result:`, result); 384 | return result; 385 | }, 386 | }; 387 | } 388 | 389 | // Case 2: Tool has call method (custom n8n AI tools) 390 | if (tool.name && tool.description && tool.call && typeof tool.call === 'function') { 391 | return { 392 | name: normalizeToolName(tool.name), 393 | description: tool.description, 394 | schema: validateAndFixSchema(tool.schema, false, logger), // schema can be undefined 395 | call: tool.call, 396 | }; 397 | } 398 | 399 | // Case 3: LangChain DynamicTool format (has func instead of call) 400 | // This includes both DynamicTool (string input) and DynamicStructuredTool (object input) 401 | if (tool.func && typeof tool.func === 'function') { 402 | // Check if it's a DynamicStructuredTool (has Zod schema that expects object) 403 | // MCP tools from @n8n/n8n-nodes-langchain.mcpClientTool use DynamicStructuredTool 404 | // They have Zod schemas and expect object arguments, not strings 405 | const hasZodSchema = 406 | tool.schema && 407 | typeof tool.schema === 'object' && 408 | ('_def' in tool.schema || 'parse' in tool.schema); 409 | 410 | logger?.debug(`[toolConverter] Converting tool with func: ${tool.name}`); 411 | logger?.debug(`[toolConverter] Has schema: ${!!tool.schema}`); 412 | logger?.debug(`[toolConverter] Schema type: ${typeof tool.schema}`); 413 | logger?.debug(`[toolConverter] Has _def: ${tool.schema && '_def' in tool.schema}`); 414 | logger?.debug(`[toolConverter] Has parse: ${tool.schema && 'parse' in tool.schema}`); 415 | logger?.debug(`[toolConverter] Is structured tool: ${hasZodSchema}`); 416 | 417 | const isStructuredTool = hasZodSchema; 418 | 419 | if (isStructuredTool) { 420 | // DynamicStructuredTool - func expects object, not string 421 | // MCP tools and other structured tools with Zod schemas 422 | const zodSchema = tool.schema as { parse?: (args: unknown) => unknown }; 423 | const toolName = normalizeToolName(tool.name); 424 | 425 | return { 426 | name: toolName, 427 | description: tool.description || 'No description provided', 428 | schema: validateAndFixSchema(tool.schema, false, logger), 429 | call: async (args: Record) => { 430 | // Debug: log what we're about to call the tool with 431 | logger?.debug(`[toolConverter] DynamicStructuredTool ${toolName}:`); 432 | logger?.debug(`[toolConverter] args type: ${typeof args}`); 433 | logger?.debug(`[toolConverter] args keys: ${Object.keys(args).join(', ')}`); 434 | logger?.debug(`[toolConverter] args value: ${JSON.stringify(args, null, 2)}`); 435 | 436 | // If schema has parse method (Zod), validate/transform args 437 | let validatedArgs = args; 438 | if (zodSchema.parse && typeof zodSchema.parse === 'function') { 439 | try { 440 | logger?.debug(`[toolConverter] Validating with Zod schema...`); 441 | validatedArgs = zodSchema.parse(args) as Record; 442 | logger?.debug(`[toolConverter] Validation successful`); 443 | } catch (error) { 444 | logger?.debug(`[toolConverter] Validation failed:`, error); 445 | // If validation fails, try to pass args as-is 446 | // Some tools might be more lenient 447 | validatedArgs = args; 448 | } 449 | } 450 | 451 | // Pass args directly as object 452 | logger?.debug( 453 | `[toolConverter] Calling tool.func with: ${JSON.stringify(validatedArgs, null, 2)}`, 454 | ); 455 | return await tool.func!(validatedArgs); 456 | }, 457 | }; 458 | } 459 | 460 | // Regular DynamicTool - func expects string input 461 | return { 462 | name: normalizeToolName(tool.name), 463 | description: tool.description || 'No description provided', 464 | schema: validateAndFixSchema( 465 | tool.schema || { 466 | type: 'object', 467 | properties: { 468 | input: { 469 | type: 'string', 470 | description: 'Tool input', 471 | }, 472 | }, 473 | required: ['input'], 474 | }, 475 | ), 476 | call: async (args: Record) => { 477 | // LangChain tools expect string input 478 | const input = typeof args === 'string' ? args : args.input || JSON.stringify(args); 479 | return await tool.func!(input as string); 480 | }, 481 | }; 482 | } 483 | 484 | // Case 4: MCP Toolkit format (from McpClientTool) 485 | // McpToolkit wraps multiple tools, need to extract individual tools 486 | if ('getTools' in tool && typeof (tool as { getTools?: () => unknown }).getTools === 'function') { 487 | // This is a toolkit, not a single tool 488 | // Will be handled by the caller 489 | throw new Error('Toolkit detected, should be unwrapped before conversion'); 490 | } 491 | 492 | // Case 5: Generic tool with invoke method 493 | if ( 494 | 'invoke' in tool && 495 | typeof (tool as { invoke?: (args: unknown) => unknown }).invoke === 'function' 496 | ) { 497 | return { 498 | name: normalizeToolName(tool.name || 'unknown_tool'), 499 | description: tool.description || 'No description provided', 500 | schema: validateAndFixSchema( 501 | tool.schema || { 502 | type: 'object', 503 | properties: { 504 | input: { 505 | type: 'string', 506 | description: 'Tool input', 507 | }, 508 | }, 509 | required: ['input'], 510 | }, 511 | ), 512 | call: async (args: Record) => { 513 | return await (tool as { invoke: (args: unknown) => Promise }).invoke(args); 514 | }, 515 | }; 516 | } 517 | 518 | // Fallback: wrap the tool as-is 519 | return { 520 | name: normalizeToolName(tool.name || 'unknown_tool'), 521 | description: tool.description || 'No description provided', 522 | schema: validateAndFixSchema( 523 | tool.schema || { 524 | type: 'object', 525 | properties: {}, 526 | }, 527 | ), 528 | call: async (args: Record) => { 529 | // Try to call the tool if it has a call method 530 | if (tool.call) { 531 | return await tool.call(args); 532 | } 533 | // Otherwise return error 534 | throw new Error(`Tool ${tool.name} does not have a callable method`); 535 | }, 536 | }; 537 | } 538 | 539 | /** 540 | * Convert array of n8n AI Tools to internal format 541 | * Handles toolkits that contain multiple tools 542 | */ 543 | export function convertN8nToolsToInternal(tools: N8nAITool[], logger?: Logger): ConvertedTool[] { 544 | const convertedTools: ConvertedTool[] = []; 545 | 546 | for (const tool of tools) { 547 | // Check if it's a toolkit (has getTools method) 548 | if ( 549 | 'getTools' in tool && 550 | typeof (tool as { getTools?: () => unknown }).getTools === 'function' 551 | ) { 552 | // Extract individual tools from toolkit 553 | const toolkitTools = (tool as { getTools: () => unknown }).getTools(); 554 | if (Array.isArray(toolkitTools)) { 555 | for (const subTool of toolkitTools) { 556 | try { 557 | convertedTools.push(convertN8nToolToInternal(subTool, logger)); 558 | } catch { 559 | // Skip tools that fail conversion - will be logged by caller 560 | } 561 | } 562 | } 563 | } else { 564 | // Convert single tool 565 | try { 566 | convertedTools.push(convertN8nToolToInternal(tool, logger)); 567 | } catch { 568 | // Skip tools that fail conversion - will be logged by caller 569 | } 570 | } 571 | } 572 | 573 | return convertedTools; 574 | } 575 | 576 | /** 577 | * Safely stringify and truncate data for logging 578 | */ 579 | function safeStringify(data: unknown, maxLength: number = 500): string { 580 | try { 581 | const str = typeof data === 'string' ? data : JSON.stringify(data, null, 2); 582 | if (str.length <= maxLength) { 583 | return str; 584 | } 585 | return str.substring(0, maxLength) + `... (truncated, total length: ${str.length})`; 586 | } catch (error) { 587 | return `[Unable to stringify: ${(error as Error).message}]`; 588 | } 589 | } 590 | 591 | /** 592 | * Create a wrapper for n8n connected tools that logs execution 593 | */ 594 | export function createLoggedToolWrapper(tool: ConvertedTool, logger: Logger): ConvertedTool { 595 | const originalCall = tool.call; 596 | 597 | return { 598 | ...tool, 599 | call: async (args: Record) => { 600 | logger.debug(`🔧 Calling external tool: ${tool.name}`); 601 | logger.debug(` Tool schema type: ${tool.schema?.type || 'unknown'}`); 602 | logger.debug(` Arguments (type): ${typeof args}`); 603 | logger.debug(` Arguments (full):\n${safeStringify(args, 1000)}`); 604 | 605 | try { 606 | const result = await originalCall(args); 607 | logger.debug(` ✅ Tool ${tool.name} completed successfully`); 608 | logger.debug(` Result type: ${typeof result}`); 609 | logger.debug(` Result (preview):\n${safeStringify(result, 500)}`); 610 | return result; 611 | } catch (error) { 612 | const errorMessage = (error as Error).message || String(error); 613 | const errorStack = (error as Error).stack || ''; 614 | 615 | logger.error(` ❌ Tool ${tool.name} failed`); 616 | logger.error(` Error message: ${errorMessage}`); 617 | if (errorStack) { 618 | logger.error(` Error stack:\n${errorStack}`); 619 | } 620 | 621 | // Log full error object for debugging 622 | logger.error(` Full error:\n${safeStringify(error, 1000)}`); 623 | 624 | throw error; 625 | } 626 | }, 627 | }; 628 | } 629 | -------------------------------------------------------------------------------- /nodes/SGR/agents/BaseAgent.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Base Agent class 3 | * Port of BaseAgent from sgr-agent-core Python project 4 | */ 5 | /* eslint-disable @typescript-eslint/ban-ts-comment */ 6 | // @ts-nocheck 7 | import { NodeOperationError, type IExecuteFunctions, type Logger } from 'n8n-workflow'; 8 | import { AgentContext } from '../core/context'; 9 | import type { Message, Tool, AIModelResponse } from '../types'; 10 | import { AgentState } from '../types'; 11 | import { 12 | DEFAULT_SYSTEM_PROMPT, 13 | DEFAULT_INITIAL_USER_REQUEST, 14 | DEFAULT_CLARIFICATION_RESPONSE, 15 | formatPrompt, 16 | getCurrentDate, 17 | } from '../prompts'; 18 | 19 | export interface AdditionalToolConfig { 20 | toolName: string; 21 | description: string; 22 | schema: Record; 23 | } 24 | 25 | export interface ConnectedN8nTool { 26 | name: string; 27 | description: string; 28 | schema?: Record; 29 | call: (args: Record) => Promise; 30 | } 31 | 32 | export interface BuiltInToolsConfig { 33 | enableReasoning?: boolean; 34 | enableFinalAnswer?: boolean; 35 | enableCreateReport?: boolean; 36 | enableClarification?: boolean; 37 | enableGeneratePlan?: boolean; 38 | enableAdaptPlan?: boolean; 39 | } 40 | 41 | export interface AgentConfig { 42 | task: string; 43 | systemPrompt?: string; 44 | initialUserRequest?: string; 45 | clarificationResponse?: string; 46 | clarificationAnswers?: string; // User's answers to clarification questions 47 | maxIterations: number; 48 | maxSearches: number; 49 | maxClarifications: number; 50 | builtInTools?: BuiltInToolsConfig; 51 | additionalTools?: AdditionalToolConfig[]; 52 | connectedTools?: ConnectedN8nTool[]; 53 | memory?: { 54 | getChatMessages?: () => Promise; 55 | addMessage?: (message: unknown) => Promise; 56 | clear?: () => Promise; 57 | [key: string]: unknown; 58 | }; // n8n Memory instance for conversation caching 59 | logger?: Logger; // Configurable logger 60 | } 61 | 62 | export abstract class BaseAgent { 63 | protected executeFunctions: IExecuteFunctions; 64 | protected context: AgentContext; 65 | protected config: AgentConfig; 66 | protected conversation: Message[]; 67 | protected aiModel: { invoke: (messages: unknown[]) => Promise; [key: string]: unknown }; 68 | protected memory?: { 69 | getChatMessages?: () => Promise; 70 | addMessage?: (message: unknown) => Promise; 71 | clear?: () => Promise; 72 | [key: string]: unknown; 73 | }; 74 | protected logger: Logger; 75 | private loadedMessagesCount: number = 0; // Track how many messages were loaded from memory 76 | 77 | constructor( 78 | executeFunctions: IExecuteFunctions, 79 | config: AgentConfig, 80 | aiModel: { invoke: (messages: unknown[]) => Promise; [key: string]: unknown }, 81 | ) { 82 | this.executeFunctions = executeFunctions; 83 | this.config = config; 84 | this.context = new AgentContext(); 85 | this.conversation = []; 86 | this.aiModel = aiModel; 87 | this.memory = config.memory; 88 | this.logger = config.logger || executeFunctions.logger; 89 | } 90 | 91 | /** 92 | * Initialize agent - load memory if available 93 | * Must be called before execute() 94 | */ 95 | async initialize(): Promise { 96 | let previousMessages: Message[] = []; 97 | 98 | // Load previous conversation from memory if available 99 | if (this.memory) { 100 | try { 101 | // LangChain BufferWindowMemory interface: loadMemoryVariables returns messages 102 | if (typeof this.memory.loadMemoryVariables === 'function') { 103 | const memoryVars = await this.memory.loadMemoryVariables({}); 104 | const chatHistory = memoryVars.chat_history || memoryVars.history || []; 105 | 106 | if (Array.isArray(chatHistory) && chatHistory.length > 0) { 107 | previousMessages = (chatHistory as unknown[]).map((msg) => { 108 | // Handle different message formats 109 | const msgType = 110 | typeof msg._getType === 'function' ? msg._getType() : msg.type || msg.role; 111 | return { 112 | role: msgType === 'human' || msgType === 'user' ? 'user' : 'assistant', 113 | content: msg.content || msg.text || '', 114 | }; 115 | }); 116 | this.loadedMessagesCount = previousMessages.length; 117 | this.logger.info(`📥 Loaded ${previousMessages.length} messages from memory`); 118 | } 119 | } else if (typeof this.memory.getChatMessages === 'function') { 120 | // Alternative interface (some memory types) 121 | const chatHistory = await this.memory.getChatMessages(); 122 | if (chatHistory && chatHistory.length > 0) { 123 | previousMessages = (chatHistory as unknown[]).map((msg) => ({ 124 | role: 125 | msg._getType() === 'human' 126 | ? 'user' 127 | : msg._getType() === 'ai' 128 | ? 'assistant' 129 | : msg._getType(), 130 | content: msg.content, 131 | })); 132 | this.loadedMessagesCount = previousMessages.length; 133 | this.logger.info(`📥 Loaded ${previousMessages.length} messages from memory`); 134 | } 135 | } else { 136 | // Memory doesn't have expected methods, skip loading 137 | this.logger.debug('Memory node connected but does not support expected interface'); 138 | } 139 | } catch (error) { 140 | this.logger.warn(`⚠️ Failed to load memory: ${(error as Error).message}`); 141 | } 142 | } 143 | 144 | // Check if this is a clarification response (user providing answers) 145 | if (this.config.clarificationAnswers) { 146 | this.logger.info('▶️ Resuming from clarification with user answers'); 147 | 148 | // Load the conversation from memory - it should contain the full context including clarification 149 | // The conversation is already loaded in previousMessages above 150 | 151 | // Replace the current task with clarification response 152 | const clarificationResponseTemplate = 153 | this.config.clarificationResponse || DEFAULT_CLARIFICATION_RESPONSE; 154 | const formattedClarificationResponse = formatPrompt(clarificationResponseTemplate, { 155 | current_date: getCurrentDate(), 156 | clarifications: this.config.clarificationAnswers, 157 | }); 158 | 159 | // Initialize conversation with system prompt only 160 | const systemPrompt = this.config.systemPrompt || DEFAULT_SYSTEM_PROMPT; 161 | const tools = this.prepareTools(); 162 | const availableToolsStr = tools 163 | .map((tool, index) => `${index + 1}. ${tool.function.name}: ${tool.function.description}`) 164 | .join('\n'); 165 | 166 | const formattedSystemPrompt = formatPrompt(systemPrompt, { 167 | available_tools: availableToolsStr, 168 | }); 169 | 170 | // Build conversation: [system, ...previous (includes clarification), user_answers] 171 | this.conversation = [ 172 | { 173 | role: 'system', 174 | content: formattedSystemPrompt, 175 | }, 176 | ...previousMessages, 177 | { 178 | role: 'user', 179 | content: formattedClarificationResponse, 180 | }, 181 | ]; 182 | 183 | // Reset state from WAITING_FOR_CLARIFICATION to RESEARCHING 184 | this.context.state = AgentState.RESEARCHING; 185 | 186 | this.logger.debug('📋 Conversation resumed with clarification answers'); 187 | return; 188 | } 189 | 190 | // Normal initialization - new task 191 | // Always initialize with system prompt and current task 192 | this.initializeConversation(); 193 | 194 | // Add previous messages after system prompt but before current task 195 | if (previousMessages.length > 0) { 196 | // Insert previous messages between system prompt and current user request 197 | // Structure: [system, ...previous, current_user_request] 198 | const systemPrompt = this.conversation[0]; // system 199 | const currentUserRequest = this.conversation[1]; // current task 200 | this.conversation = [systemPrompt, ...previousMessages, currentUserRequest]; 201 | this.logger.debug( 202 | `📋 Conversation structure: system + ${previousMessages.length} previous + current request`, 203 | ); 204 | } 205 | } 206 | 207 | /** 208 | * Initialize conversation with system prompt and task 209 | */ 210 | protected initializeConversation(): void { 211 | const systemPrompt = this.config.systemPrompt || DEFAULT_SYSTEM_PROMPT; 212 | const initialUserRequest = this.config.initialUserRequest || DEFAULT_INITIAL_USER_REQUEST; 213 | 214 | // Prepare tools list for system prompt (similar to Python's PromptLoader.get_system_prompt) 215 | const tools = this.prepareTools(); 216 | const availableToolsStr = tools 217 | .map((tool, index) => `${index + 1}. ${tool.function.name}: ${tool.function.description}`) 218 | .join('\n'); 219 | 220 | // Format system prompt 221 | const formattedSystemPrompt = formatPrompt(systemPrompt, { 222 | available_tools: availableToolsStr, 223 | }); 224 | 225 | // Format initial user request 226 | const formattedUserRequest = formatPrompt(initialUserRequest, { 227 | current_date: getCurrentDate(), 228 | task: this.config.task, 229 | }); 230 | 231 | this.conversation = [ 232 | { 233 | role: 'system', 234 | content: formattedSystemPrompt, 235 | }, 236 | { 237 | role: 'user', 238 | content: formattedUserRequest, 239 | }, 240 | ]; 241 | } 242 | 243 | /** 244 | * Main execution loop - to be implemented by subclasses 245 | */ 246 | abstract execute(itemIndex: number): Promise; 247 | 248 | /** 249 | * Prepare tools for the current iteration 250 | * Should filter based on limits and agent state 251 | */ 252 | protected abstract prepareTools(): Tool[]; 253 | 254 | /** 255 | * Call AI model with current conversation and tools 256 | */ 257 | protected async callAIModel( 258 | tools: Tool[], 259 | toolChoice?: { type: 'function'; function: { name: string } }, 260 | ): Promise { 261 | try { 262 | // Prepare the options for n8n AI model 263 | const options: Record = {}; 264 | 265 | if (tools.length > 0) { 266 | options.tools = tools; 267 | if (toolChoice) { 268 | options.tool_choice = toolChoice; 269 | } else { 270 | options.tool_choice = 'auto'; 271 | } 272 | } 273 | 274 | // Log what we're sending 275 | this.logger.debug( 276 | `Calling AI model with ${this.conversation.length} messages, ${tools.length} tools`, 277 | ); 278 | 279 | // Normalize messages to OpenAI format for the AI model 280 | const normalizedMessages = this.conversation.map((msg) => { 281 | const normalized: Record = { 282 | role: msg.role, 283 | }; 284 | 285 | // Add content - use empty string if null for assistant messages with tool_calls 286 | if (msg.content !== null && msg.content !== undefined) { 287 | normalized.content = msg.content; 288 | } else if (msg.role === 'tool') { 289 | // Tool messages must have content 290 | normalized.content = msg.content || ''; 291 | } else if (msg.role === 'assistant' && msg.tool_calls && msg.tool_calls.length > 0) { 292 | // Assistant messages with tool_calls can have null content, but some models prefer empty string 293 | normalized.content = ''; 294 | } else { 295 | // For other cases, use empty string 296 | normalized.content = msg.content || ''; 297 | } 298 | 299 | // Add tool_calls only if they exist and are properly formatted 300 | if (msg.tool_calls && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) { 301 | // Normalize tool calls to OpenAI format 302 | normalized.tool_calls = msg.tool_calls.map((tc) => { 303 | // If already in OpenAI format 304 | if (tc.function) { 305 | return tc; 306 | } 307 | // If in n8n format, convert to OpenAI format 308 | if (tc.name) { 309 | return { 310 | id: tc.id, 311 | type: 'function', 312 | function: { 313 | name: tc.name, 314 | arguments: typeof tc.args === 'string' ? tc.args : JSON.stringify(tc.args), 315 | }, 316 | }; 317 | } 318 | return tc; 319 | }); 320 | } 321 | 322 | // Add tool result fields if present 323 | if (msg.tool_call_id) { 324 | normalized.tool_call_id = msg.tool_call_id; 325 | } 326 | if (msg.name) { 327 | normalized.name = msg.name; 328 | } 329 | 330 | return normalized; 331 | }); 332 | 333 | // Call the AI model using n8n's invoke method 334 | const response = await this.aiModel.invoke(normalizedMessages, options); 335 | 336 | // Validate response structure 337 | if (!response) { 338 | throw new Error('Empty response from AI model'); 339 | } 340 | 341 | // Extract tool calls - they might be in different formats depending on the model 342 | let toolCalls = []; 343 | if (response.tool_calls && Array.isArray(response.tool_calls)) { 344 | toolCalls = response.tool_calls; 345 | } else if (response.additional_kwargs?.tool_calls) { 346 | toolCalls = response.additional_kwargs.tool_calls; 347 | } else if (response.message?.tool_calls) { 348 | toolCalls = response.message.tool_calls; 349 | } 350 | 351 | // Log response structure for debugging 352 | this.logger.debug( 353 | `AI Response: content=${!!response.content}, tool_calls=${toolCalls.length}, response_keys=${Object.keys(response || {}).join(',')}`, 354 | ); 355 | 356 | return { 357 | content: response.content || response.text || null, 358 | tool_calls: toolCalls, 359 | }; 360 | } catch (error) { 361 | const errorMessage = error instanceof Error ? error.message : String(error); 362 | const errorStack = error instanceof Error ? error.stack : ''; 363 | 364 | this.logger.error(`AI Model error: ${errorMessage}`); 365 | if (errorStack) { 366 | this.logger.debug(`Error stack: ${errorStack}`); 367 | } 368 | 369 | throw new NodeOperationError( 370 | this.executeFunctions.getNode(), 371 | `AI Model error: ${errorMessage}`, 372 | ); 373 | } 374 | } 375 | 376 | /** 377 | * Execute a tool by name 378 | * Can be overridden by subclasses to handle system tools 379 | */ 380 | protected abstract executeTool( 381 | toolName: string, 382 | toolArgs: Record, 383 | ): Promise; 384 | 385 | /** 386 | * Add assistant message to conversation 387 | */ 388 | protected addAssistantMessage(content: string | null, toolCalls?: unknown[]): void { 389 | const message: Message = { 390 | role: 'assistant', 391 | content, 392 | }; 393 | 394 | // Only add tool_calls if they exist and are not empty 395 | if (toolCalls && Array.isArray(toolCalls) && toolCalls.length > 0) { 396 | message.tool_calls = toolCalls as unknown as Message['tool_calls']; 397 | } 398 | 399 | this.conversation.push(message); 400 | } 401 | 402 | /** 403 | * Add tool result to conversation 404 | */ 405 | protected addToolResult(toolCallId: string, toolName: string, result: string): void { 406 | this.conversation.push({ 407 | role: 'tool', 408 | content: typeof result === 'string' ? result : JSON.stringify(result), 409 | tool_call_id: toolCallId, 410 | name: toolName, 411 | }); 412 | } 413 | 414 | /** 415 | * Get final output 416 | */ 417 | public getOutput(): Record { 418 | const lastMessage = this.conversation[this.conversation.length - 1]; 419 | let finalContent = ''; 420 | let answer = ''; 421 | 422 | // Check if we're waiting for clarification 423 | if (this.context.state === AgentState.WAITING_FOR_CLARIFICATION) { 424 | // Find the clarification tool result 425 | let clarificationQuestions = ''; 426 | 427 | // Search backwards through conversation for clarification tool result 428 | for (let i = this.conversation.length - 1; i >= 0; i--) { 429 | const msg = this.conversation[i]; 430 | if (msg.role === 'tool' && msg.name?.toLowerCase().includes('clarification')) { 431 | clarificationQuestions = msg.content || ''; 432 | break; 433 | } 434 | } 435 | 436 | // Extract tool usage summary from execution log 437 | const toolCalls = this.context.executionLog.filter((entry) => entry.type === 'tool_call'); 438 | const toolsSummary = toolCalls.map((entry) => ({ 439 | iteration: entry.iteration, 440 | tool: entry.tool, 441 | timestamp: entry.timestamp, 442 | })); 443 | 444 | return { 445 | task: this.config.task, 446 | state: this.context.state, 447 | iterations: this.context.iteration, 448 | clarification_needed: true, 449 | clarification_questions: clarificationQuestions, 450 | answer: clarificationQuestions, // For compatibility with existing output format 451 | final_message: '⏸️ Waiting for clarification from user', 452 | tools_used: toolsSummary, 453 | log: this.context.executionLog, 454 | conversation: this.conversation, 455 | }; 456 | } 457 | 458 | // Check if a custom final answer tool was used 459 | // Look for the last tool call in execution log that is a final answer tool 460 | const toolCalls = this.context.executionLog.filter((entry) => entry.type === 'tool_call'); 461 | const lastToolCall = toolCalls.length > 0 ? toolCalls[toolCalls.length - 1] : null; 462 | 463 | if (lastToolCall) { 464 | const toolName = lastToolCall.tool; 465 | const isCustomFinalAnswerTool = 466 | toolName !== 'final_answer_tool' && // Not the built-in one 467 | (toolName.toLowerCase().includes('final') || toolName.toLowerCase().includes('answer')) && 468 | lastToolCall.arguments; 469 | 470 | // If custom final answer tool was used, return only its arguments 471 | if (isCustomFinalAnswerTool) { 472 | this.logger.info( 473 | `📤 Custom final answer tool detected: ${toolName}. Returning tool arguments directly.`, 474 | ); 475 | return lastToolCall.arguments as Record; 476 | } 477 | } 478 | 479 | // Normal flow - try to extract answer from the last tool result 480 | if (lastMessage.role === 'tool') { 481 | const toolResult = lastMessage.content; 482 | // Try to parse JSON from tool result 483 | try { 484 | const parsed = JSON.parse(toolResult || '{}'); 485 | // Check for answer in create_report_tool or final_answer_tool 486 | if (parsed.content) { 487 | answer = parsed.content; 488 | } else if (parsed.answer) { 489 | answer = parsed.answer; 490 | } 491 | } catch { 492 | // If not JSON, use as is 493 | answer = toolResult || ''; 494 | } 495 | 496 | finalContent = 497 | this.conversation 498 | .slice() 499 | .reverse() 500 | .find((m) => m.role === 'assistant')?.content || ''; 501 | } else { 502 | finalContent = lastMessage.content || ''; 503 | } 504 | 505 | // Extract tool usage summary from execution log 506 | const toolsSummary = toolCalls.map((entry) => ({ 507 | iteration: entry.iteration, 508 | tool: entry.tool, 509 | timestamp: entry.timestamp, 510 | })); 511 | 512 | return { 513 | task: this.config.task, 514 | state: this.context.state, 515 | iterations: this.context.iteration, 516 | final_message: finalContent, 517 | answer: answer || finalContent, // The actual answer/report 518 | tools_used: toolsSummary, // Summary of all tools used 519 | log: this.context.executionLog, 520 | conversation: this.conversation, 521 | }; 522 | } 523 | 524 | /** 525 | * Save conversation to memory including clarification questions 526 | * This is called when clarification_tool is invoked 527 | */ 528 | async saveClarificationToMemory(): Promise { 529 | if (!this.memory) return; 530 | 531 | try { 532 | // Get the original user question from config 533 | const userQuestion = this.config.task; 534 | if (!userQuestion) { 535 | this.logger.debug(`📭 No user question to save`); 536 | return; 537 | } 538 | 539 | // Find clarification questions from tool result 540 | let clarificationQuestions = ''; 541 | for (let i = this.conversation.length - 1; i >= 0; i--) { 542 | const msg = this.conversation[i]; 543 | if (msg.role === 'tool' && msg.name?.toLowerCase().includes('clarification')) { 544 | clarificationQuestions = msg.content || ''; 545 | break; 546 | } 547 | } 548 | 549 | if (!clarificationQuestions) { 550 | this.logger.debug(`📭 No clarification questions found`); 551 | return; 552 | } 553 | 554 | // LangChain BufferWindowMemory interface 555 | if (typeof this.memory.saveContext === 'function') { 556 | // Save as: User question -> Clarification questions 557 | // This preserves the conversation flow for when user provides answers 558 | await this.memory.saveContext({ input: userQuestion }, { output: clarificationQuestions }); 559 | } else if ( 560 | this.memory.chatHistory && 561 | typeof this.memory.chatHistory.addMessage === 'function' 562 | ) { 563 | // Alternative interface with chatHistory.addMessage 564 | await this.memory.chatHistory.addMessage({ 565 | content: userQuestion, 566 | role: 'human', 567 | }); 568 | await this.memory.chatHistory.addMessage({ 569 | content: clarificationQuestions, 570 | role: 'ai', 571 | }); 572 | } else { 573 | this.logger.debug('Memory node does not support expected save interface'); 574 | return; 575 | } 576 | 577 | this.logger.info( 578 | `💾 Saved conversation with clarification to memory:\n User: ${userQuestion.substring(0, 50)}...\n Questions: ${clarificationQuestions.substring(0, 100)}...`, 579 | ); 580 | } catch (error) { 581 | this.logger.warn(`⚠️ Failed to save clarification to memory: ${(error as Error).message}`); 582 | } 583 | } 584 | 585 | /** 586 | * Save conversation to memory 587 | * Only saves NEW messages that were added after loading from memory 588 | */ 589 | async saveToMemory(): Promise { 590 | if (!this.memory) return; 591 | 592 | // Don't save to memory if waiting for clarification 593 | if (this.context.state === AgentState.WAITING_FOR_CLARIFICATION) { 594 | this.logger.debug( 595 | `⏸️ Not saving to memory - waiting for clarification (already saved via saveClarificationToMemory)`, 596 | ); 597 | return; 598 | } 599 | 600 | try { 601 | // Get only NEW messages (skip those loaded from memory) 602 | const allMessages = this.conversation.filter( 603 | (msg) => msg.role === 'user' || msg.role === 'assistant', 604 | ); 605 | const newMessages = allMessages.slice(this.loadedMessagesCount); 606 | 607 | if (newMessages.length === 0) { 608 | this.logger.debug(`📭 No new messages to save to memory`); 609 | return; 610 | } 611 | 612 | // Get the clean user question from config.task (original user input) 613 | // Don't use the formatted message which includes system prompts and dates 614 | const userQuestionText = this.config.task; 615 | if (!userQuestionText) { 616 | this.logger.debug(`📭 No user question found to save`); 617 | return; 618 | } 619 | 620 | // Extract final answer using same logic as getOutput() 621 | // Look for answer in the last tool result (final_answer_tool or create_report_tool) 622 | let finalAnswer = ''; 623 | const lastMessage = this.conversation[this.conversation.length - 1]; 624 | 625 | if (lastMessage.role === 'tool') { 626 | const toolResult = lastMessage.content; 627 | try { 628 | const parsed = JSON.parse(toolResult || '{}'); 629 | // Check for answer in create_report_tool or final_answer_tool 630 | if (parsed.content) { 631 | finalAnswer = parsed.content; 632 | } else if (parsed.answer) { 633 | finalAnswer = parsed.answer; 634 | } 635 | } catch { 636 | // If not JSON, try to find last assistant message 637 | finalAnswer = toolResult || ''; 638 | } 639 | } 640 | 641 | // If no answer from tool, try to get from assistant messages 642 | if (!finalAnswer) { 643 | for (let i = this.conversation.length - 1; i >= 0; i--) { 644 | if (this.conversation[i].role === 'assistant' && this.conversation[i].content) { 645 | finalAnswer = this.conversation[i].content!; 646 | break; 647 | } 648 | } 649 | } 650 | 651 | // If no final answer yet, don't save (agent still working) 652 | if (!finalAnswer) { 653 | this.logger.debug(`📭 No final answer yet, skipping memory save (agent still working)`); 654 | return; 655 | } 656 | 657 | // LangChain BufferWindowMemory interface: saveContext(input, output) 658 | if (typeof this.memory.saveContext === 'function') { 659 | // Save only the clean user question and final answer 660 | await this.memory.saveContext({ input: userQuestionText }, { output: finalAnswer }); 661 | } else if ( 662 | this.memory.chatHistory && 663 | typeof this.memory.chatHistory.addMessage === 'function' 664 | ) { 665 | // Alternative interface with chatHistory.addMessage 666 | // Save only clean user question and final answer 667 | await this.memory.chatHistory.addMessage({ 668 | content: userQuestionText, 669 | role: 'human', 670 | }); 671 | await this.memory.chatHistory.addMessage({ content: finalAnswer, role: 'ai' }); 672 | } else { 673 | this.logger.debug('Memory node does not support expected save interface'); 674 | return; 675 | } 676 | 677 | this.logger.info( 678 | `💾 Saved conversation to memory: question + final answer (${this.loadedMessagesCount} previous messages cached)`, 679 | ); 680 | } catch (error) { 681 | this.logger.warn(`⚠️ Failed to save to memory: ${(error as Error).message}`); 682 | } 683 | } 684 | 685 | /** 686 | * Get conversation history 687 | */ 688 | public getConversation(): Message[] { 689 | return this.conversation; 690 | } 691 | 692 | /** 693 | * Get agent context 694 | */ 695 | public getContext(): AgentContext { 696 | return this.context; 697 | } 698 | } 699 | -------------------------------------------------------------------------------- /nodes/SGR/agents/ToolCallingAgent.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Tool Calling Agent 3 | * Port of ToolCallingResearchAgent from sgr-agent-core Python project 4 | */ 5 | /* eslint-disable @typescript-eslint/ban-ts-comment */ 6 | // @ts-nocheck 7 | 8 | import { BaseAgent } from './BaseAgent'; 9 | import type { Tool, ToolCall } from '../types'; 10 | import { AgentState } from '../types'; 11 | import { 12 | reasoningTool, 13 | finalAnswerTool, 14 | createReportTool, 15 | createReportToolWithContext, 16 | clarificationTool, 17 | generatePlanTool, 18 | adaptPlanTool, 19 | } from '../tools'; 20 | 21 | interface ReasoningResult { 22 | reasoning: string; 23 | completed_steps: string[]; 24 | remaining_steps: string[]; 25 | status: string; 26 | } 27 | 28 | export class ToolCallingAgent extends BaseAgent { 29 | /** 30 | * Main execution loop - Two phase approach: 31 | * 1. Reasoning phase - force reasoning tool to get agent's plan 32 | * 2. Action selection phase - let agent choose which tool to use 33 | */ 34 | async execute(): Promise { 35 | this.logger.info('🚀 SGR Agent execution started'); 36 | this.logger.info(`📋 Task: ${this.config.task.substring(0, 100)}...`); 37 | this.logger.info( 38 | `⚙️ Config: maxIterations=${this.config.maxIterations}, maxSearches=${this.config.maxSearches}, maxClarifications=${this.config.maxClarifications}`, 39 | ); 40 | 41 | // Main agent loop 42 | while (!this.context.isFinished() && this.context.iteration < this.config.maxIterations) { 43 | this.context.iteration += 1; 44 | 45 | this.logger.info(`\n${'='.repeat(60)}`); 46 | this.logger.info(`🔄 Iteration ${this.context.iteration}/${this.config.maxIterations}`); 47 | this.logger.info( 48 | `📊 Stats: searches=${this.context.searches_used}/${this.config.maxSearches}, clarifications=${this.context.clarifications_used}/${this.config.maxClarifications}`, 49 | ); 50 | this.logger.info(`${'='.repeat(60)}`); 51 | 52 | // Phase 1: Reasoning phase 53 | this.logger.info(`\n🧠 Phase 1: Reasoning`); 54 | const reasoning = await this.reasoningPhase(); 55 | 56 | // Check if agent decided to complete 57 | if (this.isCompletionStatus(reasoning.status)) { 58 | this.logger.info(`✅ Agent decided to complete with status: ${reasoning.status}`); 59 | this.context.complete(); 60 | break; 61 | } 62 | 63 | // Phase 2: Action selection phase 64 | this.logger.info(`\n🎯 Phase 2: Action Selection`); 65 | await this.actionSelectionPhase(reasoning); 66 | 67 | // Check if max iterations reached 68 | if (this.context.iteration >= this.config.maxIterations) { 69 | this.logger.warn(`⚠️ Max iterations (${this.config.maxIterations}) reached`); 70 | this.context.maxIterationsReached(); 71 | } 72 | } 73 | 74 | this.logger.info(`\n${'='.repeat(60)}`); 75 | this.logger.info(`🏁 SGR Agent execution finished`); 76 | this.logger.info(`📈 Final state: ${this.context.state}`); 77 | this.logger.info(`🔢 Total iterations: ${this.context.iteration}`); 78 | this.logger.info(`${'='.repeat(60)}\n`); 79 | } 80 | 81 | /** 82 | * Phase 1: Reasoning phase 83 | * Forces the agent to use reasoning tool to think about the task 84 | */ 85 | private async reasoningPhase(): Promise { 86 | // Prepare tools with reasoning tool highlighted 87 | const availableTools = this.prepareTools(); 88 | this.logger.info(` 📦 Available tools: ${availableTools.length}`); 89 | 90 | const reasoningTool = availableTools.find((t) => 91 | t.function?.name?.toLowerCase().includes('reasoning'), 92 | ); 93 | 94 | // If we have a dedicated reasoning tool, force it 95 | let response; 96 | if (reasoningTool) { 97 | this.logger.info(` 🎯 Forcing reasoning tool: ${reasoningTool.function.name}`); 98 | response = await this.callAIModelWithToolChoice(availableTools, reasoningTool.function.name); 99 | } else { 100 | this.logger.info(` 🤖 Calling AI with all tools`); 101 | response = await this.callAIModel(availableTools); 102 | } 103 | 104 | // Debug log the response 105 | this.logger.debug( 106 | ` 🔍 Response structure: ${JSON.stringify({ hasContent: !!response.content, toolCallsCount: response.tool_calls?.length || 0 })}`, 107 | ); 108 | 109 | if (response.tool_calls && response.tool_calls.length > 0) { 110 | this.logger.debug( 111 | ` 🔍 First tool call structure: ${JSON.stringify(response.tool_calls[0])}`, 112 | ); 113 | } 114 | 115 | // Add assistant message to conversation 116 | this.addAssistantMessage(response.content || null, response.tool_calls); 117 | 118 | // Process the reasoning tool call 119 | if (response.tool_calls && response.tool_calls.length > 0) { 120 | const toolCall = response.tool_calls[0]; 121 | 122 | // Normalize tool call structure - support both OpenAI format and n8n format 123 | let toolName: string; 124 | let toolArgs: Record; 125 | 126 | if (toolCall.function) { 127 | // OpenAI format: {function: {name, arguments}, id} 128 | toolName = toolCall.function.name; 129 | try { 130 | toolArgs = 131 | typeof toolCall.function.arguments === 'string' 132 | ? JSON.parse(toolCall.function.arguments) 133 | : toolCall.function.arguments; 134 | } catch { 135 | toolArgs = toolCall.function.arguments as Record; 136 | } 137 | } else if (toolCall.name) { 138 | // n8n format: {name, args, type, id} 139 | toolName = toolCall.name; 140 | toolArgs = (toolCall.args || {}) as Record; 141 | } else { 142 | this.logger.error('❌ Invalid tool call structure received from AI model'); 143 | this.logger.error(` Tool call object: ${JSON.stringify(toolCall)}`); 144 | throw new Error('Invalid tool call structure received from AI model'); 145 | } 146 | 147 | this.logger.info(` 🔧 Tool called: ${toolName}`); 148 | 149 | // Log reasoning details 150 | if (toolArgs.current_situation) { 151 | this.logger.info(` 💭 Situation: ${toolArgs.current_situation.substring(0, 100)}...`); 152 | } 153 | if (toolArgs.remaining_steps && toolArgs.remaining_steps.length > 0) { 154 | this.logger.info(` 📝 Next steps: ${toolArgs.remaining_steps.join(', ')}`); 155 | } 156 | if (toolArgs.task_completed !== undefined) { 157 | this.logger.info(` ✓ Task completed: ${toolArgs.task_completed}`); 158 | } 159 | 160 | // Log reasoning 161 | this.context.logToolCall(toolName, toolArgs); 162 | 163 | // Execute tool to get result 164 | const toolResult = await this.executeTool(toolName, toolArgs); 165 | 166 | // Add tool result to conversation 167 | this.addToolResult(toolCall.id, toolName, toolResult); 168 | 169 | // Log result 170 | this.context.logToolResult(toolName, toolResult); 171 | 172 | return toolArgs as ReasoningResult; 173 | } 174 | 175 | // Fallback if no reasoning provided 176 | this.logger.warn(` ⚠️ No reasoning tool call, using fallback`); 177 | return { 178 | reasoning: 'Continue with task', 179 | completed_steps: [], 180 | remaining_steps: ['Continue working on the task'], 181 | status: 'RESEARCHING', 182 | }; 183 | } 184 | 185 | /** 186 | * Phase 2: Action selection phase 187 | * Let the agent choose which tool to use based on the reasoning 188 | */ 189 | private async actionSelectionPhase(reasoning: ReasoningResult): Promise { 190 | // Prepare available tools based on limits 191 | const availableTools = this.prepareTools(); 192 | this.logger.info(` 📦 Available tools: ${availableTools.length}`); 193 | 194 | // Call AI Model with tool calling 195 | // Note: Using "auto" instead of "required" for better compatibility 196 | this.logger.info(` 🤖 Calling AI model for action selection...`); 197 | const response = await this.callAIModel(availableTools); 198 | 199 | // Handle case where LLM returned text instead of tool call 200 | // Similar to Python's _select_action_phase handling 201 | if (!response.tool_calls || response.tool_calls.length === 0) { 202 | this.logger.info(` 💬 LLM returned text response instead of tool call`); 203 | const finalContent = response.content || 'Task completed successfully'; 204 | 205 | // Create a synthetic FinalAnswerTool call 206 | const syntheticToolCall = { 207 | id: `${this.context.iteration}-synthetic-final`, 208 | type: 'function' as const, 209 | function: { 210 | name: 'final_answer_tool', 211 | arguments: JSON.stringify({ 212 | reasoning: 'Agent decided to complete the task', 213 | completed_steps: [finalContent], 214 | status: 'COMPLETED', 215 | }), 216 | }, 217 | }; 218 | 219 | this.addAssistantMessage(finalContent, [syntheticToolCall]); 220 | await this.processToolCalls([syntheticToolCall]); 221 | return; 222 | } 223 | 224 | // Add assistant message to conversation 225 | const messageContent = 226 | reasoning.remaining_steps && reasoning.remaining_steps.length > 0 227 | ? reasoning.remaining_steps[0] 228 | : 'Completing task'; 229 | this.addAssistantMessage(messageContent, response.tool_calls); 230 | 231 | // Process tool calls 232 | this.logger.info(` 🔧 Processing ${response.tool_calls.length} tool call(s)`); 233 | await this.processToolCalls(response.tool_calls); 234 | } 235 | 236 | /** 237 | * Check if status indicates completion 238 | */ 239 | private isCompletionStatus(status: string | undefined): boolean { 240 | if (!status) return false; 241 | const completionStatuses = ['COMPLETED', 'FAILED', 'DONE', 'FINISHED']; 242 | return completionStatuses.includes(status.toUpperCase()); 243 | } 244 | 245 | /** 246 | * Call AI model with specific tool choice 247 | */ 248 | private async callAIModelWithToolChoice( 249 | tools: Tool[], 250 | toolName: string, 251 | ): Promise { 252 | try { 253 | const toolChoice = { 254 | type: 'function' as const, 255 | function: { name: toolName }, 256 | }; 257 | return await this.callAIModel(tools, toolChoice); 258 | } catch { 259 | // If forcing tool choice fails, fall back to regular call 260 | return await this.callAIModel(tools); 261 | } 262 | } 263 | 264 | /** 265 | * Execute a tool - handle built-in tools, connected n8n tools and additional tools 266 | */ 267 | protected async executeTool( 268 | toolName: string, 269 | toolArgs: Record, 270 | ): Promise { 271 | // Check if it's a built-in tool 272 | // Use contextual version of createReportTool for access to sources 273 | const contextualCreateReportTool = createReportToolWithContext(this.context, this.logger); 274 | 275 | const builtInToolsMap: Record< 276 | string, 277 | { call: (args: Record) => Promise } 278 | > = { 279 | [reasoningTool.name]: reasoningTool, 280 | [finalAnswerTool.name]: finalAnswerTool, 281 | [createReportTool.name]: contextualCreateReportTool, 282 | [clarificationTool.name]: clarificationTool, 283 | [generatePlanTool.name]: generatePlanTool, 284 | [adaptPlanTool.name]: adaptPlanTool, 285 | }; 286 | 287 | const builtInTool = builtInToolsMap[toolName]; 288 | if (builtInTool) { 289 | try { 290 | const result = await builtInTool.call(toolArgs); 291 | return typeof result === 'string' ? result : JSON.stringify(result, null, 2); 292 | } catch (error) { 293 | this.logger.error( 294 | ` ❌ Built-in tool execution failed: ${(error as Error).message}`, 295 | ); 296 | return JSON.stringify({ 297 | error: `Failed to execute ${toolName}: ${(error as Error).message}`, 298 | }); 299 | } 300 | } 301 | 302 | // Check if it's a connected n8n tool 303 | const connectedTool = this.config.connectedTools?.find((t) => t.name === toolName); 304 | if (connectedTool) { 305 | this.logger.info(`\n ${'═'.repeat(50)}`); 306 | this.logger.info(` 🔧 EXECUTING TOOL: ${toolName.toUpperCase()}`); 307 | this.logger.info(` ${'═'.repeat(50)}`); 308 | this.logger.debug(` 📋 Tool arguments: ${JSON.stringify(toolArgs)}`); 309 | 310 | // Send UI notification about tool execution 311 | try { 312 | this.executeFunctions.sendMessageToUI(`🔧 Executing tool: ${toolName}`); 313 | } catch { 314 | // Ignore if sendMessageToUI is not available 315 | } 316 | 317 | try { 318 | const result = await connectedTool.call(toolArgs); 319 | 320 | this.logger.info(` ✅ TOOL COMPLETED: ${toolName.toUpperCase()}`); 321 | this.logger.info(` ${'═'.repeat(50)}\n`); 322 | 323 | // Increment searches counter if it's a search tool 324 | if ( 325 | toolName.toLowerCase().includes('search') || 326 | toolName.toLowerCase().includes('tavily') 327 | ) { 328 | this.context.incrementSearches(); 329 | this.logger.info(` 🔍 Search count incremented: ${this.context.searches_used}`); 330 | 331 | // Try to extract sources from search results (for Tavily Search Tool) 332 | const formattedResult = this.extractAndStoreSources(result, toolArgs); 333 | if (formattedResult) { 334 | // Return formatted text for AI model instead of full JSON 335 | return formattedResult; 336 | } 337 | } 338 | return typeof result === 'string' ? result : JSON.stringify(result, null, 2); 339 | } catch (error) { 340 | this.logger.error(` ❌ Tool execution failed: ${(error as Error).message}`); 341 | return JSON.stringify({ 342 | error: `Failed to execute ${toolName}: ${(error as Error).message}`, 343 | }); 344 | } 345 | } 346 | 347 | // Check if it's an additional custom tool 348 | const additionalTool = this.config.additionalTools?.find((t) => t.toolName === toolName); 349 | if (additionalTool) { 350 | this.logger.debug(` 🔹 Executing additional custom tool: ${toolName}`); 351 | // For additional tools, we just return the arguments as JSON 352 | // In real implementation, this would call an external API or function 353 | return JSON.stringify({ 354 | tool: toolName, 355 | args: toolArgs, 356 | message: 'Additional tool executed (implement custom logic here)', 357 | }); 358 | } 359 | 360 | this.logger.error(` ❌ Tool not found: ${toolName}`); 361 | throw new Error(`Tool ${toolName} not found`); 362 | } 363 | 364 | /** 365 | * Process tool calls from AI response 366 | */ 367 | private async processToolCalls(toolCalls: ToolCall[]): Promise { 368 | for (let i = 0; i < toolCalls.length; i++) { 369 | const toolCall = toolCalls[i]; 370 | 371 | // Normalize tool call structure - support both OpenAI format and n8n format 372 | let toolName: string; 373 | let toolArgs: Record; 374 | let toolCallId: string; 375 | 376 | if (toolCall.function) { 377 | // OpenAI format: {function: {name, arguments}, id} 378 | if (!toolCall.function.name) { 379 | this.logger.warn(` ⚠️ Tool call ${i + 1}: Missing function name, skipping`); 380 | continue; 381 | } 382 | toolName = toolCall.function.name; 383 | toolCallId = toolCall.id; 384 | try { 385 | toolArgs = 386 | typeof toolCall.function.arguments === 'string' 387 | ? JSON.parse(toolCall.function.arguments) 388 | : toolCall.function.arguments; 389 | } catch { 390 | toolArgs = toolCall.function.arguments as Record; 391 | this.logger.warn(` ⚠️ Failed to parse arguments`); 392 | } 393 | } else if (toolCall.name) { 394 | // n8n format: {name, args, type, id} 395 | toolName = toolCall.name; 396 | toolArgs = (toolCall.args || {}) as Record; 397 | toolCallId = toolCall.id; 398 | } else { 399 | this.logger.warn(` ⚠️ Tool call ${i + 1}: Invalid structure, skipping`); 400 | continue; 401 | } 402 | 403 | this.logger.info(`\n ${'━'.repeat(60)}`); 404 | this.logger.info(` 🔧 Tool call ${i + 1}/${toolCalls.length}: ${toolName}`); 405 | 406 | // Log key arguments 407 | if (toolArgs && typeof toolArgs === 'object') { 408 | const argKeys = Object.keys(toolArgs); 409 | if (argKeys.length > 0) { 410 | this.logger.info(` 📋 Arguments: ${argKeys.join(', ')}`); 411 | } 412 | this.logger.debug(` 📋 Full arguments JSON: ${JSON.stringify(toolArgs)}`); 413 | } 414 | 415 | // Log tool call 416 | this.context.logToolCall(toolName, toolArgs); 417 | 418 | // Execute tool 419 | this.logger.info(` ⚙️ Executing...`); 420 | const startTime = Date.now(); 421 | const toolResult = await this.executeTool(toolName, toolArgs); 422 | const duration = Date.now() - startTime; 423 | 424 | this.logger.info(` ✓ Completed in ${duration}ms`); 425 | this.logger.info(` 📤 Result: ${toolResult.substring(0, 100)}...`); 426 | 427 | // Update context based on tool name patterns 428 | this.updateContextForTool(toolName); 429 | 430 | // Add tool result to conversation 431 | this.addToolResult(toolCallId, toolName, toolResult); 432 | 433 | // Log tool result 434 | this.context.logToolResult(toolName, toolResult); 435 | 436 | // Check if clarification tool was called - stop execution and wait for user response 437 | if (toolName.toLowerCase().includes('clarification')) { 438 | this.logger.info('\n⏸️ Research paused - waiting for clarification from user'); 439 | this.context.state = AgentState.WAITING_FOR_CLARIFICATION; 440 | 441 | // Save conversation history to memory including clarification questions 442 | await this.saveClarificationToMemory(); 443 | 444 | this.context.complete(); // Mark as complete to exit main loop 445 | return; // Exit processToolCalls immediately 446 | } 447 | } 448 | } 449 | 450 | /** 451 | * Update context counters based on tool usage 452 | */ 453 | private updateContextForTool(toolName: string): void { 454 | const lowerName = toolName.toLowerCase(); 455 | 456 | if (lowerName.includes('search')) { 457 | this.context.incrementSearches(); 458 | } else if (lowerName.includes('clarification')) { 459 | this.context.incrementClarifications(); 460 | } else if (lowerName.includes('final') || lowerName.includes('answer')) { 461 | this.context.complete(); 462 | } 463 | } 464 | 465 | /** 466 | * Prepare tools with filters based on current limits 467 | * Mimics Python's _prepare_tools logic 468 | */ 469 | protected prepareTools(): Tool[] { 470 | const tools: Tool[] = []; 471 | const builtInTools = this.config.builtInTools || {}; 472 | 473 | // Add built-in tools based on configuration 474 | const maxIterationsReached = this.context.iteration >= this.config.maxIterations; 475 | const searchLimitReached = this.context.searches_used >= this.config.maxSearches; 476 | const clarificationLimitReached = 477 | this.context.clarifications_used >= this.config.maxClarifications; 478 | 479 | // Check if custom final answer tool is connected 480 | // If custom final answer tool is connected, automatically disable built-in finalAnswer and clarification 481 | const allConnectedTools = this.config.connectedTools || []; 482 | const hasCustomFinalAnswerTool = allConnectedTools.some( 483 | (t) => 484 | t.name.toLowerCase().includes('final_answer') || 485 | t.name.toLowerCase().includes('finalanswer') || 486 | t.name === 'custom_final_answer_tool', 487 | ); 488 | 489 | if (hasCustomFinalAnswerTool) { 490 | this.logger.info( 491 | '🔧 Custom Final Answer Tool detected - automatically disabling built-in Final Answer and Clarification tools', 492 | ); 493 | } 494 | 495 | // Reasoning tool - always available if enabled 496 | if (builtInTools.enableReasoning !== false) { 497 | tools.push({ 498 | type: 'function' as const, 499 | function: { 500 | name: reasoningTool.name, 501 | description: reasoningTool.description, 502 | parameters: reasoningTool.schema, 503 | }, 504 | }); 505 | } 506 | 507 | // Final Answer tool - available if enabled and no custom final answer tool is connected 508 | if (builtInTools.enableFinalAnswer !== false && !hasCustomFinalAnswerTool) { 509 | tools.push({ 510 | type: 'function' as const, 511 | function: { 512 | name: finalAnswerTool.name, 513 | description: finalAnswerTool.description, 514 | parameters: finalAnswerTool.schema, 515 | }, 516 | }); 517 | } 518 | 519 | // Create Report tool - always available if enabled 520 | if (builtInTools.enableCreateReport !== false) { 521 | tools.push({ 522 | type: 'function' as const, 523 | function: { 524 | name: createReportTool.name, 525 | description: createReportTool.description, 526 | parameters: createReportTool.schema, 527 | }, 528 | }); 529 | } 530 | 531 | // If max iterations reached, only return completion tools 532 | if (maxIterationsReached) { 533 | // Add connected tools (like search) 534 | const connectedToolsFormatted: Tool[] = (this.config.connectedTools || []).map((t) => ({ 535 | type: 'function' as const, 536 | function: { 537 | name: t.name, 538 | description: t.description, 539 | parameters: t.schema || { 540 | type: 'object', 541 | properties: {}, 542 | }, 543 | }, 544 | })); 545 | 546 | return [...tools, ...connectedToolsFormatted]; 547 | } 548 | 549 | // Clarification tool - available if enabled, limit not reached, and no custom final answer tool 550 | if ( 551 | builtInTools.enableClarification !== false && 552 | !clarificationLimitReached && 553 | !hasCustomFinalAnswerTool 554 | ) { 555 | tools.push({ 556 | type: 'function' as const, 557 | function: { 558 | name: clarificationTool.name, 559 | description: clarificationTool.description, 560 | parameters: clarificationTool.schema, 561 | }, 562 | }); 563 | } 564 | 565 | // Generate Plan tool - available if enabled 566 | if (builtInTools.enableGeneratePlan !== false) { 567 | tools.push({ 568 | type: 'function' as const, 569 | function: { 570 | name: generatePlanTool.name, 571 | description: generatePlanTool.description, 572 | parameters: generatePlanTool.schema, 573 | }, 574 | }); 575 | } 576 | 577 | // Adapt Plan tool - available if enabled 578 | if (builtInTools.enableAdaptPlan !== false) { 579 | tools.push({ 580 | type: 'function' as const, 581 | function: { 582 | name: adaptPlanTool.name, 583 | description: adaptPlanTool.description, 584 | parameters: adaptPlanTool.schema, 585 | }, 586 | }); 587 | } 588 | 589 | // Add connected n8n tools (like Tavily Search) 590 | let connectedTools = this.config.connectedTools || []; 591 | 592 | // Remove search tools if limit reached 593 | if (searchLimitReached) { 594 | connectedTools = connectedTools.filter( 595 | (t) => !t.name.toLowerCase().includes('search') && !t.name.toLowerCase().includes('tavily'), 596 | ); 597 | } 598 | 599 | // Convert to OpenAI function format 600 | const connectedToolsFormatted: Tool[] = connectedTools.map((t) => { 601 | const toolDef = { 602 | type: 'function' as const, 603 | function: { 604 | name: t.name, 605 | description: t.description, 606 | parameters: t.schema || { 607 | type: 'object', 608 | properties: {}, 609 | }, 610 | }, 611 | }; 612 | 613 | // Log tool definition for debugging 614 | this.logger.debug(`[prepareTools] Connected tool: ${t.name}`); 615 | this.logger.debug(` Schema: ${JSON.stringify(toolDef.function.parameters, null, 2)}`); 616 | 617 | return toolDef; 618 | }); 619 | 620 | // Add additional custom tools from config 621 | const additionalTools: Tool[] = 622 | this.config.additionalTools?.map((t) => ({ 623 | type: 'function' as const, 624 | function: { 625 | name: t.toolName, 626 | description: t.description, 627 | parameters: t.schema, 628 | }, 629 | })) || []; 630 | 631 | return [...tools, ...connectedToolsFormatted, ...additionalTools]; 632 | } 633 | 634 | /** 635 | * Extract sources from search tool results and store them in context 636 | * Similar to Python's TavilySearchService behavior 637 | * Returns formatted text for AI model, or undefined if no sources were extracted 638 | */ 639 | private extractAndStoreSources( 640 | result: string | object, 641 | toolArgs: Record, 642 | ): string | undefined { 643 | try { 644 | // Try to parse result as JSON 645 | const resultString = typeof result === 'string' ? result : JSON.stringify(result); 646 | const parsed = JSON.parse(resultString); 647 | 648 | // Check if result contains sources metadata (from our modified SgrTavilySearchTool) 649 | if (parsed.sources && Array.isArray(parsed.sources)) { 650 | const query = parsed.query || (toolArgs.query as string) || ''; 651 | 652 | // Add sources to context 653 | let addedCount = 0; 654 | for (const source of parsed.sources) { 655 | if (source.url) { 656 | // Calculate next source number based on existing sources 657 | const nextNumber = this.context.sources.size + 1; 658 | const sourceData = { 659 | number: nextNumber, 660 | title: source.title || 'Untitled', 661 | url: source.url, 662 | snippet: source.snippet || '', 663 | full_content: source.full_content || '', 664 | char_count: source.char_count || 0, 665 | }; 666 | 667 | this.context.addSource(source.url, sourceData); 668 | addedCount++; 669 | } 670 | } 671 | 672 | this.logger.info( 673 | ` 📚 Added ${addedCount} sources to context (total: ${this.context.sources.size})`, 674 | ); 675 | 676 | // Add search result to context 677 | if (query) { 678 | const searchResult = { 679 | query, 680 | answer: parsed.answer || '', 681 | citations: parsed.sources || [], 682 | timestamp: new Date().toISOString(), 683 | }; 684 | this.context.addSearch(searchResult); 685 | this.logger.debug(` 📝 Recorded search: "${query}"`); 686 | } 687 | 688 | // Return formatted text for AI model (if available) 689 | if (parsed.formatted) { 690 | return parsed.formatted; 691 | } 692 | } 693 | } catch { 694 | // If parsing fails, it's probably not a JSON result - that's okay 695 | this.logger.debug( 696 | ` ℹ️ Could not extract sources from result (not JSON or no sources field)`, 697 | ); 698 | } 699 | 700 | return undefined; 701 | } 702 | } 703 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------