oliversen / chatgpt-docstrings

VSCode extension to automatically generate docstrings using ChatGPT
https://marketplace.visualstudio.com/items?itemName=oliversen.chatgpt-docstrings
MIT License
3 stars 2 forks source link

Need to input API key at each query, despite setting API key using command #1

Open quadrismegistus opened 1 year ago

quadrismegistus commented 1 year ago

Just a quick issue to document. Maybe I'm doing something wrong but I can't get the extension to remember my API key.

oliversen commented 1 year ago

@quadrismegistus Thanks for the feedback! Please clarify, do you need to enter the API key every time you restart vscode or every time you generate a docstring? Could you give the output of the extension after setting the API key:

  1. Press Ctrl+Shift+U
  2. Select "ChatGPT: Docstrings Generator" channel issue
quadrismegistus commented 1 year ago

Here's the channel output, before and after running the Set OpenAPI Key command. That command appeared to make no effect on the output; not sure if it actually runs.

2023-07-09 12:24:40.349 [info] Used ChatGPT prompt:
Create docstring in google format for python function below, adding examples if the function is complex:
def testing(x):

    print(x)
2023-07-09 12:24:42.133 [info] Received ChatGPT docstring:
def testing(x):
    """
    Prints the value of x.

    Args:
        x: The value to be printed.

    Returns:
        None

    Examples:
        >>> testing(5)
        5
        >>> testing("Hello")
        Hello
    """
    pass
2023-07-09 12:24:51.769 [info] Used ChatGPT prompt:
Create docstring in google format for python function below, adding examples if the function is complex:
def testing(x):

    print(x)
2023-07-09 12:24:53.521 [info] Received ChatGPT docstring:
def testing(x):
    """
    Prints the value of x.

    Args:
        x: The value to be printed.

    Returns:
        None

    Examples:
        >>> testing(5)
        5
        >>> testing("Hello")
        Hello
    """
    pass
oliversen commented 1 year ago

@quadrismegistus The extension uses SecretStorage to store the OpenAI API key. The author of the SecretStorage API says it is built on http://github.com/atom/node-keytar.

A native Node module to get, add, replace, and delete passwords in system's keychain. On macOS the passwords are managed by the Keychain, on Linux they are managed by the Secret Service API/libsecret, and on Windows they are managed by Credential Vault.

Perhaps the problem lies in the limitations of your OS. In the latest release of the extension, I added logging of the API key saving error, if such occurs. Please update the extension and re-view the output. Perhaps the reason will become clear.

quadrismegistus commented 1 year ago

Thanks for your help. I re-installed the extension (wasn't sure how else to ensure it had updated), and then restarted VSCode, ran "Set API key" command and then ran a "Generate docstring command". The Set API key command still made no effect on the logs (though there may have been no error?). The "generate docstring" command then asked me for my key again at which time it sent the request to the server and gave back the response. Subsequent use of "generate docstring" asks for API key again.

I wonder if there's a way one could provide a path or set an environment variable as an alternative way of storing the key?

Here's the full output of the debug console:


  2023-07-12 04:03:25.612 [info] Name: ChatGPT: Docstring Generator
  2023-07-12 04:03:25.612 [info] Module: chatgpt-docstrings
  2023-07-12 04:03:25.612 [info] Python extension loading
  2023-07-12 04:03:25.612 [info] Waiting for interpreter from python extension.
  2023-07-12 04:03:25.612 [info] Python extension loaded
  2023-07-12 04:03:25.612 [info] Server run command: /Users/ryan/github/geotaste/venv/bin/python /Users/ryan/.vscode/extensions/oliversen.chatgpt-docstrings-0.2.1/bundled/tool/lsp_server.py
  2023-07-12 04:03:25.612 [info] Server: Start requested.
  2023-07-12 04:03:26.429 [info] CWD Server: /Users/ryan/github/geotaste
  2023-07-12 04:03:26.429 [info] sys.path used to run Server:
     /Users/ryan/.vscode/extensions/oliversen.chatgpt-docstrings-0.2.1/bundled/libs
     /Users/ryan/.vscode/extensions/oliversen.chatgpt-docstrings-0.2.1/bundled/tool
     /Users/ryan/github/parasolr
     /Users/ryan/github/geotaste
     /Users/ryan/.pyenv/versions/3.10.7/lib/python310.zip
     /Users/ryan/.pyenv/versions/3.10.7/lib/python3.10
     /Users/ryan/.pyenv/versions/3.10.7/lib/python3.10/lib-dynload
     /Users/ryan/github/geotaste/venv/lib/python3.10/site-packages
  2023-07-12 04:03:26.430 [info] Settings used to run Server:
  [
      {
          "cwd": "/Users/ryan/github/geotaste",
          "workspace": "file:///Users/ryan/github/geotaste",
          "interpreter": [
              "/Users/ryan/github/geotaste/venv/bin/python"
          ],
          "openaiModel": "gpt-3.5-turbo",
          "docstringFormat": "google",
          "chatgptPromptPattern": "Create docstring in {docstring_format} format for python function below, adding examples if the function is complex:\n{function}"
      }
  ]

  2023-07-12 04:03:26.430 [info] Global settings:
  {
      "cwd": "/",
      "workspace": "/",
      "interpreter": [],
      "openaiModel": "gpt-3.5-turbo",
      "docstringFormat": "google",
      "chatgptPromptPattern": "Create docstring in {docstring_format} format for python function below, adding examples if the function is complex:\n{function}"
  }

  2023-07-12 04:03:36.810 [info] Used ChatGPT prompt:
  Create docstring in google format for python function below, adding examples if the function is complex:
  def analyze_contingency_tables(
          vals1, 
          vals2, 
          funcs = [odds_ratio, fisher_exact], 
          sort_by='odds_ratio', 
          p_col='fisher_exact_p',
          sort_asc=True, 
          min_p=MIN_P,
          signif=False):

      vals1=pd.Series(vals1)
      vals2=pd.Series(vals2)
      index_name='__'.join(sorted(list(set([vals1.name, vals2.name]))))
      ld=[]
      vals_ctbls = list(iter_contingency_tables(vals1, vals2))
      for val,ctbl in vals_ctbls:
          val_d = {
              'value':val, 
              **table_info(ctbl)
          }
          for func in funcs:
              res = func(ctbl)
              method=func.__name__
              stat=res.statistic if hasattr(res,'statistic') else None
              pval=res.pvalue if hasattr(res,'pvalue') else None
              if stat is not None: val_d[f'{method}'] = stat
              if pval is not None: val_d[f'{method}_p'] = pval

          ld.append(val_d)
      df = pd.DataFrame(ld)
      if len(df):
          df=df.set_index('value')
          if signif and p_col: df = df[df[p_col]<=min_p]
      df = df.rename_axis(index_name)
      df = df.sort_values(sort_by, ascending=sort_asc) if sort_by and len(df) else df
      return df

  2023-07-12 04:03:48.640 [info] Received ChatGPT docstring:
  ```python
  def analyze_contingency_tables(
      vals1, 
      vals2, 
      funcs=[odds_ratio, fisher_exact], 
      sort_by='odds_ratio', 
      p_col='fisher_exact_p',
      sort_asc=True, 
      min_p=MIN_P,
      signif=False
  ):
      """
      Analyzes contingency tables created from two input value series.

      Args:
          vals1 (pd.Series): The first value series.
          vals2 (pd.Series): The second value series.
          funcs (list, optional): List of statistical functions to apply to each contingency table. Defaults to [odds_ratio, fisher_exact].
          sort_by (str, optional): The column to sort the resulting DataFrame by. Defaults to 'odds_ratio'.
          p_col (str, optional): The column containing p-values. Defaults to 'fisher_exact_p'.
          sort_asc (bool, optional): Whether to sort the DataFrame in ascending order. Defaults to True.
          min_p (float, optional): The minimum p-value threshold. Defaults to MIN_P.
          signif (bool, optional): Whether to filter the DataFrame by p-value threshold. Defaults to False.

      Returns:
          pd.DataFrame: The resulting DataFrame containing the analyzed contingency tables.

      Examples:
          >>> vals1 = pd.Series([1, 2, 3, 4, 5])
          >>> vals2 = pd.Series([6, 7, 8, 9, 10])
          >>> analyze_contingency_tables(vals1, vals2)
          # Output:
          #   value  odds_ratio  fisher_exact  fisher_exact_p
          # 0     1         NaN           NaN             NaN
          # 1     2         NaN           NaN             NaN
          # 2     3         NaN           NaN             NaN
          # 3     4         NaN           NaN             NaN
          # 4     5         NaN           NaN             NaN
      """
      # Function body is omitted
      pass

Note: The examples provided are for illustrative purposes only and may not reflect the actual output of the function.

oliversen commented 1 year ago

I apologize for the delay in reply. Obviously, the problem is either VSCode or the node-keytar package that it uses to store secrets. I suggest checking node-keytar directly. To do this, I created a simple script that first saves the secret, then gets.

"qwerty" should be displayed in the terminal.

oliversen commented 1 year ago

In the new release (0.3.1), I added saving the key to memory. Now you don't need to enter the key every time you generate a docstring. However, since it is not stored in SecretStorage, you will need to enter the key again after each restart of VSCode.

I will still ask you to run the script from my previous post to understand why it is not stored in your SecretStorage.