Skip to content

Conversation

sid597
Copy link
Collaborator

@sid597 sid597 commented Jun 22, 2025

https://www.loom.com/share/44125280d2eb4aec921b0933e8e27ee3?sid=b17f08dc-372c-45ab-88c0-4209cb50e250

Loom does not have access to console log so adding a screenshot of the console.log

image

Tested using stub code that fetches 5 discourse nodes from graph and creates embeddings for them using this function

Summary by CodeRabbit

  • New Features
    • Introduced the ability to fetch and attach vector embeddings to content nodes, enhancing data with additional model and vector information.

Copy link

linear bot commented Jun 22, 2025

Copy link

vercel bot commented Jun 22, 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) Jun 22, 2025 10:36am

Copy link
Contributor

coderabbitai bot commented Jun 22, 2025

📝 Walkthrough

Walkthrough

A new type alias, DiscourseGraphContent, has been added to define the structure of discourse graph nodes. Additionally, a utility function, fetchEmbeddingsForNodes, was introduced to batch-fetch vector embeddings for these nodes from an external API, augmenting each node with its corresponding embedding and model identifier.

Changes

File(s) Change Summary
apps/roam/src/utils/types.ts Added the DiscourseGraphContent type alias defining node structure with text and vector fields.
apps/roam/src/utils/fetchEmbeddingsForNodes.ts.ts Introduced fetchEmbeddingsForNodes function to batch-fetch and attach embeddings to nodes.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant fetchEmbeddingsForNodes
    participant EmbeddingAPI

    Caller->>fetchEmbeddingsForNodes: Provide array of DiscourseGraphContent nodes
    loop For each batch of 100 nodes
        fetchEmbeddingsForNodes->>EmbeddingAPI: POST /api/embeddings with batch texts
        EmbeddingAPI-->>fetchEmbeddingsForNodes: Return embeddings array
    end
    fetchEmbeddingsForNodes-->>Caller: Return nodes augmented with model and vector
Loading

Possibly related PRs

Suggested reviewers

  • mdroidian

Poem

In the warren where data flows,
A new type for discourse now grows.
With vectors fetched in tidy batches,
Each node a story, each node matches.
Embeddings hop from API to code,
Mapping meaning on the rabbit’s road. 🐇✨

✨ 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
Copy link
Collaborator Author

sid597 commented Jun 22, 2025

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Jun 22, 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: 1

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

18-18: Consider making the API URL configurable.

The API URL is hardcoded, which may make it difficult to use different environments or endpoints. Consider making this configurable through environment variables or configuration.

-  const apiUrl = `https://discoursegraphs.com/api/embeddings/openai/small`;
+  const apiUrl = process.env.EMBEDDINGS_API_URL || `https://discoursegraphs.com/api/embeddings/openai/small`;

66-66: Consider making the model name configurable.

The model name is hardcoded and should ideally match the API endpoint or be configurable to maintain consistency across different embedding models.

-    model: "openai_text_embedding_3_small_1536",
+    model: process.env.EMBEDDING_MODEL_NAME || "openai_text_embedding_3_small_1536",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a0a6082 and 5040e8e.

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

50-59: LGTM! Well-structured type definition.

The DiscourseGraphContent type is well-defined with appropriate property types and follows consistent naming conventions. The vector property as number[] correctly represents embedding vectors.

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

11-69: Excellent implementation with robust error handling.

The function is well-structured with:

  • Proper batch processing to handle large datasets
  • Comprehensive error handling for HTTP and data validation
  • Clear error messages with batch information
  • Validation that input and output counts match
  • Good TypeScript typing throughout

The implementation effectively handles the complexity of batch processing while maintaining data integrity.

@sid597
Copy link
Collaborator Author

sid597 commented Jun 22, 2025

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Jun 22, 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: 2

🔭 Outside diff range comments (1)
apps/roam/src/utils/fetchEmbeddingsForNodes.ts.ts (1)

1-70: Fix the filename extension.

