Skip to content

memo api v2 user_id fix - #563

Open
parthshr370 wants to merge 2 commits into
aipotheosis-labs:mainfrom
parthshr370:mem0/apiv2
Open

memo api v2 user_id fix#563
parthshr370 wants to merge 2 commits into
aipotheosis-labs:mainfrom
parthshr370:mem0/apiv2

Conversation

@parthshr370

@parthshr370 parthshr370 commented Jul 30, 2025

Copy link
Copy Markdown
Contributor

🏷️ Ticket

LLM hallucinates user_id during tool call of mem0 api v2

📝 Description

Add a function to inject linked_account_owner_id to the user_id field and make it invisible for the LLM to not edit

🎥 Demo (if applicable)

📸 Screenshots (if applicable)

Screenshot_20250730_172730 Screenshot_20250730_172807 Screenshot_20250730_172828

✅ Checklist

  • I have signed the Contributor License Agreement (CLA) and read the contributing guide (required)
  • I have linked this PR to an issue or a ticket (required)
  • I have updated the documentation related to my change if needed
  • I have updated the tests accordingly (required for a bug fix or a new feature)
  • All checks on CI passed

Summary by cubic

Fixed an issue where the mem0 API v2 could hallucinate the user_id by automatically injecting the correct linked_account_owner_id and making it invisible to the LLM.

  • Bug Fixes
    • Injects linked_account_owner_id as user_id using template substitution.
    • Hides user_id from LLM-editable fields to prevent accidental changes.

Summary by CodeRabbit

  • New Features

    • The "user_id" field is now automatically populated with your linked account owner ID in relevant memory functions, reducing the need for manual entry.
  • Style

    • The "user_id" field is now hidden from view in memory-related forms but remains required and is filled in automatically.

@parthshr370
parthshr370 had a problem deploying to CICD_FOR_FORKED_REPO July 30, 2025 12:05 — with GitHub Actions Failure
@parthshr370
parthshr370 had a problem deploying to CICD_FOR_FORKED_REPO July 30, 2025 12:05 — with GitHub Actions Failure
@vercel

vercel Bot commented Jul 30, 2025

Copy link
Copy Markdown

@parthshr370 is attempting to deploy a commit to the Proxy Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jul 30, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduce template-based default value substitution in the schema processing logic, allowing placeholders like {{linked_account_owner_id}} to be dynamically resolved using a provided context. This mechanism is integrated into the default injection process and is applied to several function schemas, making certain required fields invisible while automatically populating their values via context.

Changes

Cohort / File(s) Change Summary
Schema Default Injection Logic
backend/aci/common/processor.py
Enhanced inject_required_but_invisible_defaults to accept an optional context dict for template substitution in default values. When a default string matches the {{key}} pattern, the key is resolved from the context. The function signature was updated, and recursive calls now propagate the context. No other logic was changed.
Function Input Preprocessing
backend/aci/server/function_executors/base_executor.py
Updated _preprocess_function_input to pass a context dictionary containing linked_account_owner_id to the default injection function, enabling template substitution for relevant schema fields. No other logic was altered.
Function Schemas (MEM0)
backend/apps/mem0/functions.json
Added "default": "{{linked_account_owner_id}}" to the user_id property in three function schemas. Removed user_id from the visible arrays, making it required but invisible and auto-filled via context. No other structural or logical changes were made to the schemas.

Sequence Diagram(s)

sequenceDiagram
    participant Executor as FunctionExecutor
    participant Processor as inject_required_but_invisible_defaults
    participant Context as Context Dict

    Executor->>Processor: Call with schema, input_data, context
    alt Default value is a template
        Processor->>Context: Lookup key in context
        Context-->>Processor: Return value
        Processor->>Processor: Substitute default value
    else No template
        Processor->>Processor: Use static default value
    end
    Processor-->>Executor: Return processed data
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

A rabbit hops through fields of code,
With context keys in tow,
Invisible defaults now bestowed,
As schemas gently flow.
User IDs appear by magic’s hand,
Templates filled as planned—
Oh, what a clever, hoppy land! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@recurseml

recurseml Bot commented Jul 30, 2025

Copy link
Copy Markdown

✨ No issues found! Your code is sparkling clean! ✨

Need help? Join our Discord for support!
https://discord.gg/qEjHQk64Z9

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
backend/aci/common/processor.py (2)

54-54: Improve documentation specificity

Consider being more specific about the template format and provide an example.

