Skip to content

fix: Anthropic compatibility for memory injection middleware#50

Open
tamashi095 wants to merge 1 commit intoMystenLabs:devfrom
tamashi095:fix/anthropic-middleware-compat
Open

fix: Anthropic compatibility for memory injection middleware#50
tamashi095 wants to merge 1 commit intoMystenLabs:devfrom
tamashi095:fix/anthropic-middleware-compat

Conversation

@tamashi095
Copy link
Copy Markdown

Summary

  • Anthropic compatibility: injectMemoryContext inserted memories as a separate { role: "system" } message. When the consumer already passes a system prompt to streamText, this creates multiple system messages separated by user/assistant messages, which Anthropic rejects with AI_UnsupportedFunctionalityError. Fix: append memory context to the existing system message instead of inserting a new one.
  • Publish safety: Added prepublishOnly script to ensure tsc runs before npm publish, preventing packages from being published without dist/.
  • Tests: Added unit tests for findLastUserMessage, injectMemoryContext, and formatMemories using bun:test.

Context

Discovered while integrating MemWal with Sona's Miso chat assistant, which uses @ai-sdk/anthropic + streamText with a system prompt. The middleware worked with OpenAI (which tolerates multiple system messages) but broke on Anthropic.

Test plan

  • bun test packages/sdk/src/ai/middleware.test.ts — 13 tests pass
  • bun run build in packages/sdk/ — clean compile
  • Verified end-to-end with @ai-sdk/anthropic + streamText + system prompt

The `injectMemoryContext` helper inserted memories as a separate system
message. Anthropic's API rejects multiple system messages separated by
user/assistant messages, causing `AI_UnsupportedFunctionalityError`.

Fix: append memory context to the existing system message instead of
inserting a new one. When no system message exists, prepend as before.

Also adds:
- `prepublishOnly` script to prevent publishing without building
- Unit tests for middleware helpers (bun:test)
- tsconfig exclusion for test files
@Aaron1924 Aaron1924 requested a review from ducnmm March 26, 2026 10:12
@ducnmm
Copy link
Copy Markdown
Collaborator

ducnmm commented Mar 26, 2026

Hi @tamashi095 Thanks for the fix! Before approving, could you share a screenshot or recording of the e2e test passing with @ai-sdk/anthropic + streamText + system prompt? The unit tests look good, but I'd like to see proof the Anthropic error is actually resolved.

Could you include:

  • A log/screenshot showing the AI_UnsupportedFunctionalityError before the fix
  • A log/screenshot showing it working correctly after the fix

This helps verify the root cause and confirms the fix resolves it. Thanks!

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.

2 participants