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

Enhance AI-driven development scripts and update documentation #7

Merged
merged 16 commits into from
Jul 16, 2024

Conversation

alexsoyes
Copy link
Collaborator

@alexsoyes alexsoyes commented Jul 3, 2024

User description

Fix and Feature Updates for AI-Driven Development

✅ Type of PR

  • Feature
  • Bug Fix

🗒️ Description

This PR introduces a series of bug fixes and feature enhancements aimed at improving the AI-driven development experience. Key changes include improved error handling, new utility scripts, and updates to documentation for better clarity.

🚶‍➡️ Behavior

  • Bug Fixes: Resolves issues with empty output in aiddc and enhances error messaging in commit message scripts.
  • Features: Adds new scripts for listing untracked files and comparing commit differences between the current branch and main.
  • Optimizations: Cleans up commented code and adjusts the AI temperature setting for more dynamic responses.

🧪 Steps to test

  • Verify that the empty output issue in aiddc is fixed.
  • Test the new function for listing untracked files.
  • Use the updated commit message rules and verify improved error handling.
  • Check the new alias aiddc-commits-diff-main for functionality.
  • Review updated documentation for clarity and formatting.

PR Type

Enhancement, Bug fix, Documentation


Description

  • Added a new alias aiddc-commits-diff-main for commit differences between the current branch and main.
  • Enhanced aidd-commit-msg.sh script with better error handling and a function to list untracked files.
  • Introduced a new script aidd-commits-diff-main.sh to get commit differences between the current branch and main.
  • Cleaned up commented code and adjusted GEN_AI_TEMPERATURE setting in main.js.
  • Updated PR creation and code review prompts for better clarity and formatting.

Changes walkthrough 📝

Relevant files
Enhancement
aliases.sh
Add alias for commit differences between branches               

scripts/aiddc/aliases.sh

  • Added new alias aiddc-commits-diff-main.
+1/-0     
aidd-commit-msg.sh
Enhance commit message script with better error handling 

scripts/aiddc/scripts/aidd-commit-msg.sh

  • Improved error handling for unstaged changes.
  • Added a function to list untracked files.
  • Updated commit message generation rules.
  • +33/-3   
    aidd-commits-diff-main.sh
    Add script for commit differences between branches             

    scripts/aiddc/scripts/aidd-commits-diff-main.sh

  • Added a new script to get commit differences between the current
    branch and main.
  • +24/-0   
    main.js
    Clean up code and adjust AI temperature setting                   

    scripts/aiddc/main.js

  • Cleaned up commented code.
  • Adjusted GEN_AI_TEMPERATURE setting.
  • Updated system message for clarity.
  • +5/-8     
    Documentation
    package.yml
    Update PR creation prompt for clarity                                       

    ai-driven-dev-prompts/package.yml

    • Updated PR creation prompt for clarity and formatting.
    +13/-4   
    code-review.md
    Update code review prompt for clarity                                       

    resources/prompts/code-review.md

    • Updated code review prompt for clarity and formatting.
    +13/-4   

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    Summary by CodeRabbit

    • New Features

      • Introduced support for Ollama with setup instructions for environment variables.
      • Added aidd-commits-diff-main.sh script to retrieve commits difference between branches.
      • New alias aiddc-commits-diff-main for easier command usage.
      • Enhanced aidd-commit-msg.sh with new function to list created files.
    • Improvements

      • Refined pull request creation instructions and template handling.
      • Updated .env.example with specific local model identifiers and debugging settings.
      • Adjusted console output colors and Gen-AI parameters in main.js.
      • Improved aidd-pull-request.sh script to validate template file paths.
    • Bug Fixes

      • Removed unused imports in main.js.
    • Documentation

      • Updated README.md with Ollama support instructions.
    • Version Update

      • Incremented project version to 0.3.87.

    Copy link
    Contributor

    coderabbitai bot commented Jul 3, 2024

    Walkthrough

    This update to the ai-driven-dev-community project includes version increments, enhanced settings for pull requests and API configurations, addition of new functionalities like handling staged git changes and commits difference, and an updated readme to support new environments. The changes aim to streamline development processes, enrich configuration options, and optimize automation in various scripts.

    Changes

    File/Path Change Summary
    ai-driven-dev-prompts/_manifest.yml Incremented version from 0.3.86 to 0.3.87.
    ai-driven-dev-prompts/package.yml Revamped the form section under the trigger: ':reviewCreatePullRequest', including new rules and directives.
    package.json Updated version number and minor description change.
    resources/prompts/code-review.md Refined instructions for AI-generated pull requests, emphasizing formatting and process.
    scripts/aiddc/.env.example Updated API key configurations, added local model settings, and new debugging settings.
    scripts/aiddc/aliases.sh Added new alias aiddc-commits-diff-main.
    scripts/aiddc/main.js Removed unused imports, adjusted console outputs, updated constants, and added callOllamaApi function.
    scripts/aiddc/scripts/aidd-commit-msg.sh Updated handling of staged git changes and added created_files_prompt() function.
    scripts/aiddc/scripts/aidd-commits-diff-main.sh New script to retrieve commit differences between the current branch and main branch using Git.
    scripts/aiddc/scripts/aidd-pull-request.sh Allows specifying and validating a template file path as an argument.
    scripts/aiddc/README.md Added support instructions for Ollama environment variables.

    Poem

    In the land where code does play,
    New tools arise to ease the day,
    Version bumps and scripts refined,
    Helping devs not fall behind.
    Pull requests now clearer be,
    A smoother path for you and me.
    🌟✨


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

    Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

    @github-actions github-actions bot changed the title Feature/aiddc scripts documentation Enhance AI-driven development scripts and update documentation Jul 3, 2024
    Copy link

    github-actions bot commented Jul 3, 2024

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Key issues to review

    Possible Bug:
    The created_files_prompt function returns a string "No created files." instead of printing it, which might not be the intended behavior.

    Documentation:
    Ensure that the updated documentation is clear and accurately reflects the new features and changes.

    Copy link

    github-actions bot commented Jul 3, 2024

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Possible issue
    Ensure the created_files_prompt function returns an appropriate exit status

    The created_files_prompt function should use return 0 instead of return "No created
    files." to avoid potential issues, as return in shell functions should return an exit
    status (0 for success).

    scripts/aiddc/scripts/aidd-commit-msg.sh [32]

    -return "No created files."
    +return 0
     
    Suggestion importance[1-10]: 10

    Why: The suggestion correctly identifies a potential issue with the use of return in shell functions. Returning an appropriate exit status (0 for success) is crucial for proper function behavior.

    10
    Wrap $file in double quotes to handle filenames with special characters

    To avoid potential issues with special characters in filenames, wrap $file in double
    quotes in the for loop within the created_files_prompt function.

    scripts/aiddc/scripts/aidd-commit-msg.sh [37]

    -for file in $UNTRACKED; do
    +for file in "$UNTRACKED"; do
     
    Suggestion importance[1-10]: 10

    Why: Wrapping $file in double quotes is a best practice to handle filenames with spaces or special characters, ensuring the script works correctly in all scenarios.

    10
    Set GEN_AI_TEMPERATURE to 0.7 to maintain consistency with the previous configuration

    The GEN_AI_TEMPERATURE value should be set to 0.7 instead of 1 to maintain consistency
    with the previous configuration and avoid potential issues with response variability.

    scripts/aiddc/main.js [65]

    -const GEN_AI_TEMPERATURE = 1;
    +const GEN_AI_TEMPERATURE = 0.7;
     
    Suggestion importance[1-10]: 8

    Why: Maintaining the GEN_AI_TEMPERATURE at 0.7 ensures consistency with the previous configuration and avoids potential issues with response variability. This is a good suggestion for maintaining expected behavior.

    8
    Best practice
    Calculate the diff against the remote main branch to ensure accuracy

    Use git log --oneline --no-merges origin/main..HEAD instead of git log --oneline
    --no-merges main..HEAD to ensure the diff is calculated against the remote main branch.

    scripts/aiddc/scripts/aidd-commits-diff-main.sh [15]

    -DIFF=$(git log --oneline --no-merges main..HEAD)
    +DIFF=$(git log --oneline --no-merges origin/main..HEAD)
     
    Suggestion importance[1-10]: 9

    Why: Using origin/main ensures that the diff is calculated against the latest remote main branch, which is a best practice for accuracy. This is a significant improvement.

    9

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

    Outside diff range and nitpick comments (3)
    ai-driven-dev-prompts/package.yml (3)

    116-116: Add a brief description for the goal.

    Consider adding a brief description for the goal to provide more context.

    - Goal:
    + Goal: Create a pull request for my changes.

    120-124: Ensure proper indentation and alignment for readability.

    The instructions should be properly indented and aligned to enhance readability.

    - - Use the changes from main.
    - - Fill the "template" file to create the PR (the "output").
    - - "Instructions" comments must be followed no matter what.
    - - "Instructions" comments must be remove from the output.
    - - Output should be properly formatted in markdown.
    + - Use the changes from main.
    + - Fill the "template" file to create the PR (the "output").
    + - "Instructions" comments must be followed no matter what.
    + - "Instructions" comments must be removed from the output.
    + - Output should be properly formatted in markdown.

    126-126: Clarify the template directive.

    Clarify the purpose of the Template directive to avoid confusion.

    - Template: #file
    + Template: Path to the template file: #file
    Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits

    Files that changed from the base of the PR and between 2d4d19d and 3b2873c.

    Files selected for processing (6)
    • ai-driven-dev-prompts/package.yml (1 hunks)
    • resources/prompts/code-review.md (1 hunks)
    • scripts/aiddc/aliases.sh (1 hunks)
    • scripts/aiddc/main.js (4 hunks)
    • scripts/aiddc/scripts/aidd-commit-msg.sh (2 hunks)
    • scripts/aiddc/scripts/aidd-commits-diff-main.sh (1 hunks)
    Files skipped from review due to trivial changes (4)
    • resources/prompts/code-review.md
    • scripts/aiddc/aliases.sh
    • scripts/aiddc/main.js
    • scripts/aiddc/scripts/aidd-commits-diff-main.sh
    Additional context used
    Shellcheck
    scripts/aiddc/scripts/aidd-commit-msg.sh

    [warning] 29-29: In POSIX sh, 'local' is undefined.

    (SC3043)


    [warning] 29-29: Declare and assign separately to avoid masking return values.

    (SC2155)


    [warning] 29-29: Quote this to prevent word splitting.

    (SC2046)


    [error] 32-32: Can only return 0-255. Other data should be written to stdout.

    (SC2152)

    local UNTRACKED=$(git ls-files --others --exclude-standard)

    if [ -z "$UNTRACKED" ]; then
    return "No created files."
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Return values in shell functions must be numeric.

    The return statement can only return numeric values (0-255). Use echo to output the message instead.

    - return "No created files."
    + echo "No created files."
    + return 0
    Committable suggestion

    ‼️ IMPORTANT
    Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    Suggested change
    return "No created files."
    echo "No created files."
    return 0
    Tools
    Shellcheck

    [error] 32-32: Can only return 0-255. Other data should be written to stdout.

    (SC2152)

    Comment on lines +15 to +16
    CHANGES=$(git diff)
    CURRENT_DIR=$(pwd)
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Quote the variable to prevent word splitting.

    The CHANGES variable should be quoted to prevent word splitting and potential issues with filenames containing spaces.

    - CHANGES=$(git diff)
    + CHANGES="$(git diff)"
    Committable suggestion

    ‼️ IMPORTANT
    Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    Suggested change
    CHANGES=$(git diff)
    CURRENT_DIR=$(pwd)
    CHANGES="$(git diff)"
    CURRENT_DIR=$(pwd)

    # --------------------
    created_files_prompt() {

    local UNTRACKED=$(git ls-files --others --exclude-standard)
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Use local in POSIX sh, declare and assign separately, and quote the variable.

    In POSIX sh, local is undefined. Declare and assign separately to avoid masking return values, and quote the variable to prevent word splitting.

    - local UNTRACKED=$(git ls-files --others --exclude-standard)
    + UNTRACKED="$(git ls-files --others --exclude-standard)"

    Committable suggestion was skipped due to low confidence.

    Tools
    Shellcheck

    [warning] 29-29: In POSIX sh, 'local' is undefined.

    (SC3043)


    [warning] 29-29: Declare and assign separately to avoid masking return values.

    (SC2155)


    [warning] 29-29: Quote this to prevent word splitting.

    (SC2046)

    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 and nitpick comments (8)
    scripts/aiddc/scripts/aidd-pull-request.sh (4)

    12-18: Add a brief description of the argument.

    Including a description for the template file path argument will improve the script's usability.

    echo "Args:
    - 1: Template file path (default: $DEFAULT_PARAM)
    
    Example:
    $ aiddc-pull-request './my-projects/.github/pull_request_template.md'
    
    Description:
    - Template file path: Path to the pull request template file. Defaults to $DEFAULT_PARAM if not provided.
    "

    26-28: Use consistent logging for default template usage.

    It is good practice to log the usage of the default template consistently with other notices.

    - notice "[aiddc-pull-request]: Using default template"
    + notice "[aiddc-pull-request]: Using default template at $DEFAULT_PARAM"

    30-33: Consider suggesting the correct path.

    When the template file does not exist, suggesting the correct path can improve user experience.

    - error "Template file does not exist: $PARAM"
    + error "Template file does not exist: $PARAM. Please provide a valid path."

    Line range hint 50-66:
    Ensure proper formatting in the prompt.

    The prompt should be clear and well-formatted to avoid confusion during processing.

    Goal:
    Create a pull request for my changes.
    
    Rules:
    - Use the changes from main.
    - Fill the "template" file to create the PR (the "output").
    - "Instructions" comments must be followed no matter what.
    - "Instructions" comments must be removed from the output.
    - Output should be properly formatted in markdown.
    
    Changes from main (surrounded by """ delimiters):
    """
    $CHANGES
    """
    
    Template file (surrounded by """ delimiters):
    """
    $TEMPLATE
    """
    scripts/aiddc/scripts/aidd-commit-msg.sh (2)

    21-21: Improve the message for unstaged changes.

    Clarify the message to ensure users understand they need to unstage changes.

    - echo "Please UNSTAGE changes before generating a commit message."
    + echo "Please unstage changes before generating a commit message."

    Line range hint 50-64:
    Ensure proper formatting in the prompt.

    The prompt should be clear and well-formatted to avoid confusion during processing.

    Goal:
    1. Summarize functional changes in comments, with numbered list.
    2. Identify hunks (but do not display them).
    3. Generate git add + git commit message for every change in the code, following rules.
    
    Rules:
    - Should be formatted in Conventional Commit.
    - Remain consistent with the last commit messages if possible.
    - Focus on describing the changes made, not the implementation details.
    - Commits should be small and focused on a single change.
    - 1 commit message can have multiple file changes.
    - Answer with shell script ONLY.
    - Use relative git add path based on $CURRENT_DIR.
    - Use "git add --patch" with hunks when little changes are made.
      - When using patch option, be sure to "y" in EOF multiple if needed.
    - Do not use "git add --patch" on 1 line changes.
    scripts/aiddc/main.js (1)

    325-333: Log the selected API for clarity.

    Logging the selected API will help with debugging and understanding the script's behavior.

    - callableAPI = callOllamaApi;
    + callableAPI = callOllamaApi;
    + console.log('Using Ollama API');
    - callableAPI = callOpenAiApi;
    + callableAPI = callOpenAiApi;
    + console.log('Using OpenAI API');
    ai-driven-dev-prompts/package.yml (1)

    116-139: Ensure proper formatting in the form.

    The form should be clear and well-formatted to avoid confusion during processing.

    Goal:
    Create a pull request for my changes.
    
    Rules:
    - Use the changes from main.
    - Fill the "template" file to create the PR (the "output").
    - "Instructions" comments must be followed no matter what.
    - "Instructions" comments must be removed from the output.
    - Output should be properly formatted in markdown.
    
    Template (surrounded by `---`):
    ---
    [[copy_your_pr_template_here__use_githubpull_request_templatemd_if_needed]]
    ---
    
    Commits (surrounded by `---`):
    ---
    [[commits_list_from_main_here__use_aiddccommitsdiffmain]]
    ---
    
    Code changes (surrounded by `---`):
    ---
    [[copy_your_git_changes_from_main_here__use_aiddcchangesfrommain]]
    ---
    Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits

    Files that changed from the base of the PR and between 3b2873c and 7e5a408.

    Files ignored due to path filters (1)
    • package-lock.json is excluded by !**/package-lock.json
    Files selected for processing (9)
    • ai-driven-dev-prompts/_manifest.yml (1 hunks)
    • ai-driven-dev-prompts/package.yml (1 hunks)
    • package.json (1 hunks)
    • resources/prompts/code-review.md (1 hunks)
    • scripts/aiddc/.env.example (1 hunks)
    • scripts/aiddc/README.md (2 hunks)
    • scripts/aiddc/main.js (10 hunks)
    • scripts/aiddc/scripts/aidd-commit-msg.sh (2 hunks)
    • scripts/aiddc/scripts/aidd-pull-request.sh (1 hunks)
    Files skipped from review due to trivial changes (4)
    • ai-driven-dev-prompts/_manifest.yml
    • package.json
    • scripts/aiddc/.env.example
    • scripts/aiddc/README.md
    Files skipped from review as they are similar to previous changes (1)
    • resources/prompts/code-review.md
    Additional context used
    Shellcheck
    scripts/aiddc/scripts/aidd-commit-msg.sh

    [warning] 29-29: In POSIX sh, 'local' is undefined.

    (SC3043)


    [warning] 29-29: Declare and assign separately to avoid masking return values.

    (SC2155)


    [warning] 29-29: Quote this to prevent word splitting.

    (SC2046)

    GitHub Check: Codacy Static Code Analysis
    scripts/aiddc/main.js

    [warning] 133-133: scripts/aiddc/main.js#L133
    This application accepts user input directly from the client side without validation.

    Additional comments not posted (5)
    scripts/aiddc/scripts/aidd-pull-request.sh (1)

    22-24: Quote the variable to prevent word splitting.

    The DEFAULT_PARAM variable should be quoted to prevent word splitting and potential issues with spaces in file paths.

    - DEFAULT_PARAM=$(dirname "$0")/../templates/pull_request_template.md
    + DEFAULT_PARAM="$(dirname "$0")/../templates/pull_request_template.md"

    Likely invalid or redundant comment.

    scripts/aiddc/scripts/aidd-commit-msg.sh (3)

    15-16: Quote the variable to prevent word splitting.

    The CHANGES variable should be quoted to prevent word splitting and potential issues with filenames containing spaces.

    - CHANGES=$(git diff)
    + CHANGES="$(git diff)"

    27-44: Return values in shell functions must be numeric.

    The return statement can only return numeric values (0-255). Use echo to output the message instead.

    - return "No created files."
    + echo "No created files."
    + return 0
    Tools
    Shellcheck

    [warning] 29-29: In POSIX sh, 'local' is undefined.

    (SC3043)


    [warning] 29-29: Declare and assign separately to avoid masking return values.

    (SC2155)


    [warning] 29-29: Quote this to prevent word splitting.

    (SC2046)


    29-29: Use local in POSIX sh, declare and assign separately, and quote the variable.

    In POSIX sh, local is undefined. Declare and assign separately to avoid masking return values and quote the variable to prevent word splitting.

    - local UNTRACKED=$(git ls-files --others --exclude-standard)
    + UNTRACKED="$(git ls-files --others --exclude-standard)"
    Tools
    Shellcheck

    [warning] 29-29: In POSIX sh, 'local' is undefined.

    (SC3043)


    [warning] 29-29: Declare and assign separately to avoid masking return values.

    (SC2155)


    [warning] 29-29: Quote this to prevent word splitting.

    (SC2046)

    scripts/aiddc/main.js (1)

    57-66: Ensure the updated temperature value is intentional.

    The GEN_AI_TEMPERATURE value has been changed from 0.7 to 1. Verify that this change is intentional, as it can significantly affect the AI's response variability.

    Comment on lines +37 to 38
    TEMPLATE=$PARAM
    CHANGES=$(git diff main)
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Quote the variable to prevent word splitting.

    The CHANGES variable should be quoted to prevent word splitting and potential issues with filenames containing spaces.

    - CHANGES=$(git diff main)
    + CHANGES="$(git diff main)"
    Committable suggestion

    ‼️ IMPORTANT
    Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    Suggested change
    TEMPLATE=$PARAM
    CHANGES=$(git diff main)
    TEMPLATE=$PARAM
    CHANGES="$(git diff main)"

    Comment on lines +69 to +136
    /**
    * Calls the Ollama API with a specified prompt and model.
    *
    * This function sends a POST request to the Ollama API endpoint, submitting a JSON payload
    * that includes the model and input data. It logs the API response to the console.
    *
    * @param {string} prompt - The input data to be processed by the Ollama API.
    * @param {string} [model=GEN_AI_MODEL] - The model to use for processing the input. Defaults to GEN_AI_MODEL.
    */
    function callOllamaApi(prompt, model=GEN_AI_MODEL) {

    const cleanPrompt = prompt.replace(/[^\x20-\x7E\t]/g, '');

    const data = JSON.stringify({
    model,
    prompt: cleanPrompt,
    system: GEN_AI_SYSTEM_MESSAGE,
    stream: false,
    options: {
    temperature: GEN_AI_TEMPERATURE,
    },
    keep_alive: '0',
    });

    const options = {
    hostname: '127.0.0.1',
    port: 11434,
    path: '/api/generate',
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
    }
    };

    return new Promise((resolve, reject) => {
    const req = http.request(options, (res) => {
    let responseBody = '';

    res.on('data', (chunk) => {
    responseBody += chunk;
    });

    res.on('end', () => {
    const parsedResponse = JSON.parse(responseBody);

    if (parsedResponse.error) {
    return reject(new Error(parsedResponse.error));
    }

    console.log(parsedResponse)
    console.log(`\n🚚 Usage:`);
    console.warn(`--------------------\n`);
    console.warn(`Loading time: ${(parsedResponse.total_duration / 1000000000).toFixed(2)} seconds.`);
    console.warn(`Number of tokens in prompt: ${parsedResponse.prompt_eval_count}.`);
    console.warn(`--------------------\n`);
    resolve(parsedResponse.response);
    });
    })

    req.on('error', (error) => {
    console.error('Error:', error);
    });

    req.write(data);
    req.end();
    });
    }
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    Ensure proper error handling for API calls.

    The callOllamaApi function should include error handling for potential issues during the API call.

    - const parsedResponse = JSON.parse(responseBody);
    + let parsedResponse;
    + try {
    +     parsedResponse = JSON.parse(responseBody);
    + } catch (error) {
    +     return reject(new Error('Failed to parse API response'));
    + }
    Committable suggestion

    ‼️ IMPORTANT
    Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    Suggested change
    /**
    * Calls the Ollama API with a specified prompt and model.
    *
    * This function sends a POST request to the Ollama API endpoint, submitting a JSON payload
    * that includes the model and input data. It logs the API response to the console.
    *
    * @param {string} prompt - The input data to be processed by the Ollama API.
    * @param {string} [model=GEN_AI_MODEL] - The model to use for processing the input. Defaults to GEN_AI_MODEL.
    */
    function callOllamaApi(prompt, model=GEN_AI_MODEL) {
    const cleanPrompt = prompt.replace(/[^\x20-\x7E\t]/g, '');
    const data = JSON.stringify({
    model,
    prompt: cleanPrompt,
    system: GEN_AI_SYSTEM_MESSAGE,
    stream: false,
    options: {
    temperature: GEN_AI_TEMPERATURE,
    },
    keep_alive: '0',
    });
    const options = {
    hostname: '127.0.0.1',
    port: 11434,
    path: '/api/generate',
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
    }
    };
    return new Promise((resolve, reject) => {
    const req = http.request(options, (res) => {
    let responseBody = '';
    res.on('data', (chunk) => {
    responseBody += chunk;
    });
    res.on('end', () => {
    const parsedResponse = JSON.parse(responseBody);
    if (parsedResponse.error) {
    return reject(new Error(parsedResponse.error));
    }
    console.log(parsedResponse)
    console.log(`\n🚚 Usage:`);
    console.warn(`--------------------\n`);
    console.warn(`Loading time: ${(parsedResponse.total_duration / 1000000000).toFixed(2)} seconds.`);
    console.warn(`Number of tokens in prompt: ${parsedResponse.prompt_eval_count}.`);
    console.warn(`--------------------\n`);
    resolve(parsedResponse.response);
    });
    })
    req.on('error', (error) => {
    console.error('Error:', error);
    });
    req.write(data);
    req.end();
    });
    }
    /**
    * Calls the Ollama API with a specified prompt and model.
    *
    * This function sends a POST request to the Ollama API endpoint, submitting a JSON payload
    * that includes the model and input data. It logs the API response to the console.
    *
    * @param {string} prompt - The input data to be processed by the Ollama API.
    * @param {string} [model=GEN_AI_MODEL] - The model to use for processing the input. Defaults to GEN_AI_MODEL.
    */
    function callOllamaApi(prompt, model=GEN_AI_MODEL) {
    const cleanPrompt = prompt.replace(/[^\x20-\x7E\t]/g, '');
    const data = JSON.stringify({
    model,
    prompt: cleanPrompt,
    system: GEN_AI_SYSTEM_MESSAGE,
    stream: false,
    options: {
    temperature: GEN_AI_TEMPERATURE,
    },
    keep_alive: '0',
    });
    const options = {
    hostname: '127.0.0.1',
    port: 11434,
    path: '/api/generate',
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
    }
    };
    return new Promise((resolve, reject) => {
    const req = http.request(options, (res) => {
    let responseBody = '';
    res.on('data', (chunk) => {
    responseBody += chunk;
    });
    res.on('end', () => {
    let parsedResponse;
    try {
    parsedResponse = JSON.parse(responseBody);
    } catch (error) {
    return reject(new Error('Failed to parse API response'));
    }
    if (parsedResponse.error) {
    return reject(new Error(parsedResponse.error));
    }
    console.log(parsedResponse)
    console.log(`\n🚚 Usage:`);
    console.warn(`--------------------\n`);
    console.warn(`Loading time: ${(parsedResponse.total_duration / 1000000000).toFixed(2)} seconds.`);
    console.warn(`Number of tokens in prompt: ${parsedResponse.prompt_eval_count}.`);
    console.warn(`--------------------\n`);
    resolve(parsedResponse.response);
    });
    })
    req.on('error', (error) => {
    console.error('Error:', error);
    });
    req.write(data);
    req.end();
    });
    }
    Tools
    GitHub Check: Codacy Static Code Analysis

    [warning] 133-133: scripts/aiddc/main.js#L133
    This application accepts user input directly from the client side without validation.

    @alexsoyes alexsoyes merged commit b22930a into main Jul 16, 2024
    1 check failed
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    1 participant