The file has a double .ts.ts extension which is incorrect and may cause build issues.

Rename the file from fetchEmbeddingsForNodes.ts.ts to fetchEmbeddingsForNodes.ts.

🧹 Nitpick comments (4)
apps/roam/src/utils/types.ts (1)

50-59: Consider making embedding-related fields optional.

The type definition looks good overall, but consider whether model and vector fields should be optional since nodes may not have embeddings initially before processing through fetchEmbeddingsForNodes.

 export type DiscourseGraphContent = {
   author_local_id: string;
   source_local_id: string;
   scale: string;
   created: string;
   last_modified: string;
   text: string;
-  model: string;
-  vector: number[];
+  model?: string;
+  vector?: number[];
 };

This would allow the type to represent both input nodes (without embeddings) and output nodes (with embeddings) from the utility function.

apps/roam/src/utils/fetchEmbeddingsForNodes.ts.ts (3)

32-46: Improve error handling robustness.

The error handling could be more robust. The current implementation may fail to parse error responses properly in some cases.

     if (!response.ok) {
-      let errorData;
+      let errorMessage = `Server responded with ${response.status}`;
       try {
-        errorData = await response.json();
+        const errorData = await response.json();
+        errorMessage = errorData.error || errorData.message || errorMessage;
       } catch (e) {
-        errorData = {
-          error: `Server responded with ${response.status}: ${await response.text()}`,
-        };
+        try {
+          const textResponse = await response.text();
+          errorMessage = textResponse || errorMessage;
+        } catch (textError) {
+          // Use default error message
+        }
       }
       throw new Error(
-        `API Error (${response.status}) processing batch ${
-          i / EMBEDDING_BATCH_SIZE + 1
-        }: ${errorData.error || "Failed to fetch embeddings"}`,
+        `API Error (${response.status}) processing batch ${
+          i / EMBEDDING_BATCH_SIZE + 1
+        }: ${errorMessage}`,
       );
     }

66-66: Make model name consistent with API endpoint.

The hardcoded model name should match the API endpoint being used or be configurable.

+const EMBEDDING_MODEL = "openai_text_embedding_3_small_1536";
+
 export const fetchEmbeddingsForNodes = async (
   nodes: DiscourseGraphContent[],
 ): Promise<DiscourseGraphContent[]> => {
   // ... rest of function
   return nodes.map((node, i) => ({
     ...node,
-    model: "openai_text_embedding_3_small_1536",
+    model: EMBEDDING_MODEL,
     vector: allEmbeddings[i],
   })) as DiscourseGraphContent[];

This ensures consistency and makes it easier to update if the model changes.


11-69: Consider adding rate limiting and retry logic.

For production use with external APIs, consider adding rate limiting and retry logic to handle temporary failures gracefully.

The function currently makes all API calls without any delay or retry mechanism. For better reliability:

  1. Add retry logic for transient failures (network timeouts, 5xx errors)
  2. Add exponential backoff between retries
  3. Consider adding a delay between batches to respect API rate limits
  4. Add timeout configuration for fetch requests

This would make the function more robust in production environments where network issues or API rate limits may occur.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a0a6082 and 9488006.

📒 Files selected for processing (2)
  • apps/roam/src/utils/fetchEmbeddingsForNodes.ts.ts (1 hunks)
  • apps/roam/src/utils/types.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/roam/src/utils/fetchEmbeddingsForNodes.ts.ts (1)
apps/roam/src/utils/types.ts (1)
  • DiscourseGraphContent (50-59)

@sid597 sid597 requested a review from mdroidian June 22, 2025 10:42
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 changes.

@sid597 sid597 requested a review from mdroidian June 26, 2025 10:57
@mdroidian mdroidian merged commit 05553f8 into main Jun 26, 2025
4 checks passed
@mdroidian mdroidian deleted the eng-449-calculate-the-embeddings-or-updated-discourse-nodes-v2 branch June 26, 2025 18:20
@github-project-automation github-project-automation bot moved this to Done in General Jun 26, 2025
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