Skip to content

feat(memory): add per-call memory control options (read/write) for ge… - #906

Merged
murdore merged 1 commit into
juspay:releasefrom
adarshpandey-cs21:BZ-1914-add-per-call-memory-control-options-read-write-for-generate-and-stream-in-neuro-link
Mar 27, 2026
Merged

murdore merged 1 commit into
juspay:releasefrom
adarshpandey-cs21:BZ-1914-add-per-call-memory-control-options-read-write-for-generate-and-stream-in-neuro-link

Conversation

@adarshjuspay

@adarshjuspay adarshjuspay commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

…nerate and stream in NeuroLink

  • add per-call memory control options (read/write) for generate and stream in NeuroLink

Pull Request

Description

What does this PR do?

A clear and concise description of the changes in this pull request.

Related Issues

Does this PR close any issues?

Fixes #(issue number)
Closes #(issue number)
Relates to #(issue number)

Type of Change

Please select the type of change:

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement
  • Test coverage improvement
  • Build/CI configuration
  • Other (please describe):

Motivation and Context

Why is this change needed? What problem does it solve?

Provide context for reviewers:

  • Background information
  • Use case or scenario
  • Links to relevant discussions or documentation
  • Screenshots/GIFs (if UI-related)

Changes Made

What specific changes were made?

Provide a bullet-point list of the key changes:

  • Added X functionality to Y component
  • Modified Z behavior to handle edge case A
  • Updated documentation in file B
  • Refactored C for better performance

Breaking Changes

Does this PR introduce breaking changes?

  • No breaking changes
  • Yes, breaking changes (describe below)

If yes, describe:

  • What breaks?
  • Migration path for users
  • Deprecation warnings added?

Testing

How has this been tested?

Please describe the tests you ran and their results:

  • Unit tests added/updated
  • Integration tests added/updated
  • E2E tests pass
  • Manual testing completed
  • Tested with multiple providers: [list providers]
  • Tested on multiple platforms: [list platforms]

Test Coverage

  • All new code is covered by tests
  • Existing tests pass
  • Coverage percentage maintained or improved

Manual Testing Steps

Provide steps for manual testing:

  1. Set up environment with [...]
  2. Run command [...]
  3. Verify that [...]
  4. Check that [...]

Code Quality

Have you followed code quality standards?

  • Code follows the project's style guidelines (ESLint passes)
  • Code is properly formatted (Prettier applied)
  • Self-review of code completed
  • No console.log statements (using logger instead)
  • No hardcoded API keys or secrets
  • TypeScript strict mode compliance
  • Proper error handling implemented
  • TODO/FIXME comments reference issues

Documentation

Have you updated documentation?

  • JSDoc comments added/updated for public APIs
  • README.md updated (if needed)
  • Documentation in /docs updated (if needed)
  • Code examples added/updated (if needed)
  • CHANGELOG.md updated (if applicable)
  • Migration guide provided (if breaking changes)

Commit Message Format

Does your commit follow semantic commit conventions?

  • Commit message follows format: type(scope): description
  • Valid type used: feat, fix, docs, style, refactor, test, chore, build, ci, perf, revert
  • Scope specified (e.g., providers, cli, docs, middleware)

Example: feat(providers): add support for LiteLLM proxy

Dependencies

Does this PR add, update, or remove dependencies?

  • No dependency changes
  • Dependencies added (list below)
  • Dependencies updated (list below)
  • Dependencies removed (list below)

If yes, list dependencies and justification:

package-name@version - Reason for adding/updating

Performance Impact

Does this change affect performance?

  • No performance impact
  • Performance improved (provide metrics)
  • Performance degraded (justify why acceptable)

If applicable, provide benchmark results:

Before: X ms
After: Y ms
Improvement: Z%

Security Considerations

Are there any security implications?

  • No security implications
  • Security review needed
  • Security vulnerability fixed

If applicable, describe:

  • Security measures implemented
  • Potential risks mitigated
  • Compliance considerations (HIPAA, SOC2, GDPR)

Deployment Notes

Special deployment instructions?

  • No special deployment steps
  • Requires environment variable changes (list below)
  • Requires database migration
  • Requires Redis schema update
  • Other (describe below)

Screenshots / Videos

If applicable, add screenshots or videos to demonstrate changes:

[Add screenshots or videos here]

Reviewer Checklist

For reviewers:

  • Code follows project style and conventions
  • Changes are well-documented
  • Tests provide adequate coverage
  • No obvious performance issues
  • No security vulnerabilities introduced
  • Breaking changes are properly documented
  • Documentation is clear and accurate

Additional Notes

Any additional information for reviewers:

[Add any extra context, concerns, or questions here]


Pre-submission Checklist

Before submitting, ensure you have:

  • Read and followed the Contributing Guidelines
  • Verified all automated pre-commit checks pass
  • Tested changes locally with pnpm test
  • Built the project successfully with pnpm build
  • Run pnpm run validate:all and all checks pass
  • Reviewed your own code for obvious issues
  • Ensured commit messages follow semantic format
  • Updated relevant documentation
  • Added tests for new functionality
  • Checked that CI/CD pipeline passes (after creating PR)

Thank you for contributing to NeuroLink!

Summary by CodeRabbit

Release Notes

  • New Features

    • Added per-call memory control to generate() and stream() methods, allowing you to override global memory settings on individual API calls with granular enabled, read, and write flags.
  • Documentation

    • Updated memory activation conditions documentation and added Per-Call Memory Control section with usage examples for read-only, write-only, and fully disabled memory modes.

…nerate and stream in NeuroLink

 - add per-call memory control options (read/write) for generate and stream in NeuroLink
Copilot AI review requested due to automatic review settings March 27, 2026 11:16
@vercel

vercel Bot commented Mar 27, 2026

Copy link
Copy Markdown

@adarshpandey-cs21 is attempting to deploy a commit to the Sachin Sharma's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Mar 27, 2026 •

Copy link
Copy Markdown

Walkthrough

Per-call memory control feature added to GenerateOptions and StreamOptions type definitions, enabling clients to override global memory behavior on individual function calls. Two private helper methods introduced to centralize memory enablement logic with consistent precedence: global config enables memory, per-call enabled flag disables both read/write, and separate read/write flags control each operation independently.

Changes

Cohort / File(s) Summary
Type Definitions
src/lib/types/generateTypes.ts, src/lib/types/streamTypes.ts
Added optional memory field with enabled, read, and write boolean overrides to both GenerateOptions and StreamOptions types.
Memory Gating Logic
src/lib/neurolink.ts
Introduced private helper methods shouldReadMemory() and shouldWriteMemory() to centralize per-call override logic. Updated three call sites (scheduleGenerateMemoryStorage, prepareStreamOptions, storeStreamConversationMemory) to use the new helpers instead of inline conditional checks.
Documentation
docs/features/memory.md
Updated memory activation condition wording and added comprehensive Per-Call Memory Control section documenting the new memory option, flag defaults, precedence order, and usage examples for generate() and stream().

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

released

Suggested reviewers

  • NayniSinghal10
  • murdore

Poem

🐰 Hops with glee through memory's halls,
Per-call control now answers calls!
Read or write, or both, or none—
Override the globals, oh what fun! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main feature addition: per-call memory control options (read/write) for generate and stream operations, which aligns with all the changes shown in the PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

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

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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Adds per-call overrides to control NeuroLink’s condensed memory behavior (read/write) on generate() and stream() calls, without changing global memory configuration.

Changes:

  • Added memory per-call flags (enabled, read, write) to GenerateOptions and StreamOptions.
  • Introduced shouldReadMemory() / shouldWriteMemory() helpers and applied them to stream retrieval and generate/stream background storage.
  • Updated memory feature docs to describe per-call override semantics and precedence.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
