Skip to content

Conversation

sid597
Copy link
Collaborator

@sid597 sid597 commented May 6, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a new capability for generating and ranking related discourse suggestions based on semantic relationships.
    • Enhanced relevance of suggested nodes through improved semantic matching and ranking.
    • Improved error handling and robustness during the suggestion process.
    • Added flexible embedding generation with customizable model, dimensions, and encoding options.
    • Enhanced API stability by handling missing API keys gracefully with clear error responses.

Copy link

linear bot commented May 6, 2025

Copy link

vercel bot commented May 6, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
discourse-graph ⬜️ Skipped (Inspect) May 16, 2025 6:49pm

Copy link
Contributor

coderabbitai bot commented May 6, 2025

📝 Walkthrough

Walkthrough

A new TypeScript module, hyde.ts, is introduced to generate and rank hypothetical related discourse nodes using semantic embeddings and relation types. It defines relevant types, core functions for node generation via an external API, embedding, searching, ranking, and a main orchestration function with robust error handling for the entire process. Additionally, the OpenAI embedding API route is updated to handle missing API keys gracefully and accept optional parameters for model, dimensions, and encoding format.

Changes

File(s) Change Summary
apps/roam/src/utils/hyde.ts New module providing types and functions for generating, embedding, searching, and ranking hypothetical nodes.
apps/website/app/api/embeddings/openai/small/route.ts Updated embedding API route to handle missing API keys without throwing, accept optional parameters, and use them dynamically.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant hyde.ts
    participant ClaudeAPI
    participant EmbeddingFunc
    participant SearchFunc

    Caller->>hyde.ts: findSimilarNodesUsingHyde(candidateNodes, currentNodeText, relationTriplets)
    loop For each relationTriplet
        hyde.ts->>ClaudeAPI: generateHypotheticalNode(currentNodeText, relationTriplet)
        ClaudeAPI-->>hyde.ts: hypotheticalNodeText
    end
    hyde.ts->>EmbeddingFunc: embed hypotheticalNodeTexts
    hyde.ts->>SearchFunc: searchAgainstCandidates(embeddings, candidateNodes)
    hyde.ts->>hyde.ts: combineScores(searchResults)
    hyde.ts->>hyde.ts: rankNodes(combinedScores)
    hyde.ts-->>Caller: suggestedNodes
Loading

Possibly related PRs

Poem

In the warren of code, a new path appears,
Where hyde’s clever logic now volunteers.
It ponders, it ranks, with embeddings it peers,
Through nodes and relations, connections it steers.
With a hop and a skip, suggestions arise—
A rabbit’s delight, both thoughtful and wise! 🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sid597 sid597 changed the base branch from main to add-embedding-endpoint May 6, 2025 14:58
@sid597
Copy link
Collaborator Author

sid597 commented May 6, 2025

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented May 6, 2025

✅ Actions performed

Full review triggered.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (2)
apps/roam/src/utils/hyde.ts (2)

158-175: Expose a topK parameter for callers to control result set size

rankNodes currently returns all candidates sorted by score. This leaks low-confidence suggestions, increases bandwidth, and can overwhelm clients. Accept a topK option (default ≈ 20) and slice the result.


1-13: Minor: prefer interface for extensibility

For publicly exported shapes (CandidateNodeWithEmbedding, SuggestedNode) consider using interface instead of type – users can extend them via declaration merging.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7c4685c and 7c0e97d.

📒 Files selected for processing (1)
  • apps/roam/src/utils/hyde.ts (1 hunks)

@sid597
Copy link
Collaborator Author

sid597 commented May 6, 2025

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented May 6, 2025

✅ Actions performed

Full review triggered.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
apps/roam/src/utils/hyde.ts (2)

45-55: ⚠️ Potential issue

Prompt interpolation can still be broken by rogue back-ticks
Escaping with \``helps, but an input containing `` ``` `` followed by newlines will still terminate the fence and let the user smuggle content or system directives (classic prompt-injection). Consider fencing the variables in JSON (or base-64-encoding) instead of Markdown, or at least replacing back-ticks innode, relationLabel`, etc.

(Previous review raised the same concern.)


33-38: 🛠️ Refactor suggestion

