Skip to content

fix(backend): include short conversations in RAG context - #8311

Closed
ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/rag-short-conversation-dropped
Closed

ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/rag-short-conversation-dropped

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

get_better_conversation_chunk in the RAG retrieval pipeline assembles each matched conversation into a shared context_data dict that the caller later joins into the model's context. For conversations under 250 tokens the function returned the rendered text instead of writing it into context_data, and the caller ignores the return value. The result is that short conversations were silently dropped from the assembled RAG context, so chat answers that depended on a brief conversation lost that source with no error. This PR writes the short-conversation render into context_data[memory.id], the same place the long-conversation branch already writes, so the caller picks it up.

Root cause

In backend/utils/retrieval/rag.py, get_better_conversation_chunk takes a context_data: dict argument and is meant to mutate it. The long branch does exactly that, but the short branch returns instead:

def get_better_conversation_chunk(
    memory: Conversation, topics: List[str], context_data: dict, people: List[Person] = None, user_name: str = None
) -> str:
    logger.info(f'get_better_memory_chunk {memory.id} {topics}')
    conversation = TranscriptSegment.segments_as_string(
        memory.transcript_segments, include_timestamps=True, people=people, user_name=user_name
    )
    if num_tokens_from_string(conversation) < 250:
        return conversations_to_string([memory], people=people, user_name=user_name)
    chunk = chunk_extraction(memory.transcript_segments, topics, people=people, user_name=user_name)
    if not chunk or len(chunk) < 10:
        return
    context_data[memory.id] = chunk

The caller retrieve_rag_conversation_context runs these through db_executor and never looks at what they return:

futures = [
    db_executor.submit(
        get_better_conversation_chunk, m, memories_id_to_topics.get(m.id, []), context_data, people, user_name
    )
    for m in memories
]
for f in futures:
    f.result()
context_str = '\n'.join(context_data.values()).strip()

f.result() is called only to surface exceptions; the value is discarded. The assembled context comes entirely from context_data.values(). So when a conversation is under 250 tokens, its rendered text is returned into a future that nobody reads, and it never reaches context_str. There is no exception, the answer is just built from fewer sources than it should be. Longer conversations are unaffected because they write into context_data directly.

Fix

Make the short branch follow the same contract as the rest of the function: write into context_data keyed by memory.id, then return None.

    if num_tokens_from_string(conversation) < 250:
        context_data[memory.id] = conversations_to_string([memory], people=people, user_name=user_name)
        return

Both branches now mutate context_data and return nothing, which is what the caller expects. Behavior for conversations of 250 tokens or more is unchanged.

Testing

Added backend/tests/unit/test_rag_short_conversation_dropped.py (registered in backend/test.sh). utils.retrieval.rag has a heavy database and utils import graph, so the test imports it under a meta-path stub finder that resolves those imports to stubs while keeping utils.retrieval.rag real, then patches the module-level helpers (num_tokens_from_string, conversations_to_string, chunk_extraction, and TranscriptSegment.segments_as_string) and calls get_better_conversation_chunk directly. One case drives a short conversation (token count below 250) and asserts the rendered chunk lands in context_data[memory.id] and is visible via context_data.values(), the exact path the caller consumes, and that chunk_extraction is not called and the function returns None. A second case checks the long-conversation branch still writes its extracted chunk into context_data. Verified red to green: the test fails on current main and passes with this change.

PR status check

No open PR changes this logic. This context_data write does not appear anywhere in the history of backend/utils/retrieval/rag.py, so it is not a previously reverted fix being resubmitted. No filed GitHub issue matches.

Review in cubic

@cubic-dev-ai cubic-dev-ai 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.

1 issue found across 3 files

Confidence score: 5/5

  • In backend/utils/retrieval/rag.py, the function’s return annotation says str but it now always returns None, which can mislead callers and static type checks into handling the result incorrectly; this is low runtime risk but can cause subtle integration mistakes later — update the annotation (or return value) to match actual behavior before or shortly after merging.

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

Comment thread backend/utils/retrieval/rag.py Resolved
@Git-on-my-level

Copy link
Copy Markdown
Member

Hi @ZachL111 — thank you for finding and writing up this retrieval/output semantic correctness issue. We consolidated this group into a smaller aggregate PR with shared semantic models/helpers and focused tests: #8366.

Your original discovery, reproduction details, and candidate fix are credited in the new PR body and commit metadata. I’m closing this individual PR as superseded by #8366, not because the issue is invalid. Thanks again for surfacing it.

@Git-on-my-level

Copy link
Copy Markdown
Member

Superseded by #8366. Thanks again @ZachL111 — credited there for the original discovery and candidate fix.

@github-actions

Copy link
Copy Markdown
Contributor

Hey @ZachL111 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our roadmap and vision

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community! 💜

Git-on-my-level added a commit that referenced this pull request Jun 26, 2026
## Summary

Supersedes #8290, #8291, #8306, #8310, #8311, #8313, #8319, #8320.

Original issue discovery, reproductions, and candidate fixes by
@ZachL111.

This aggregates the retrieval/output semantic correctness fixes into one
focused backend PR:

- adds shared conversation metadata keys/model and uses them for vector
metadata production + reranking
- fixes metadata entity extraction so entities no longer copy topics
- refactors RAG chunking through a pure `build_conversation_context(...)
-> str | None` path so short conversations are included consistently
- separates calendar deletion successes from failures before building
user-visible output
- normalizes merge/photo timestamps through a UTC-aware helper and keeps
malformed/missing photo dates with a structured warning
- makes proactive-notification cache setters keyword-only for `app_id`
to prevent passing an `App` object as the cache key
- validates daily-summary LLM JSON with a Pydantic payload, falls back
only on JSON/model-validation failures, and stops logging raw LLM output
- safely handles Google contacts with absent names while preserving
email extraction

## Included Zach PRs

Included/redesigned in this aggregate: #8290, #8291, #8306, #8310,
#8311, #8313, #8319, #8320.

Deferred from this aggregate: none.

## Tests

- `cd backend && ./scripts/sync-python-deps.sh`
- `cd backend && source .venv/bin/activate && pytest
tests/unit/test_retrieval_semantics.py
tests/unit/test_daily_summary_regenerate.py
tests/unit/test_daily_summary_race_condition.py
tests/unit/test_conversations_to_string.py`
- `cd backend && source .venv/bin/activate && python -m py_compile
models/conversation_metadata.py models/calendar_mutation.py
models/daily_summary_payload.py utils/conversations/datetime_utils.py
utils/conversations/merge_conversations.py utils/retrieval/rag.py
utils/llm/chat.py utils/llm/external_integrations.py
utils/retrieval/tools/calendar_tools.py database/mem_db.py
database/redis_db.py database/vector_db.py
tests/unit/test_retrieval_semantics.py`
- `cd backend && bash testing/e2e/run.sh` — 73 passed, 6 skipped

Also ran `python backend/scripts/scan_async_blockers.py` from repo root;
it exits 0 and reports existing async-blocker findings unrelated to this
PR. Running it from `backend/` currently fails with `Error:
backend/routers not found`, so root invocation was used.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/8366?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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