chatgpt.nvim

repository·main·Indexed 26 days ago

https://github.com/jackmort/chatgpt.nvim

A Neovim plugin that integrates the OpenAI ChatGPT API for interactive Q&A, persona-based conversations, code editing assistance, and code completion. It supports custom OpenAI hosts, Azure OpenAI deployments, and secure API key management via executable commands. Features include built-in actions like grammar correction and code optimization, the ability to define custom JSON-based actions, and a comprehensive Lua API for mapping functions.

Tokens
2.9K
Snippets
8
Records
11
Agent score
38%

What's inside chatgpt.nvim

  1. Install ChatGPT.nvim

    main

    To install ChatGPT.nvim, ensure you have curl installed and an OpenAI API key. You can manage your API key via the api_key_cmd configuration option or the $OPENAI_API_KEY environment variable.

    Dependencies

    • MunifTanjim/nui.nvim
    • nvim-lua/plenary.nvim
    • nvim-telescope/telescope.nvim
    • folke/trouble.nvim (optional)
    -- Lazy.nvim
    {
      "jackMort/ChatGPT.nvim",
        event = "VeryLazy",
        config = function()
          require("chatgpt").setup()
        end,
        dependencies = {
          "MunifTanjim/nui.nvim",
          "nvim-lua/plenary.nvim",
          "folke/trouble.nvim", -- optional
          "nvim-telescope/telescope.nvim"
        }
    }
  2. Securely manage API keys with api_key_cmd

    main

    To avoid storing API keys in plain text or environment variables, use the api_key_cmd option. This option executes a command at startup and uses its stdout as the API key.

    Note: Arguments are split by whitespace. If your command requires arguments with spaces, wrap the command in a separate script.

    -- Using 1Password CLI
    require("chatgpt").setup({
        api_key_cmd = "op read op://private/OpenAI/credential --no-newline"
    })
    
    -- Using GPG to decrypt a file
    local home = vim.fn.expand("$HOME")
    require("chatgpt").setup({
        api_key_cmd = "gpg --decrypt " .. home .. "/secret.txt.gpg"
    })
  3. Configure Azure OpenAI deployments

    main

    For Azure deployments, you must specify the URL base, engine, and API type. This can be done via configuration options (using executable commands) or environment variables.

    Using Configuration Options

    Use the following keys in your setup() call. Each must be an executable command that returns the corresponding value:

    • api_type_cmd (e.g., echo azure)
    • azure_api_base_cmd (e.g., echo https://{resource}.openai.azure.com)
    • azure_api_engine_cmd (e.g., echo chat)
    • azure_api_version_cmd (e.g., echo 2023-05-15)

    Using Environment Variables

    • $OPENAI_API_TYPE
    • $OPENAI_API_BASE
    • $OPENAI_API_AZURE_ENGINE
    • $OPENAI_API_AZURE_VERSION
    local config = {
      api_host_cmd = 'echo -n ""',
      api_key_cmd = 'pass azure-openai-key',
      api_type_cmd = 'echo azure',
      azure_api_base_cmd = 'echo https://{your-resource-name}.openai.azure.com',
      azure_api_engine_cmd = 'echo chat',
      azure_api_version_cmd = 'echo 2023-05-15'
    }
    
    require("chatgpt").setup(config)
  4. Configure OpenAI API credentials and host

    main

    You can configure the OpenAI API key and host using either configuration options (which accept executable commands that return the value via stdout) or environment variables.

    Environment Variables

    • $OPENAI_API_KEY
    • $OPENAI_API_HOST (for custom hosts)

    Configuration Options

    • api_key_cmd: Path and arguments to an executable that returns the API key via stdout.
    • api_host_cmd: Path and arguments to an executable that returns the API host via stdout.
    • extra_curl_params: A table of custom cURL parameters (e.g., additional headers).
    {
      ...,
      extra_curl_params = {
        "-H",
        "Origin: https://example.com"
      }
    }
  5. Configure OpenAI model parameters

    main

    Pass an openai_params table to setup() to customize the model behavior. The model key can be a string or a function that returns a string (useful for dynamic model switching).

    Available keys in openai_params:

    • model: The name of the model (e.g., "gpt-4").
    • frequency_penalty: Float.
    • presence_penalty: Float.
    • max_tokens: Integer.
    • temperature: Float.
    • top_p: Float.
    • n: Integer.
    require("chatgpt").setup({
      openai_params = {
        model = "gpt-5-mini",
        frequency_penalty = 0,
        presence_penalty = 0,
        max_tokens = 4095,
        temperature = 0.2,
        top_p = 0.1,
        n = 1,
      }
    })
  6. Run specific ChatGPT actions with ChatGPTRun

    main

    The :ChatGPTRun [action] command executes predefined tasks using the gpt-5-mini model.

    Available built-in actions:

    1. grammar_correction
    2. translate
    3. keywords
    4. docstring
    5. add_tests
    6. optimize_code
    7. summarize
    8. fix_bugs
    9. explain_code
    10. roxygen_edit
    11. code_readability_analysis
    12. fix_diagnostic (fix error under cursor)
    13. explain_diagnostic (explain error under cursor)
    14. fix_diagnostics (fix all errors in selection)
  7. Map ChatGPT functions via Lua API

    main

    You can call ChatGPT functions directly using the Lua API. For example, to map the edit_with_instructions function using which-key.nvim in visual mode:

    local chatgpt = require("chatgpt")
    wk.register({
        p = {
            name = "ChatGPT",
            e = {
                function()
                    chatgpt.edit_with_instructions()
                end,
                "Edit with instructions",
            },
        },
    }, {
        prefix = "<leader>",
        mode = "v",
    })
  8. Configure WhichKey mappings for ChatGPT

    main

    To integrate ChatGPT commands into which-key.nvim, use the following configuration structure to map common actions like grammar correction, translation, and code optimization:

    c = {
      name = "ChatGPT",
        c = { "<cmd>ChatGPT<CR>", "ChatGPT" },
        e = { "<cmd>ChatGPTEditWithInstruction<CR>", "Edit with instruction", mode = { "n", "v" } },
        g = { "<cmd>ChatGPTRun grammar_correction<CR>", "Grammar Correction", mode = { "n", "v" } },
        t = { "<cmd>ChatGPTRun translate<CR>", "Translate", mode = { "n", "v" } },
        k = { "<cmd>ChatGPTRun keywords<CR>", "Keywords", mode = { "n", "v" } },
        d = { "<cmd>ChatGPTRun docstring<CR>", "Docstring", mode = { "n", "v" } },
        a = { "<cmd>ChatGPTRun add_tests<CR>", "Add Tests", mode = { "n", "v" } },
        o = { "<cmd>ChatGPTRun optimize_code<CR>", "Optimize Code", mode = { "n", "v" } },
        s = { "<cmd>ChatGPTRun summarize<CR>", "Summarize", mode = { "n", "v" } },
        f = { "<cmd>ChatGPTRun fix_bugs<CR>", "Fix Bugs", mode = { "n", "v" } },
        x = { "<cmd>ChatGPTRun explain_code<CR>", "Explain Code", mode = { "n", "v" } },
        r = { "<cmd>ChatGPTRun roxygen_edit<CR>", "Roxygen Edit", mode = { "n", "v" } },
        l = { "<cmd>ChatGPTRun code_readability_analysis<CR>", "Code Readability Analysis", mode = { "n", "v" } },
      },
  9. Define custom ChatGPT actions

    main

    You can define custom actions using a JSON file. The path to this file can be configured via the actions_paths field.

    An action requires a type (chat, completion, or edit), a strategy (replace, display, append, or edit), and optional args.

    Template Variables:

    • {{input}}: The selected text
    • {{filetype}}: Neovim filetype
    • {{filepath}}: Relative path to the file
    • {{argument}}: Provided on the command line
    • {{diagnostic}}: LSP diagnostic under cursor ([SEVERITY] message (line N))
    • {{diagnostics}}: All LSP diagnostics in selection (Line N [SEVERITY]: message)

    Strategies:

    • edit: (Chat type only) Shows output side-by-side with input for further editing.
    • display: Shows output in a float window.
    • append: Modifies the text directly in the buffer by adding to it.
    • replace: Modifies the text directly in the buffer by replacing it.
    {
      "action_name": {
        "type": "chat",
        "opts": {
          "template": "A template using possible variables",
          "strategy": "replace",
          "params": {
            "model": "gpt-5-mini",
            "stop": [
              "```"
            ]
          }
        },
        "args": {
          "argument": {
              "type": "strig",
              "optional": "true",
              "default": "some value"
          }
        }
      }
    }
  10. Interactive popup keybindings

    main

    When using :ChatGPT or :ChatGPTEditWithInstructions, use the following keybindings within the interactive window:

    Submitting and Closing:

    • <C-Enter> / <Enter>: Submit prompt
    • q: Close chat window
    • <C-c>: Stop generating response

    Navigation:

    • ]m / [m: Next/previous message
    • ]c / [c: Next/previous code block
    • <C-u> / <C-d>: Scroll up/down
    • <Tab>: Cycle between windows

    Toggles (g prefix):

    • gs: Toggle settings panel (read-only)
    • gh: Toggle help panel
    • gp: Toggle sessions panel
    • gr: Toggle system role window
    • gm: Toggle message role (user/assistant)
    • gl: Cycle layout modes (center/right)
    • gn: Start new session
    • gd: Draft message (add without sending)

    Actions:

    • y: Copy code block at cursor
    • Y: Copy entire last answer
    • d: Delete selected message
    • e: Edit selected message
    • r: Rename session (in sessions panel)
    • za: Toggle fold for code block
    • @: Trigger context autocomplete (LSP, project, file, git diff)

    Edit Window specific:

    • <C-y>: Accept changes
    • <C-d>: Toggle diff view
    • <C-i>: Use response as input
  11. Use ChatGPT commands

    main

    The plugin provides several primary commands for interacting with ChatGPT:

    • :ChatGPT: Opens an interactive window using the gpt-5-mini model.
    • :ChatGPTActAs: Opens a prompt selection from Awesome ChatGPT Prompts to use with the gpt-5-mini model.
    • :ChatGPTEditWithInstructions: Opens an interactive window to edit selected text or the whole window using the gpt-5-mini model (configurable).