-    Supports template substitution for values like {{linked_account_owner_id}}.
+    Supports template substitution for values using {{key}} format, e.g., {{linked_account_owner_id}}.

72-74: Enhance error message with more context

The error message could be more helpful by including available context keys.

-                        raise Exception(
-                            f"Template variable '{template_key}' not found in context for property: {prop}"
-                        )
+                        available_keys = list(context.keys()) if context else []
+                        raise Exception(
+                            f"Template variable '{template_key}' not found in context for property: {prop}. "
+                            f"Available keys: {available_keys}"
+                        )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fcf3798 and 177ac15.

📒 Files selected for processing (3)
  • backend/aci/common/processor.py (3 hunks)
  • backend/aci/server/function_executors/base_executor.py (1 hunks)
  • backend/apps/mem0/functions.json (4 hunks)
🧰 Additional context used
🧠 Learnings (1)
backend/apps/mem0/functions.json (1)

Learnt from: jiwei-aipolabs
PR: #538
File: backend/apps/microsoft_calendar/functions.json:276-308
Timestamp: 2025-07-22T19:31:44.823Z
Learning: In backend/apps/microsoft_calendar/functions.json and similar API function definitions, the additionalProperties: false restriction on query objects is intentionally designed for strict validation, even if it blocks some legitimate OData/HTTP headers. The user prefers explicit whitelisting of parameters over flexible schema validation.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Format, Lint, and Test
🔇 Additional comments (10)
backend/aci/common/processor.py (2)

51-51: LGTM: Function signature enhancement

Good addition of the optional context parameter with a sensible default value of None.


86-86: LGTM: Context propagation

Correct propagation of the context parameter to recursive calls.

backend/aci/server/function_executors/base_executor.py (1)

70-74: LGTM: Clean context injection implementation

The implementation correctly creates the context dictionary and passes it to the processor function. The comments clearly explain the purpose of the template substitution feature.

backend/apps/mem0/functions.json (7)

53-55: LGTM: Template default value for user_id

Correctly adds the template default value for automatic user_id injection while maintaining the description.


74-74: LGTM: user_id removed from visible parameters

Correctly removes user_id from the visible array while keeping it in the required array, ensuring it's automatically injected but invisible to the LLM.


122-124: LGTM: Consistent template implementation

Properly implements the same template pattern for the search function.


127-127: LGTM: Filters object made invisible

Correctly makes the entire filters object invisible since user_id is the only required field and should be auto-injected.


182-184: LGTM: Consistent pattern in GET_MEMORIES

Maintains consistency with the template substitution pattern across all affected functions.


187-187: LGTM: Consistent visibility handling

Properly removes user_id from visibility while maintaining the required constraint.


53-187: user_id template substitution is consistent across all MEM0 functions

All six MEM0 endpoints were checked:

  • MEM0__ADD_MEMORY, MEM0__SEARCH_MEMORIES, and MEM0__GET_MEMORIES include user_id with default: "{{linked_account_owner_id}}".
  • MEM0__GET_MEMORY, MEM0__UPDATE_MEMORY, and MEM0__DELETE_MEMORY do not reference user_id, as expected.

No further updates are needed.

Comment on lines +65 to +75
default_value = subschema["default"]
# Handle template substitution like {{linked_account_owner_id}}
if isinstance(default_value, str) and default_value.startswith("{{") and default_value.endswith("}}"):
template_key = default_value[2:-2] # Extract the key between {{ }}
if context and template_key in context:
default_value = context[template_key]
else:
raise Exception(
f"Template variable '{template_key}' not found in context for property: {prop}"
)
input_data[prop] = default_value

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

❓ Verification inconclusive

Verify template parsing robustness

The template parsing logic uses simple string operations. Consider edge cases and potential security implications.

The current implementation:

  1. Uses simple string slicing which could be fragile with malformed templates
  2. Doesn't validate the template key format
  3. Could potentially allow injection if context values aren't sanitized

Consider adding validation for the template key format and ensuring context values are properly sanitized.


🏁 Script executed:

#!/bin/bash
# Verify if there are any other template patterns or edge cases in the codebase
rg -A 3 -B 3 "{{.*}}" --type json

Length of output: 117


🏁 Script executed:

#!/bin/bash
# Search for template patterns like {{key}} across the repository
rg -n '\{\{[^}]\+\}\}'

Length of output: 24


Improve template parsing robustness in backend/aci/common/processor.py

The current logic around default‐value templating relies on simple startswith/endswith checks and unvalidated slicing, which may break on malformed inputs or enable unexpected values from context. To harden this:

