crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

fix: harden memory tool input validation

Open MatthiasHowellYopp opened this issue 7 months ago • 2 comments

Description:

Part 2/4 of adding Valkey as a storage backend for CrewAI. This PR hardens the memory tools against malformed inputs that surface more frequently with the new storage paths.

What changed:

  • memory_tools.py — RecallMemoryTool and RememberTool now handle None, empty lists, and lists of empty strings gracefully, returning descriptive error messages instead of crashing. String inputs are normalized to lists. The queries and contents fields are now optional with min_length=1 validation, and both schemas use extra="forbid" to reject unexpected parameters.

  • en.json — Updated tool descriptions for recall_memory and save_to_memory to include explicit parameter format examples (e.g. {"queries": ["search term"]}), reducing LLM misuse of the tool interface.

Testing:

test_memory_tools.py (15 tests) — Covers None input, empty lists, empty strings, string-to-list conversion, deduplication across queries, and single vs. batch remember paths.

Summary by CodeRabbit

  • New Features

    • Memory tools accept optional inputs and normalize single strings or lists; non-string items are ignored.
  • Bug Fixes

    • Improved handling of missing/empty/whitespace inputs with clearer error messages; previous recall/remember flows preserved.
  • Documentation

    • Instruction text updated to require explicit JSON parameters for recall and save operations.
  • Tests

    • Added tests covering non-string item handling and related edge cases.
  • Chores

    • Linting config adjusted to exclude JSON files.

Review Change Stack

MatthiasHowellYopp avatar May 04 '26 14:05 MatthiasHowellYopp

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Memory tools' input schemas now permit optional queries and contents and forbid extra fields; tools normalize string inputs to lists, trim and filter entries (including non-strings), and return explicit errors when no usable items remain; translations and tests updated accordingly.

Changes

Memory Tools Input Validation

Layer / File(s) Summary
Input Schemas
lib/crewai/src/crewai/tools/memory_tools.py
RecallMemorySchema.queries and RememberSchema.contents change from required list[str] to optional list[str] | None with min-length validation and model_config = {"extra": "forbid"}.
Recall Tool Input Processing
lib/crewai/src/crewai/tools/memory_tools.py
RecallMemoryTool._run signature expands queries to accept list[str] | str | None. Adds validation for missing/empty inputs, string-to-list normalization, trimming/filtering blank and non-string queries, and targeted errors when no valid queries remain.
Remember Tool Input Processing
lib/crewai/src/crewai/tools/memory_tools.py
RememberTool._run signature expands contents to accept list[str] | str | None. Adds validation for missing/empty inputs, string-to-list normalization, trimming/filtering blank and non-string contents, and targeted errors when no valid contents remain.
Tool Instruction Translations
lib/crewai/src/crewai/translations/en.json
recall_memory and save_to_memory tool instructions now explicitly require queries and contents parameters respectively, with clearer JSON examples.
Test Module & Fixtures
lib/crewai/tests/tools/test_memory_tools.py
New pytest fixtures instantiate a mocked memory object and both tool instances; tests added/expanded to cover validation and behavior.
Recall Tool Tests
lib/crewai/tests/tools/test_memory_tools.py
TestRecallMemoryToolValidation covers None/empty/whitespace inputs, string-to-list normalization, per-query memory.recall invocation, no-match messaging, match formatting, and deduplication.
Remember Tool Tests
lib/crewai/tests/tools/test_memory_tools.py
TestRememberToolValidation covers None/empty/whitespace inputs, string-to-list normalization, routing to memory.remember vs memory.remember_many, whitespace filtering, and success messaging.
Non-String Item Tests
lib/crewai/tests/tools/test_memory_tools.py
TestNonStringItemHandling asserts filtering of non-string elements and errors when no valid strings remain for both recall and remember tools.
Ruff Exclude JSON
pyproject.toml
Added **/*.json to tool.ruff.extend-exclude.

Sequence Diagram

sequenceDiagram
  participant User
  participant RecallMemoryTool
  participant Memory
  User->>RecallMemoryTool: sends queries (None|string|list)
  RecallMemoryTool->>RecallMemoryTool: normalize, trim, filter, dedupe
  RecallMemoryTool->>Memory: memory.recall(valid_queries)
  Memory-->>RecallMemoryTool: returns matches
  RecallMemoryTool-->>User: formatted matches or error

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I tidy queries and contents with care,
Trim the fluff, filter what isn't fair.
Strings become lists, blanks gently tossed,
Only real memories are kept — never lost.
Tests hop in place to guard what was crossed.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the primary change: hardening memory tool input validation to handle malformed inputs gracefully.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

[!WARNING]

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 11 '26 19:05 coderabbitai[bot]

@greysonlalonde hoping I can get a review on this.

MatthiasHowellYopp avatar May 19 '26 18:05 MatthiasHowellYopp