Skip to content

fix(whatsapp): use private system prompt for natural assistant replies#402

Merged
onerandomdevv merged 7 commits into
devfrom
fix/whatsapp-private-prompt-natural-replies
Jun 9, 2026
Merged

fix(whatsapp): use private system prompt for natural assistant replies#402
onerandomdevv merged 7 commits into
devfrom
fix/whatsapp-private-prompt-natural-replies

Conversation

@SAHEED2010

@SAHEED2010 SAHEED2010 commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Adds a private-prompt natural answer path for Twizrr/shopping-related WhatsApp questions via Gemini function calling.
  • Supports the private WhatsApp system prompt from environment/config with a minimal safe committed fallback.
  • Validates Gemini-authored answers before sending them to WhatsApp and falls back safely when an answer is unsafe.

Scope

  • WhatsApp channel only.
  • No Prisma schema changes.
  • No auth core, payment/order, checkout, delivery, web app, shared package, or deployment config changes.
  • The full WhatsApp system prompt remains private and is not included in source.

Behavior

  • Adds the answer_twizrr_question Gemini function for natural Twizrr help, trust, account-linking, image-search, and company-identity questions.
  • Keeps consent, account linking, checkout/cart/wishlist/order/payment actions, delivery confirmation, disputes/refunds, Gemini errors, and generic errors backend-controlled.
  • Keeps product-like phrasing routed to product discovery, including buy-style search phrases, without creating cart/order/payment mutations.
  • Preserves account-link gates for unlinked users before personalized or state-changing actions.

Validation

  • Rejects empty, overlong, JSON-like, internal-field, unapproved founder/person, emoji-containing, and unsupported product/price/stock/delivery/payment claim answers.
  • Safe fallback is sent if validation fails.

Tests

  • npx.cmd jest src/channels/whatsapp --runInBand
  • pnpm.cmd run lint
  • npx.cmd tsc --noEmit
  • pnpm.cmd run build

Security Notes

  • .env.local was not committed.
  • No prompt content, raw phone numbers, OTPs, API keys, tokens, DB URLs, credentials, or other secrets were committed or printed.

Summary by CodeRabbit

  • New Features

    • Added direct handling of Twizrr product assistance questions in chat conversations
    • Expanded product search keyword recognition to include additional phrases
    • Implemented safety validation for AI-generated responses with fallback messaging
  • Tests

    • Added comprehensive test coverage for new prompt selection and response validation logic

@SAHEED2010 SAHEED2010 requested a review from onerandomdevv as a code owner June 8, 2026 16:37
@codesandbox

codesandbox Bot commented Jun 8, 2026

Copy link
Copy Markdown

Review or Edit in CodeSandbox

Open the branch in Web EditorVS CodeInsiders

Open Preview

@vercel

vercel Bot commented Jun 8, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
twizrr-web Ready Ready Preview, Comment Jun 9, 2026 5:05am

@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@onerandomdevv, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 22 minutes and 6 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 87c8f9ed-902e-43ce-bd31-75c8fc44b32a

📥 Commits

Reviewing files that changed from the base of the PR and between 3b358bc and f145d9a.

📒 Files selected for processing (3)
  • apps/backend/src/channels/whatsapp/whatsapp.constants.ts
  • apps/backend/src/channels/whatsapp/whatsapp.service.spec.ts
  • apps/backend/src/channels/whatsapp/whatsapp.service.ts
📝 Walkthrough

Walkthrough

This PR introduces a new answer_twizrr_question Gemini function to answer Twizrr-related help queries with validated natural text responses. System prompt selection logic is centralized in the intent service, intent detection is expanded to route Twizrr questions, and the response layer validates answers against safety patterns before sending.

Changes

WhatsApp Answer Intent Feature