• Validate the extracted template_key against an explicit pattern (e.g. ^[A-Za-z0-9_]+$) before lookup.
• Use a regex-based capture (e.g. re.match(r'^\{\{([A-Za-z0-9_]+)\}\}$', default_value)) instead of manual slicing.
• Sanitize or type‐check the resolved context[template_key] to prevent injection or misuse downstream.

Suggested diff snippet:

-               if isinstance(default_value, str) and default_value.startswith("{{") and default_value.endswith("}}"):
-                   template_key = default_value[2:-2]
+               import re
+               if isinstance(default_value, str):
+                   m = re.match(r'^\{\{([A-Za-z0-9_]+)\}\}$', default_value)
+                   if m:
+                       template_key = m.group(1)
+                   else:
+                       raise ValueError(f"Invalid template syntax for property '{prop}': {default_value}")
                if context and template_key in context:
                    # Optional: further sanitize or validate context[template_key] here
                    default_value = context[template_key]
                else:
                    raise KeyError(
                        f"Template variable '{template_key}' not found in context for property: {prop}"
                    )

This enforces a strict key format, avoids fragile string slicing, and makes it clear where to apply sanitization.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In backend/aci/common/processor.py around lines 65 to 75, improve the template
parsing by replacing the manual startswith/endswith checks and slicing with a
regex match that captures the template key using a pattern like
^\{\{([A-Za-z0-9_]+)\}\}$. Validate the extracted template_key against this
pattern before using it. After retrieving the value from context, add
sanitization or type-checking to ensure it is safe and appropriate for
downstream use. This will make the template handling more robust and secure.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cubic analysis

2 issues found across 3 files • Review in cubic

React with 👍 or 👎 to teach cubic. You can also tag @cubic-dev-ai to give feedback, ask questions, or re-run the review.



def inject_required_but_invisible_defaults(parameters_schema: dict, input_data: dict) -> dict:
def inject_required_but_invisible_defaults(parameters_schema: dict, input_data: dict, context: dict = None) -> dict:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The context parameter is annotated as dict but defaulted to None, producing an invalid type hint and causing static-analysis noise.

Prompt for AI agents
Address the following comment on backend/aci/common/processor.py at line 51:

<comment>The context parameter is annotated as dict but defaulted to None, producing an invalid type hint and causing static-analysis noise.</comment>

<file context>
@@ -48,9 +48,10 @@ def filter(schema: dict) -&gt; dict:
     return filter(filtered_parameters_schema)
 
 
-def inject_required_but_invisible_defaults(parameters_schema: dict, input_data: dict) -&gt; dict:
+def inject_required_but_invisible_defaults(parameters_schema: dict, input_data: dict, context: dict = None) -&gt; dict:
     &quot;&quot;&quot;
     Recursively injects required but invisible properties with their default values into the input data.
</file context>
Suggested change
def inject_required_but_invisible_defaults(parameters_schema: dict, input_data: dict, context: dict = None) -> dict:
def inject_required_but_invisible_defaults(parameters_schema: dict, input_data: dict, context: dict | None = None) -> dict:

},
"required": ["user_id"],
"visible": ["user_id"],
"visible": [],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Making user_id invisible here while allowing additionalProperties true lets callers supply their own user_id value and bypass the intended default injection.

Prompt for AI agents
Address the following comment on backend/apps/mem0/functions.json at line 127:

<comment>Making user_id invisible here while allowing additionalProperties true lets callers supply their own user_id value and bypass the intended default injection.</comment>

<file context>
@@ -118,11 +119,12 @@
                             &quot;properties&quot;: {
                                 &quot;user_id&quot;: {
                                     &quot;type&quot;: &quot;string&quot;,
-                                    &quot;description&quot;: &quot;Filter memories by a specific user ID&quot;
+                                    &quot;description&quot;: &quot;Filter memories by a specific user ID&quot;,
+                                    &quot;default&quot;: &quot;{{linked_account_owner_id}}&quot;
                                 }
                             },
                             &quot;required&quot;: [&quot;user_id&quot;],
</file context>
Suggested change
"visible": [],
"visible": ["user_id"],

@parthshr370
parthshr370 had a problem deploying to CICD_FOR_FORKED_REPO August 5, 2025 08:06 — with GitHub Actions Failure
@parthshr370
parthshr370 had a problem deploying to CICD_FOR_FORKED_REPO August 5, 2025 08:06 — with GitHub Actions Failure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant