feat: agent changes#799
Conversation
There was a problem hiding this comment.
Pull request overview
This PR extends the "create agent" flow to leverage AI-generated configuration when a purpose field is supplied. It also enriches the AI prompt context with available API call tools and folder embed fields so the AI can produce a fully pre-configured agent.
Changes:
- AI-context enrichment: When
purposeis provided, available API call functions (tools) and folder embed fields are now fetched and included as variables sent to the AI middleware. - AI-driven agent creation: The AI response is used directly as the agent configuration (model, service, name, fall_back, gpt_memory, etc.) instead of extracting a small subset of fields as before.
- Minor cleanup: Removed an extraneous blank line in
aiCall.utils.js.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 7 comments.
| File | Description |
|---|---|
src/controllers/agentConfig.controller.js |
Core logic change: fetches API call tools, passes enriched variables to AI, and uses the full AI response to populate the createAgent call when purpose is set. |
src/services/utils/aiCall.utils.js |
Trivial whitespace removal (blank line deleted). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
ccd5a51 to
7faf054
Compare
|
add validation in it we cannot believe on the agent reponse |
dda4560 to
14bd711
Compare
Husainbw786
left a comment
There was a problem hiding this comment.
Code Review - PR #799
General Observations
This PR adds AI-powered agent configuration generation with new tools/fields context and restructures the configuration model with proper schemas.
Issues & Suggestions
1. Hardcoded version_id (Critical)
// aiCall.utils.js:35
requestBody.version_id = "699fd583a7ad6f86eb736a1e";2. Variable naming inconsistency (Minor)
// Line 97
const functions = await apiCallService.getAllApiCallsByOrgId(...);
// Line 100
tools: functions.map((tools) => { ... })The variable is named functions but the callback parameter is tools. Suggest:
tools: functions.map((fn) => ({
id: fn._id,
description: fn.description
}))3. Potential null reference (Bug Risk)
// Line 103-110
fields: folder_data
? folder_data?.config?.prompt?.embedFields
?.filter((field) => !field.hidden)
...If folder_data is truthy but embedFields is undefined, the ?.filter() returns undefined, then the ?.reduce() fails. Consider:
fields: folder_data?.config?.prompt?.embedFields
?.filter((field) => !field.hidden)
?.reduce((acc, field) => {
acc[field.name] = field.value || "";
return acc;
}, {}) || { role: "", goal: "", instruction: "" }(Simplified - no need for outer ternary)
4. Typo fixed ✅
Good catch fixing "accroding" → "according" on line 114.
5. Repeated ternary logic (DRY opportunity)
Lines 221-228 repeat purpose ? agent_data?.X || default : default pattern multiple times. Consider:
const useAiData = purpose && agent_data;
const getValue = (aiVal, defaultVal) => useAiData ? (aiVal ?? defaultVal) : defaultVal;
const result = await ConfigurationServices.createAgent({
...(useAiData ? agent_data : {}),
configuration: getValue(agent_data?.configuration, model_data),
name: getValue(agent_data?.name, name),
service: getValue(agent_data?.service, service),
// etc.
});6. Schema change impact
The configuration field type changed from Object to configurationSchema. Existing documents with non-conforming data may behave unexpectedly. Is there a migration needed?
7. Missing error handling
No error handling if apiCallService.getAllApiCallsByOrgId fails. Consider wrapping in try-catch or adding fallback:
const functions = await apiCallService.getAllApiCallsByOrgId(...).catch(() => []);Summary
- 🔴 Remove/configure hardcoded version_id before merge
- 🟡 Consider null safety improvements
- 🟡 Schema migration for existing documents
- 🟢 Good refactoring of configuration logic
a1bf5b8 to
2940abd
Compare
Husainbw786
left a comment
There was a problem hiding this comment.
Code Review for PR #799: feat: agent changes
🔴 Critical Issues
1. Security Risk: Unvalidated AI Response Spread into Database
Location: src/controllers/agentConfig.controller.js:229-230
const result = await ConfigurationServices.createAgent({
...(useAiData ? agent_data : {}),Problem: The code directly spreads agent_data (raw AI response from callAiMiddleware) into the database object. This is a serious security vulnerability:
- An AI response could contain malicious or unexpected fields (e.g.,
org_id,user_id,_id,apikey,function_ids) - These could override critical fields set later in the object
- The AI could return fields that shouldn't be user-controllable, leading to privilege escalation
Fix: Whitelist only the expected fields from the AI response:
const allowedAiFields = ['name', 'service', 'configuration', 'gpt_memory', 'fall_back'];
const safeAgentData = Object.keys(agent_data)
.filter(key => allowedAiFields.includes(key))
.reduce((obj, key) => ({ ...obj, [key]: agent_data[key] }), {});
const result = await ConfigurationServices.createAgent({
...(useAiData ? safeAgentData : {}),
// ... rest of fields
});2. Logic Bug: useAiData Truthy Check Incorrect
Location: src/controllers/agentConfig.controller.js:226
const useAiData = purpose && agent_data;Problem: agent_data is initialized as {} (empty object), which is always truthy in JavaScript. So useAiData will be true whenever purpose exists, even if the AI call failed and agent_data is empty.
Fix: Check for actual AI response data:
const useAiData = purpose && Object.keys(agent_data).length > 0;🟡 Moderate Issues
3. Missing Required Fields When Using AI Configuration
Location: src/controllers/agentConfig.controller.js:175-195
When purpose && agent_data?.configuration is true, the code uses model_data = agent_data.configuration directly. However, this may be missing required fields like:
type(chat/completion)response_formatis_rich_textprompt
This could create agents with incomplete configurations.
Fix: Merge with defaults:
if (purpose && agent_data?.configuration) {
model_data = {
type: type,
response_format: { type: 'default', cred: {} },
is_rich_text: false,
prompt: prompt,
...agent_data.configuration
};
}4. Inconsistent Error Handling for Tools Fetch
Location: src/controllers/agentConfig.controller.js:93-99
The error is logged but silently swallowed. While this prevents the entire agent creation from failing, consider:
- Logging the error level (warn/error) consistently
- Perhaps including in the response that tools couldn't be loaded
- The
purposeAI generation will proceed without tools, which may give suboptimal results
🟢 Minor Issues / Suggestions
5. Typo Fix in constant.js ✅
Good catch fixing "shcmea accroding" → "schema according". This improves AI prompt quality.
6. Rename Ambiguity
The variable res_data (line 107) shadows the common pattern of res for Express response. Consider ai_response or generatedConfig for clarity.
7. Optional: Add JSDoc Comments
The aiVal helper function is useful but could benefit from documentation:
/**
* Returns AI value if AI data is being used and field exists, otherwise fallback
* @param {*} aiField - Value from AI response
* @param {*} fallback - Default value to use
*/
const aiVal = (aiField, fallback) => ...Summary
| Severity | Issue | Action |
|---|---|---|
| 🔴 Critical | Unvalidated AI response spread | Whitelist allowed fields |
| 🔴 Critical | Truthy check bug | Check Object.keys length |
| 🟡 Moderate | Missing config fields | Merge with defaults |
| 🟡 Moderate | Silent error swallow | Consider logging strategy |
| 🟢 Good | Typo fix | ✅ Approved |
Please address the critical security and logic bugs before merging.
ca837d8 to
0995b26
Compare
dbcf348 to
375c320
Compare
* fix: chatbot image save (input and generation) * fix: revmove embed user agent from the webhook * refactor: prompt spilit fix * add grafanna package * fix: update resource creation settings to include keepDuplicate option * fix: update settings in createCollection and createResourceInCollection to ensure keepDuplicate is consistently applied * key name change * proxy url remove from env * change proxy_refrence_id to PUBLIC_REFERENCEID * feat: added the 'status' key to the apikey model * removed status key * status removed * fixed prompt_enhancer_percentage and criteria_check * static data with security key * feat: add hide feature to hide prompt helper * fix: prompt optimiser fix * feat auto reset limit and remove cron * fix: embed preview * fix: embed preview * feat: transform ViaSocket fields structure for new payload format * feat: add model type in get all agent api * fix: resolved windsurf comments * feat: add configuration type in get agents by user id projection * feat: integrate Not Diamond model selection and update agent version controller * fix: resolved windsurd comments * feat: response caching * feat: auto model select * feat: added batch in model * feat: implement log queue processing with multiple services for enhanced message handling * feat: auto model select * fix: improve Redis error handling and connection strategy * refactor: rich ui * feat: implement multi-type pre-tool support (#803) * feat: implement multi-type pre-tool support * fix: add validation pre-tool management * fix: removed redundant code * feat: agent to template (#810) Co-authored-by: Yogesh Patel <yogeshpatel@gmail.com> * feat: response caching (#813) * create proxy auth token for automaint (#815) Co-authored-by: Prayanshrajput <prayanshrajput15@gmail.com> * cosumer logic change * grafanna added * not take start date from frontend * fix: add pre_tools to simple_fields in updateAgentController * refactor: consolidate actionData and onClickType field schema handling (#824) * fix: handled the notdiamond api failure safely * refactor: convert Pyroscope import from require to ES6 import syntax (#826) * fix: agent template knowledgeBase added * update local token generation config * fix: chatbot preveiw bug fixed * fix: pass template name and description to schema builder and remove actionData field overrides * fix: tempalte tool call count bug fixed * refactor: apply code review suggestions * fix: add bridge_id to Thread query filter in saveSubThreadIdAndName * feat: enhance log processing and metrics storage (#823) - Added new fields to the raw_data model, including time_zone and updated table name. - Refactored logQueueConsumer to handle saving conversation and orchestrator history, as well as batch metrics. - Introduced saveHistory and saveMetrics services for structured data storage in PostgreSQL and TimescaleDB. - Implemented error handling for database operations in the new services. Co-authored-by: Husain Baghwala <husainhackerrank@gmail.com> * fix: stream in subscribe api (#847) * feat: added reasoning in history and fixed orchestral history * refactor: enhance Redis cache clearing response (#852) - Updated the clearRedisCache function to include detailed response data. - Added 'cleared_keys' and 'skipped_keys' to the response, along with a count of cleared keys. - Improved message formatting for multiple cleared keys. * Clear redid while publish (#855) * feat: implement cache invalidation after publishing version - Added functionality to delete cache keys related to the published version after the publish operation. - Ensures that outdated cache entries are removed, improving data consistency. * feat: add cache invalidation for API call updates - Added cache deletion when API calls are updated via updateApiCallByFunctionId - Implemented cache invalidation in saveApi service when updating existing API calls - Invalidates cache keys for all associated bridge_ids to ensure data consistency - Imported agentVersionService and deleteInCache utilities in apiCall controller and service --------- Co-authored-by: Husain Baghwala <husainhackerrank@gmail.com> * refactor: change connected_agents key from agent_name to bridge_id across codebase * changes * fix: pr comment resolved (#853) * chore: optimise apicalls collections, migration (#844) chore: refactor apicalls migration script and add getOrganizationOwner helper chore: moved all migrations to migration-mongo folder * feat: api key validation (#789) * feat: template validation by agent (#843) * feat: template validation by agent * fix: agent comment changes * fix: agent changes and one commit (#799) * chore: optimized apicredentials collection and wrote migreation (#845) * chore: optimized apicredentials collection and wrote migreation * chore: refactor apikeycredentials migration * chore: optimised apilerts collection , removed duplicate schema from code, and wrote migration (#848) chore: resolved ai comments `# squash d8c192a # chore: resolved ai comments * chore: migrate orgAccessToken from ResponseType collection to Proxy org meta (#858) * fix: history queue bug * fix: log queue bugs * fix: prod or test env check added * feat: update model configuration modes and include additional fields in agent retrieval and API responses (#868) * refactor: replace flattenDict with extractPrimitiveValues and include pre-tool arguments in variable path resolution (#870) * chore: add migration script to remap connected_agents keys from agent names to bridge_id in configurations and configuration_versions collections (#872) Co-authored-by: Yogesh Patel <yogeshpatel@gmail.com> * fix: added stream for model (#871) s * fix: missed condition (#874) * axios package fix --------- Co-authored-by: adityajunwal <adityakjunwal@gmail.com> Co-authored-by: Dhiraj Parihar <dhirajparihar2001@gmail.com> Co-authored-by: Natwar Singh Rathor <87537893+Natwar589@users.noreply.github.com> Co-authored-by: Natwar589 <natwarrathor961@gmail.com> Co-authored-by: harshhsahu <harsh@whozzat.com> Co-authored-by: Husain Baghwala <husainhackerrank@gmail.com> Co-authored-by: Prayanshrajput <104488357+Prayanshrajput@users.noreply.github.com> Co-authored-by: Yogesh Patel <yogeshpatel@gmail.com> Co-authored-by: Prayanshrajput <prayanshrajput15@gmail.com> Co-authored-by: Anushtha-Rathore <anushtharathore35@gmail.com> Co-authored-by: LAVISH GEHLOD <lavishgehlod210204@acropolis.in> Co-authored-by: yogeshpatel70 <155749062+yogeshpatel70@users.noreply.github.com> Co-authored-by: Aditya Kumar Junwal <163153177+adityajunwal@users.noreply.github.com> Co-authored-by: harsh <145131947+harshhsahu@users.noreply.github.com> Co-authored-by: LAVI9966 <102133274+LAVI9966@users.noreply.github.com>
No description provided.