Layer / File(s) Summary
Constants and Gemini function declarations
apps/backend/src/channels/whatsapp/whatsapp.constants.ts
Exports SAFE_NATURAL_ANSWER_FALLBACK and MINIMAL_WHATSAPP_SYSTEM_PROMPT constants; updates search_products description; adds answer_twizrr_question Gemini function declaration with topic enum and answer string schema.
Intent service system prompt centralization
apps/backend/src/channels/whatsapp/whatsapp-intent.service.ts, apps/backend/src/channels/whatsapp/whatsapp-intent.service.spec.ts
Introduces getSystemPrompt() and getPrivateSystemPrompt() helpers to select between private and minimal prompts; logs privatePromptConfigured flag during construction; adds Logger spy in tests with setup/teardown; verifies prompt selection logic and ensures prompt content is not logged.
Intent detection expansion for answer and search intents
apps/backend/src/channels/whatsapp/whatsapp-intent.service.ts, apps/backend/src/channels/whatsapp/whatsapp-intent.service.spec.ts
Extends search_products keyword matching with "do you have" and "can i get"; adds keyword block for Twizrr-related phrases routing to answer_twizrr_question; tests validate Gemini parsing of answer function calls and fallback routing when Gemini is unconfigured.
WhatsApp service response handling and safe-answer validation
apps/backend/src/channels/whatsapp/whatsapp.service.ts, apps/backend/src/channels/whatsapp/whatsapp.service.spec.ts
Adds answer_twizrr_question switch case calling getSafeNaturalAnswer(); excludes answer intent from account-action path; reworks isAccountActionRequest() keyword sets based on intent type; implements getSafeNaturalAnswer() with validators rejecting JSON, emoji, forbidden terms, and unsupported claims; tests cover natural-answer sending, unsafe fallbacks, and cart-action routing.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant WhatsAppService
  participant IntentService
  participant GeminiClient
  participant SafeValidator
  
  User->>WhatsAppService: send "how do I verify account"
  WhatsAppService->>IntentService: parseMessage()
  IntentService->>GeminiClient: parseFunctionCall(systemPrompt)
  GeminiClient-->>IntentService: { functionName: "answer_twizrr_question", params: { topic: "verification", answer: "..." } }
  IntentService-->>WhatsAppService: return parsed intent
  WhatsAppService->>SafeValidator: getSafeNaturalAnswer(params)
  SafeValidator->>SafeValidator: validate answer (no JSON, emoji, forbidden terms)
  SafeValidator-->>WhatsAppService: return safe answer or fallback
  WhatsAppService->>User: send validated text response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • coded-devs/twizrr#397: Both PRs refactor WhatsAppIntentService.parseIntent to manage the Gemini systemPrompt passed to geminiClient.parseFunctionCall; this PR centralizes via getSystemPrompt() while the related PR enforces function-calling constraints.

Suggested reviewers

  • onerandomdevv

🐰 A question floats in on WhatsApp's breeze,
The Twizrr bot answers with practiced ease,
But guards the truth with careful care,
No JSON sneaks, no emoji there!
Safe answers flow from nature's source.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and specifically refers to the main change: introducing a private system prompt for natural assistant replies in WhatsApp.
Description check ✅ Passed The description comprehensively addresses all template sections including what changed, type of change, area affected, testing instructions, and pre-commit checks; security notes are also provided.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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
  • Commit unit tests in branch fix/whatsapp-private-prompt-natural-replies

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.

Comment thread apps/backend/src/channels/whatsapp/whatsapp.constants.ts Outdated
Comment thread apps/backend/src/channels/whatsapp/whatsapp.service.ts
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Autofix skipped. No unresolved CodeRabbit review comments with fix instructions found.

@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Autofix skipped. No unresolved CodeRabbit review comments with fix instructions found.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@onerandomdevv

Copy link
Copy Markdown
Collaborator

PR #402 follow-up: support_handoff remains declared and is now handled deterministically in WhatsAppService with safe Twizrr support copy that does not claim live human handoff. Added/updated focused WhatsAppService coverage for Gemini selecting support_handoff; existing WhatsApp channel tests still cover consent before AI/search, guest product discovery after consent, account/order/checkout/payment/delivery gates, product-like buy phrasing, natural-answer validation, and no private prompt logging. Branch was refreshed from latest origin/dev via merge before the follow-up commit. Validation passed: pnpm --filter @twizrr/backend test -- channels/whatsapp; pnpm --filter @twizrr/backend test -- modules/auth/auth.service.spec.ts -t 'WhatsApp phone'; npx tsc -p apps/backend/tsconfig.build.json --noEmit; pnpm --filter @twizrr/backend run build; touched-file ESLint; git diff --check; staged security-sentinel scan. Confirmed no .env.local changes, no silent User.phone identity matching changes, and no unrelated delivery/auth/payment/web code edits in the follow-up commit.

@onerandomdevv onerandomdevv merged commit b1a8ace into dev Jun 9, 2026
10 checks passed
@onerandomdevv onerandomdevv deleted the fix/whatsapp-private-prompt-natural-replies branch June 9, 2026 05:17
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