src/lib/types/streamTypes.ts Adds StreamOptions.memory per-call flags for memory control.
src/lib/types/generateTypes.ts Adds GenerateOptions.memory per-call flags for memory control.
src/lib/neurolink.ts Implements helper gates and wires per-call flags into stream read + generate/stream write logic.
docs/features/memory.md Documents per-call memory override flags, defaults, and precedence.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/lib/neurolink.ts
Comment on lines +1299 to +1306
private shouldReadMemory(
perCallMemory: { enabled?: boolean; read?: boolean } | undefined,
userId: unknown,
): boolean {
if (
!this.conversationMemoryConfig?.conversationMemory?.memory?.enabled ||
!userId
) {

Copilot AI Mar 27, 2026

Copy link

Choose a reason for hiding this comment

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

memory.read is now part of the public per-call API, but generate() never performs condensed-memory retrieval (there’s no call path that uses shouldReadMemory()/retrieveMemory() for generate). As a result, GenerateOptions.memory.read has no effect, and the docs/API contract are misleading. Consider adding the same pre-call retrieval step to generate() (after auth/requestContext merging so context.userId is available) or remove/rename the read option for generate if it’s intentionally stream-only.

Copilot uses AI. Check for mistakes.
Comment thread src/lib/neurolink.ts
Comment on lines 6165 to 6168
if (
this.conversationMemoryConfig?.conversationMemory?.memory?.enabled &&
this.shouldReadMemory(options.memory, options.context?.userId) &&
options.context?.userId
) {

Copilot AI Mar 27, 2026

Copy link

Choose a reason for hiding this comment

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

Per-call memory overrides (memory.enabled / memory.read / memory.write) introduce new branching behavior for both stream retrieval and background storage, but there doesn’t appear to be automated coverage asserting the precedence rules (global disabled vs per-call overrides, enabled=false overriding read/write, etc.). Adding coverage in the existing continuous test suite for memory would help prevent regressions and ensure the new flags behave as documented.

Copilot uses AI. Check for mistakes.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/features/memory.md (1)

278-283: ⚠️ Potential issue | 🟡 Minor

Clarify read vs write activation conditions explicitly.

“all three conditions must be met” is slightly inaccurate for read-only calls. Non-empty response content is only a write prerequisite, not a read prerequisite. Consider splitting into separate bullets for read and write activation to avoid ambiguity.

Suggested wording
-For memory to activate on a call, all three conditions must be met:
-
-1. `memory.enabled` is `true` in the config
-2. `options.context.userId` is provided in the generate/stream call
-3. The response has non-empty content (for write)
+Memory activation depends on operation:
+
+- **Read (inject into prompt)** requires:
+  1. Global memory enabled
+  2. `options.context.userId` provided
+  3. Per-call flags allow read (`memory.enabled !== false` and `memory.read !== false`)
+
+- **Write (store after call)** requires:
+  1. Global memory enabled
+  2. `options.context.userId` provided
+  3. Per-call flags allow write (`memory.enabled !== false` and `memory.write !== false`)
+  4. Response content is non-empty (trimmed)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/features/memory.md` around lines 278 - 283, The current wording implies
all three conditions (memory.enabled, options.context.userId, and non-empty
response content) apply to both read and write—update the text to separate read
vs write activation: state that for reads only memory.enabled and
options.context.userId are required (e.g., when calling generate/stream to fetch
memory), and for writes both memory.enabled and options.context.userId are
required plus the response must have non-empty content before persisting;
reference the config flag memory.enabled, the call options.context.userId used
in generate/stream, and the response content requirement so readers can see
which conditions apply to read-only vs write operations.
🧹 Nitpick comments (2)
src/lib/types/generateTypes.ts (2)

475-482: Consider extracting shared PerCallMemoryOptions type.

The memory field shape is identical in both GenerateOptions and StreamOptions. Extracting it to a shared type would ensure consistency and simplify future modifications.

♻️ Optional: Extract shared type

In src/lib/types/common.ts or a dedicated file:

/**
 * Per-call memory control options.
 * Override global memory SDK behavior for individual generate/stream calls.
 */
export type PerCallMemoryOptions = {
  /** Master toggle. When false, both read and write are skipped. Defaults to true. */
  enabled?: boolean;
  /** Whether to read condensed memory and prepend to prompt. Defaults to true. */
  read?: boolean;
  /** Whether to write the conversation into memory after completion. Defaults to true. */
  write?: boolean;
};

Then in both GenerateOptions and StreamOptions:

-  memory?: {
-    /** Master toggle for this call. When false, both read and write are skipped. Defaults to true. */
-    enabled?: boolean;
-    /** Whether to read condensed memory and prepend to prompt. Defaults to true. */
-    read?: boolean;
-    /** Whether to write (add/condense) the conversation into memory after completion. Defaults to true. */
-    write?: boolean;
-  };
+  memory?: PerCallMemoryOptions;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/types/generateTypes.ts` around lines 475 - 482, Extract the
duplicated memory shape into a shared type and replace the inline definitions in
both GenerateOptions and StreamOptions: create a new exported type
PerCallMemoryOptions (or add it to src/lib/types/common.ts) with enabled?:
boolean, read?: boolean, write?: boolean and then update the memory?: { ... }
fields in GenerateOptions and StreamOptions to use memory?: PerCallMemoryOptions
so both interfaces reference the single definition (adjust imports/exports
accordingly).

475-482: CLI does not expose per-call memory flags.

Based on the context snippets, commandFactory.ts constructs GenerateOptions without the memory field, and processOptions has no --memory, --disable-memory-read, or --disable-memory-write argument parsing. CLI users won't be able to leverage this feature until corresponding flags are added.

Consider adding CLI support in a follow-up if per-call memory control is needed from the command line.

Would you like me to open an issue to track adding CLI flags for per-call memory control (e.g., --memory-read=false, --memory-write=false)?

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/types/generateTypes.ts` around lines 475 - 482, The PR adds per-call
memory settings to GenerateOptions but the CLI never exposes them: update
commandFactory.ts where GenerateOptions is constructed to include the new memory
object (memory.enabled, memory.read, memory.write) based on parsed flags, and
extend processOptions (or the argument parsing setup) to accept CLI flags like
--memory, --disable-memory-read, and --disable-memory-write (or synonymous
names) so the parsed values feed into GenerateOptions; ensure flag names map to
booleans and default behavior matches the types' defaults when flags are
omitted.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@docs/features/memory.md`:
- Around line 278-283: The current wording implies all three conditions
(memory.enabled, options.context.userId, and non-empty response content) apply
to both read and write—update the text to separate read vs write activation:
state that for reads only memory.enabled and options.context.userId are required
(e.g., when calling generate/stream to fetch memory), and for writes both
memory.enabled and options.context.userId are required plus the response must
have non-empty content before persisting; reference the config flag
memory.enabled, the call options.context.userId used in generate/stream, and the
response content requirement so readers can see which conditions apply to
read-only vs write operations.

---

Nitpick comments:
In `@src/lib/types/generateTypes.ts`:
- Around line 475-482: Extract the duplicated memory shape into a shared type
and replace the inline definitions in both GenerateOptions and StreamOptions:
create a new exported type PerCallMemoryOptions (or add it to
src/lib/types/common.ts) with enabled?: boolean, read?: boolean, write?: boolean
and then update the memory?: { ... } fields in GenerateOptions and StreamOptions
to use memory?: PerCallMemoryOptions so both interfaces reference the single
definition (adjust imports/exports accordingly).
- Around line 475-482: The PR adds per-call memory settings to GenerateOptions
but the CLI never exposes them: update commandFactory.ts where GenerateOptions
is constructed to include the new memory object (memory.enabled, memory.read,
memory.write) based on parsed flags, and extend processOptions (or the argument
parsing setup) to accept CLI flags like --memory, --disable-memory-read, and
--disable-memory-write (or synonymous names) so the parsed values feed into
GenerateOptions; ensure flag names map to booleans and default behavior matches
the types' defaults when flags are omitted.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a5a03519-e13c-4774-97ba-8196144e4713

📥 Commits

Reviewing files that changed from the base of the PR and between 67e9533 and fb26d5e.

📒 Files selected for processing (4)
  • docs/features/memory.md
  • src/lib/neurolink.ts
  • src/lib/types/generateTypes.ts
  • src/lib/types/streamTypes.ts

@murdore
murdore merged commit c9a354b into juspay:release Mar 27, 2026
14 of 16 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 9.33.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants