Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Additional insertAt options, add support for postprocessors to templated prompts #68

Merged
merged 8 commits into from
Sep 9, 2024

Conversation

justyns
Copy link
Owner

@justyns justyns commented Sep 9, 2024

Initial support for the use-cases described in #59

insertAt now allows these values:
"cursor",
"page-start",
"page-end",
"start-of-line",
"end-of-line",
"start-of-item",
"end-of-item",
"new-line-above",
"new-line-below",
"replace-line",

Templated Prompts also now have a new postProcessors option. It's a list of space-script functions. After the template prompt is executed and finished streaming, the full response is sent to each post processor function. That post processor function can then manipulate the response data if needed and return the modified version.

As a demo, I'm using it to ensure the response from the llm is a list of markdown tasks and also indented as subtasks:

ai-split-tasks

Summary by CodeRabbit

  • New Features

    • Introduced an AI prompt to help users break down larger tasks into smaller components using the aiSplitTodo command.
    • Added functionality to convert strings into bullet lists and markdown task lists.
    • Enhanced text formatting with new scripts for indentation and removing duplicate lines.
  • Improvements

    • Expanded capabilities of text manipulation functions for better usability.
    • Enhanced response handling in AI chat interactions with new callback options.
  • Bug Fixes

    • Improved error handling for prompt insertion and text processing.
  • Documentation

    • Updated documentation to reflect new features and enhancements.

Enhance the enrichChatMessages function to include optional
global metadata. This allows for injecting global information
into the chat message enrichment process.

- Update function signature to accept globalMetadata
- Merge globalMetadata into the template context
Enhance the functionality of `insertAt` by adding more options to
facilitate better template responses. This includes support for
inserting at various points within lines, items, and surrounding
lines.

- Added insertAt options:
  - "start-of-line"
  - "end-of-line"
  - "start-of-item"
  - "end-of-item"
  - "new-line-above"
  - "new-line-below"
  - "replace-line"
- Updated global metadata structure to support additional options
- Implemented logic for new insertAt cases
- Enhance `.gitignore` to exclude `docs/Library/Core`
- Export utility functions in `editorUtils.ts` for line
  operations based on text position
- Modify `Provider.ts` to handle post-processors in
  `AbstractProvider`, processing data after response is complete
- Update `prompts.ts` to support post-processors in AI prompt
  templates
- Extend `StreamChatOptions` in `types.ts` to include
  `postProcessors` array
- Define `PostProcessorData` type to pass context to post-processors
- Introduced `convertToBulletList` for transforming strings into bullet lists
- Added `convertToTaskList` to ensure each line in a string is a markdown task
- Implemented `indentOneLevel` to indent lines based on the previous line
- Created `removeDuplicateStart` to remove the first line if it's a duplicate

These functions enhance the utility of space scripts, making them more versatile.
Copy link
Contributor

coderabbitai bot commented Sep 9, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

Walkthrough

This pull request introduces enhancements to task management and text processing capabilities within the application. It adds new AI prompts and space scripts for task decomposition, string conversion to bullet and task lists, and improved text formatting. Additionally, modifications to existing functions increase their accessibility and functionality, particularly in handling AI responses and managing metadata. These changes aim to streamline user interactions and improve task organization.

Changes

File Path Change Summary
docs/Library/AICore/AIPrompt/AI Split Task.md Introduced AI prompt for task decomposition with metadata, slash command, and post-processing functions.
docs/Library/AICore/Space Script/AI Query LLM.md Added meta tag for improved document categorization.
docs/Library/AICore/Space Script/AI Search Embeddings.md Added meta tag for improved document categorization.
docs/Library/AICore/Space Script/Convert to bullets.md Defined a function to convert strings to bullet lists.
docs/Library/AICore/Space Script/Convert to task list.md Defined a function to convert strings to markdown task lists.
docs/Library/AICore/Space Script/Indent lines.md Defined a function to indent lines based on a reference line.
docs/Library/AICore/Space Script/Remove Duplicate Start.md Defined a function to remove duplicate starting lines from responses.
src/editorUtils.ts Changed visibility of functions and added new functions for text manipulation.
src/interfaces/Provider.ts Modified AbstractProvider to include new options for response handling.
src/prompts.ts Enhanced prompt insertion functions with new template handling and error management.
src/providers/ollama.ts Updated chatWithAI method to include onResponseComplete callback.
src/providers/openai.ts Updated StreamChatOptions to include onResponseComplete and modified related methods.
src/types.ts Enhanced StreamChatOptions and defined PostProcessorData type.

Possibly related PRs

Tip

New features

Walkthrough comment now includes:

  • Possibly related PRs: A list of potentially related PRs to help you recall past context.
  • Suggested labels: CodeRabbit can now suggest labels by learning from your past PRs. You can also provide custom labeling instructions in the UI or configuration file.

Notes:

  • Please share any feedback in the discussion post on our Discord.
  • Possibly related PRs, automatic label suggestions based on past PRs, learnings, and possibly related issues require data opt-in (enabled by default).

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @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.

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 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.

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: 7

Outside diff range, codebase verification and nitpick comments (5)
docs/Library/AICore/Space Script/Remove Duplicate Start.md (1)

11-25: Approve the logic but consider removing debug logs.

The function correctly implements the logic to remove duplicate lines at the start of the response. However, consider removing or replacing console.log statements with a more appropriate logging mechanism if this script is intended for production use.

src/interfaces/Provider.ts (1)

Line range hint 52-131: Approve the integration of new features, suggest improvements for type safety and simplification.

The modifications to the streamChatIntoEditor method in the AbstractProvider class effectively integrate the new onResponseComplete and postProcessors features, enhancing the method's functionality.

However, consider the following improvements:

  • Use more specific types than any for callback parameters to enhance type safety.
  • Simplify the new logic to improve readability and maintainability, possibly by breaking down the method into smaller, more focused functions.
src/providers/openai.ts (2)

15-15: Consider specifying the type of data in onResponseComplete.

The addition of onResponseComplete as an optional callback in StreamChatOptions is correctly implemented. However, specifying the type of data more precisely than any could enhance type safety and code clarity.


Line range hint 56-104: Effective use of onResponseComplete in streamChat.

The integration of onResponseComplete in the streamChat method is well-implemented, with the callback being correctly invoked at the end of the stream and upon the "end" event. It is advisable to consider adding error handling around the callback invocation to manage any potential exceptions that might arise from the callback execution.

src/prompts.ts (1)

37-37: Suggestion: Remove commented-out debug code.

To maintain a clean codebase, consider removing the commented-out console log unless it's intended for future debugging purposes.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 65eaa1b and 1488c4e.

Files ignored due to path filters (2)
  • .gitignore is excluded by none and included by none
  • scripts/create-test-space.sh is excluded by none and included by none
Files selected for processing (14)
  • docs/Library/AICore/AIPrompt/AI Split Task.md (1 hunks)
  • docs/Library/AICore/Space Script/AI Query LLM.md (1 hunks)
  • docs/Library/AICore/Space Script/AI Search Embeddings.md (1 hunks)
  • docs/Library/AICore/Space Script/Convert to bullets.md (1 hunks)
  • docs/Library/AICore/Space Script/Convert to task list.md (1 hunks)
  • docs/Library/AICore/Space Script/Indent lines.md (1 hunks)
  • docs/Library/AICore/Space Script/Remove Duplicate Start.md (1 hunks)
  • src/editorUtils.ts (3 hunks)
  • src/interfaces/Provider.ts (4 hunks)
  • src/prompts.ts (10 hunks)
  • src/providers/ollama.ts (1 hunks)
  • src/providers/openai.ts (4 hunks)
  • src/types.ts (2 hunks)
  • src/utils.ts (2 hunks)
Files skipped from review due to trivial changes (2)
  • docs/Library/AICore/Space Script/AI Query LLM.md
  • docs/Library/AICore/Space Script/AI Search Embeddings.md
Additional context used
Path-based instructions (12)
docs/Library/AICore/Space Script/Remove Duplicate Start.md (1)

Pattern **/*.md: Review these markdown files. They are written for a markdown note taking tool called Silverbullet, and may contain extra syntax not typically found in markdown.

Ensure any documentation makes sense and is good.

docs/Library/AICore/Space Script/Convert to task list.md (1)

Pattern **/*.md: Review these markdown files. They are written for a markdown note taking tool called Silverbullet, and may contain extra syntax not typically found in markdown.

Ensure any documentation makes sense and is good.

docs/Library/AICore/Space Script/Convert to bullets.md (1)

Pattern **/*.md: Review these markdown files. They are written for a markdown note taking tool called Silverbullet, and may contain extra syntax not typically found in markdown.

Ensure any documentation makes sense and is good.

docs/Library/AICore/Space Script/Indent lines.md (1)

Pattern **/*.md: Review these markdown files. They are written for a markdown note taking tool called Silverbullet, and may contain extra syntax not typically found in markdown.

Ensure any documentation makes sense and is good.

docs/Library/AICore/AIPrompt/AI Split Task.md (1)

Pattern **/*.md: Review these markdown files. They are written for a markdown note taking tool called Silverbullet, and may contain extra syntax not typically found in markdown.

Ensure any documentation makes sense and is good.

src/editorUtils.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

src/providers/ollama.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

src/types.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

src/interfaces/Provider.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

src/providers/openai.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

src/prompts.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

src/utils.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

Additional comments not posted (11)
docs/Library/AICore/Space Script/Convert to task list.md (1)

11-28: Approve the changes.

The function convertToTaskList is well-implemented, using regular expressions effectively to convert strings into markdown task list items. The logic is clear and the code is clean.

docs/Library/AICore/Space Script/Convert to bullets.md (1)

11-34: Approve the changes.

The function convertToBulletList is well-implemented, using the indentation of the previous line effectively to maintain formatting consistency when converting strings into bullet list items. The logic is clear and the code is clean.

src/editorUtils.ts (4)

3-3: Well-implemented function for retrieving selected text.

The getSelectedText function is correctly implemented, handling cases where no text is selected and providing a consistent return structure. This function enhances the editor's functionality by allowing other parts of the application to access selected text.


39-39: Simple and effective function for retrieving page length.

The getPageLength function is straightforward and effectively retrieves the length of the text in the current page. This function is essential for features that need to know the size of the content within the editor.


56-62: Well-implemented function for retrieving specific lines of text.

The getLine function is correctly implemented, handling cases where the line number is out of range by returning an empty string. This function is essential for features that need to access specific lines of text within the editor.


64-67: Effective function for retrieving lines based on position.

The getLineOfPos function effectively combines getLineNumberAtPos and getLine to retrieve the line of text at a specific position. This function provides a useful abstraction for features that need to access text based on its position within the editor.

src/types.ts (1)

154-159: Approve the definition of PostProcessorData.

The new type PostProcessorData is well-defined and appropriately structured for its intended use in handling post-processing data. The properties included are relevant and useful for the described functionality.

src/providers/openai.ts (1)

42-49: Proper integration of onResponseComplete in chatWithAI.

The update to include onResponseComplete in the function signature and its subsequent handling within the method are correctly implemented. The logic separation between streaming and non-streaming chats is maintained, ensuring that existing functionalities are not disrupted.

src/prompts.ts (2)

Line range hint 6-22: Approved: New imports for enhanced functionality.

The addition of system and PostProcessorData supports the new features introduced in this PR, enhancing system interactions and type safety for postprocessors.


Line range hint 79-313: Review: Enhanced insertAt handling and postProcessors integration.

The expanded functionality for insertAt options and the addition of postProcessors significantly enhance the flexibility and capabilities of the insertAiPromptFromTemplate function. However, ensure that:

  • The insertAt options are thoroughly tested, especially for edge cases.
  • The postProcessors are securely integrated and do not introduce performance bottlenecks.

Consider adding more detailed error handling and logging for the postProcessors execution to aid in debugging and maintenance.

src/utils.ts (1)

Line range hint 178-248: Review: Integration of globalMetadata in enrichChatMessages.

The addition of globalMetadata enhances the function's capability to handle dynamic data. Ensure that:

  • globalMetadata is properly validated and sanitized to prevent security vulnerabilities.
  • The function handles cases where globalMetadata is undefined to avoid runtime errors.

Consider adding default values or checks for required metadata properties to improve robustness and error handling.

Comment on lines +10 to +35
```space-script
silverbullet.registerFunction({ name: "indentOneLevel" }, async (data) => {
const { response, lineBefore, lineCurrent } = data;
console.log(data);

// Function to determine the indentation of a line
const getIndentation = (line) => line.match(/^\s*/)[0];

// Determine the maximum indentation of lineBefore and lineCurrent
const maxIndentation = getIndentation(lineBefore).length > getIndentation(lineCurrent).length
? getIndentation(lineBefore)
: getIndentation(lineCurrent);

// Define additional indentation level
const additionalIndentation = ' ';

// Compute new indentation
const newIndentation = maxIndentation + additionalIndentation;

// Apply new indentation to all lines in the response
const indentedLines = response.split('\n').map(line => `${newIndentation}${line.trim()}`).join('\n');

console.log("indentedLines:", indentedLines);

return indentedLines;
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Well-implemented function with clear documentation.

The indentOneLevel function is well-documented and logically structured. It effectively uses regular expressions and string manipulation to indent lines based on the maximum indentation of two reference lines.

Suggestion for Improvement:
Consider adding error handling for potential edge cases, such as null or undefined inputs, to enhance robustness.

docs/Library/AICore/AIPrompt/AI Split Task.md Show resolved Hide resolved
@@ -17,7 +17,7 @@ async function getSelectedText() {
};
}

async function getSelectedTextOrNote() {
export async function getSelectedTextOrNote() {
Copy link
Contributor

Choose a reason for hiding this comment

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

Logical extension of text selection functionality.

The getSelectedTextOrNote function effectively extends the getSelectedText function by adding the capability to determine if the entire note is selected. This is useful for features that need to differentiate between partial and full note selections.

Suggestion for Improvement:
Consider simplifying the condition for isWholeNote to enhance readability and maintainability.

Comment on lines +44 to +54
export function getLineNumberAtPos(text: string, pos: number): number {
const lines = text.split("\n");
let currentPos = 0;
for (let i = 0; i < lines.length; i++) {
if (currentPos <= pos && pos < currentPos + lines[i].length + 1) {
return i;
}
currentPos += lines[i].length + 1; // +1 for the newline character
}
return -1;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Efficient function for calculating line numbers.

The getLineNumberAtPos function is well-implemented and efficiently calculates the line number corresponding to a given position in the text. This function is crucial for features that need to manipulate text based on line numbers.

Suggestion for Improvement:
Consider optimizing the loop to reduce the number of iterations for large texts, potentially using a binary search approach if the lines are of relatively uniform length.

Comment on lines +69 to +77
export function getLineBefore(text: string, pos: number): string {
const lineNumber = getLineNumberAtPos(text, pos);
return getLine(text, lineNumber - 1);
}

export function getLineAfter(text: string, pos: number): string {
const lineNumber = getLineNumberAtPos(text, pos);
return getLine(text, lineNumber + 1);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Useful functions for navigating text based on position.

The getLineBefore and getLineAfter functions effectively leverage getLineNumberAtPos and getLine to retrieve the lines before and after a specific position. These functions are crucial for features that need to navigate text based on its position within the editor.

Suggestion for Improvement:
Consider adding error handling for cases where the position is at the start or end of the text to prevent potential out-of-range errors.

Comment on lines +34 to +40
{ messages, stream, onDataReceived, onResponseComplete }: StreamChatOptions,
): Promise<any> {
return await this.openaiProvider.chatWithAI({
messages,
stream,
onDataReceived,
onResponseComplete,
Copy link
Contributor

Choose a reason for hiding this comment

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

Approve the addition of onResponseComplete, suggest specifying return type.

The integration of onResponseComplete in the chatWithAI method is correctly implemented, enhancing the method's functionality by allowing additional callback handling.

However, consider specifying a more detailed return type than Promise<any> to improve type safety and clarity.

Comment on lines +11 to +12
onResponseComplete?: (data: any) => void;
postProcessors?: string[];
Copy link
Contributor

Choose a reason for hiding this comment

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

Approve additions, suggest more specific type for onResponseComplete.

The additions of onResponseComplete and postProcessors to StreamChatOptions are well-aligned with the PR objectives and enhance the functionality significantly.

However, consider using a more specific type than any for the onResponseComplete parameter to improve type safety and clarity.

@justyns justyns merged commit 47a1e42 into main Sep 9, 2024
2 checks passed
@justyns justyns deleted the template-options branch September 9, 2024 07:06
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.

1 participant