Expose endpoint & timeout through environment variables
Hard-coding ANTHROPIC_API_URL and ANTHROPIC_REQUEST_TIMEOUT_MS forces a rebuild for every config change and makes local testing cumbersome. Reading them from process.env (with sane fall-backs) keeps the code flexible and consistent with how you already handle the model name.

-export const ANTHROPIC_API_URL =
-  "https://discoursegraphs.com/api/llm/anthropic/chat";
+export const ANTHROPIC_API_URL =
+  process.env.ANTHROPIC_API_URL ??
+  "https://discoursegraphs.com/api/llm/anthropic/chat";
@@
-export const ANTHROPIC_REQUEST_TIMEOUT_MS = 30_000;
+export const ANTHROPIC_REQUEST_TIMEOUT_MS = Number(
+  process.env.ANTHROPIC_REQUEST_TIMEOUT_MS ?? 30_000,
+);
🧹 Nitpick comments (2)
apps/roam/src/utils/hyde.ts (2)

78-85: Trim surrounding quotes/markdown artefacts from LLM output
Claude often wraps responses in quotes or code fences. Down-stream ranking treats the text literally, so "Some fact" vs Some fact would hash to different embeddings. A small clean-up step prevents semantic duplicates.

-    return body.completion.trim();
+    return body.completion
+      .trim()
+      .replace(/^```(markdown)?\s*/i, "")
+      .replace(/```$/, "")
+      .replace(/^["']|["']$/g, "")
+      .trim();

157-163: Add topK limit before returning to avoid overwhelming the UI
rankNodes currently returns all candidates, which could be hundreds. Consider slicing to the caller-requested topK (default 20?) to keep transport and rendering light, and avoid showing marginally-relevant results.

   combinedResults.sort((a, b) => b.score - a.score);
-  return combinedResults.map((item) => ({
+  const topK = 20; // make this a parameter or env var
+  return combinedResults.slice(0, topK).map((item) => ({
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eaa9c8f and 0033fb1.

📒 Files selected for processing (1)
  • apps/roam/src/utils/hyde.ts (1 hunks)
🔇 Additional comments (1)
apps/roam/src/utils/hyde.ts (1)

108-125: Parallel search implementation looks great
Switching to Promise.all removes the N-round-trip latency bottleneck and the defensive try/…catch keeps partial failures contained. Nice improvement!

@sid597 sid597 requested a review from mdroidian May 7, 2025 18:09
Copy link
Contributor

@mdroidian mdroidian left a comment

Choose a reason for hiding this comment

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

A few questions/change requests

Base automatically changed from add-embedding-endpoint to eng-233-suggestive-mode-internal May 8, 2025 04:10
@sid597
Copy link
Collaborator Author

sid597 commented May 16, 2025

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented May 16, 2025

✅ Actions performed

Full review triggered.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
apps/roam/src/utils/hyde.ts (1)

131-136: ⚠️ Potential issue

LLM response assumed to be plain text – may break when JSON is returned

Earlier feedback (now reverted) highlighted that the endpoint often returns JSON ({ completion: "..." }). Relying on response.text() silently returns [object Object] when the payload format changes, cascading bad prompts downstream.

-    return await response.text();
+    const body = await response.json().catch(() => null);
+    if (!body || typeof body.completion !== "string") {
+      throw new Error("Unexpected payload from LLM endpoint");
+    }
+    return body.completion.trim();

Please reinstate structured parsing to avoid subtle failures and allow better error messages.

🧹 Nitpick comments (4)
apps/website/app/api/embeddings/openai/small/route.ts (2)

61-63: Validate dimensions range & model compatibility before forwarding to OpenAI

dimensions is only accepted for text-embedding-3* models and must be within the range supported by the chosen model (currently 1-→1536 for -small and 1-→3072 for -large). Forwarding an out-of-range value will trigger a 400 from OpenAI.

 if (dimensions && model.startsWith("text-embedding-3")) {
-  options.dimensions = dimensions;
+  if (
+    (model.endsWith("-small") && dimensions > 1536) ||
+    (model.endsWith("-large") && dimensions > 3072) ||
+    dimensions < 1
+  ) {
+    return cors(
+      req,
+      NextResponse.json(
+        { error: "`dimensions` out of range for selected model." },
+        { status: 400 },
+      ),
+    ) as NextResponse;
+  }
+  options.dimensions = dimensions;
 }

This prevents unnecessary upstream calls and returns an actionable error to the client.


65-71: Promise.race timeout doesn’t cancel the OpenAI request

The pending openai!.embeddings.create call continues to run in the background even after the timeout fires, consuming resources and counting against rate limits.
Wrap the call in an AbortController so both the caller and the underlying request are aborted:

-const embeddingsPromise = openai!.embeddings.create(options);
+const abortController = new AbortController();
+const embeddingsPromise = openai!.embeddings.create({
+  ...options,
+  signal: abortController.signal as any, // OpenAI typings don’t expose `signal` yet
+});
 ...
 const openAIResponse = await Promise.race([embeddingsPromise, timeoutPromise])
   .finally(() => abortController.abort());

This keeps the worker process clean and avoids leaking concurrent connections.

apps/roam/src/utils/hyde.ts (2)

137-148: Error strings leak internal details to callers

Returning a literal string that embeds the raw error.message will surface stack traces, hostnames or API keys to the UI/log stream. Instead return a generic message and log the detailed error server-side (already done).

-    return `Error: Failed to generate hypothetical node. ${
-      error instanceof Error ? error.message : String(error)
-    }`;
+    return "Error: Failed to generate hypothetical node.";

This keeps user-visible output clean while retaining full diagnostics in server logs.


188-201: Potentially massive payload – batch subsetRoamUids or fall back to local cosine

All candidate UIDs are sent in one RPC call. With thousands of nodes this will blow past URL/JSON limits and slow Supabase.

Consider:

  1. Chunk subsetRoamUids into e.g. 500-item batches and merge the results client-side.
  2. When indexData already contains embeddings, compute cosine similarity locally for small datasets and skip the HTTP round-trip.

Implementing either strategy will improve robustness and reduce latency for large graphs.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d3fcd5 and e5290c0.

📒 Files selected for processing (2)
  • apps/roam/src/utils/hyde.ts (1 hunks)
  • apps/website/app/api/embeddings/openai/small/route.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/roam/src/utils/hyde.ts (1)
apps/roam/src/utils/types.ts (1)
  • Result (42-46)
🔇 Additional comments (2)
apps/website/app/api/embeddings/openai/small/route.ts (1)

27-36: Graceful fallback for missing OPENAI_API_KEY looks good

Early-returning a structured 500 JSON response avoids throwing and still honours CORS. Nice touch!

apps/roam/src/utils/hyde.ts (1)

303-314:

❌ Incorrect review comment

type shadowing risk – reserve the key or rename

type is added to CandidateNodeWithEmbedding but Result already allows arbitrary keys. If the original Roam node object contains its own type field, this will silently overwrite the value when you strip embedding:

const { embedding, ...restOfNode } = fullNode; // `type` ambiguity

Safer to namespace the helper metadata, e.g. nodeType or _dgType, to avoid collisions.

-export type CandidateNodeWithEmbedding = Result & {
-  type: string;
+export type CandidateNodeWithEmbedding = Result & {
+  hydeType: string;
   embedding: EmbeddingVectorType;
 };

Update downstream destructuring accordingly.


🏁 Script executed:

#!/bin/bash
# Locate the definition of CandidateNodeWithEmbedding
rg "export type CandidateNodeWithEmbedding" -n -A3 -B3 apps/roam/src/utils/hyde.ts

Length of output: 256


🏁 Script executed:

#!/bin/bash
# Show imports and type definitions at top of the file, plus occurrences of `Result`
sed -n '1,80p' apps/roam/src/utils/hyde.ts
echo "----- Occurrences of Result -----"
rg -n "Result" -C2 apps/roam/src/utils/hyde.ts

Length of output: 4527


Ignore type rename—no shadowing in practice
The only type property on these nodes comes from your own CandidateNodeWithEmbedding/SuggestedNode aliases; the original Roam‐fetched objects here only carry uid and text. When you do

const { embedding, ...restOfNode } = fullNode;

restOfNode.type is always the custom field you declared, and there’s nothing for it to collide with. No downstream code pulls in any other type key, so you can leave the definition as-is.

Likely an incorrect or invalid review comment.

@sid597 sid597 merged commit 1a80026 into eng-233-suggestive-mode-internal May 16, 2025
5 checks passed
@github-project-automation github-project-automation bot moved this to Done in General May 16, 2025
@sid597 sid597 deleted the hyde-utility branch May 17, 2025 07:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants