Skip to content

Commit dc6f76e

Browse files
alejandroclaroAlejandro Claro
andauthored
fix(api): fix issue loading Azure OpenAI configuration (#364)
* fix(api): fix issue loading Azure OpenAI configuration Because of asynchronous operations, loading *_cmd options from configuration was not working properly. It was only working using the environment variables. Also add a missing options to set API type (api_type_cmd) from vim config files instead of having to set a environment variable. * style: fix linter findings and update README documentation - Format README.md file to comply with regular MD guidelines (linter findings) - Add information about new configuration options to configure Azure deployment programmatically. * style(api): fix stylua style findings --------- Co-authored-by: Alejandro Claro <alejandro.claro@smartmatic.com>
1 parent ff458cb commit dc6f76e

2 files changed

Lines changed: 147 additions & 63 deletions

File tree

README.md

Lines changed: 99 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,49 @@
33
![GitHub Workflow Status](http://img.shields.io/github/actions/workflow/status/jackMort/ChatGPT.nvim/default.yml?branch=main&style=for-the-badge)
44
![Lua](https://img.shields.io/badge/Made%20with%20Lua-blueviolet.svg?style=for-the-badge&logo=lua)
55

6-
`ChatGPT` is a Neovim plugin that allows you to effortlessly utilize the OpenAI ChatGPT API,
7-
empowering you to generate natural language responses from OpenAI's ChatGPT directly within the editor in response to your inquiries.
6+
`ChatGPT` is a Neovim plugin that allows you to effortlessly utilize the OpenAI
7+
ChatGPT API, empowering you to generate natural language responses from
8+
OpenAI's ChatGPT directly within the editor in response to your inquiries.
89

910
![preview image](https://github.com/jackMort/ChatGPT.nvim/blob/media/preview-2.png?raw=true)
1011

1112
## Features
12-
- **Interactive Q&A**: Engage in interactive question-and-answer sessions with the powerful gpt model (ChatGPT) using an intuitive interface.
13-
- **Persona-based Conversations**: Explore various perspectives and have conversations with different personas by selecting prompts from Awesome ChatGPT Prompts.
14-
- **Code Editing Assistance**: Enhance your coding experience with an interactive editing window powered by the gpt model, offering instructions tailored for coding tasks.
15-
- **Code Completion**: Enjoy the convenience of code completion similar to GitHub Copilot, leveraging the capabilities of the gpt model to suggest code snippets and completions based on context and programming patterns.
16-
- **Customizable Actions**: Execute a range of actions utilizing the gpt model, such as grammar correction, translation, keyword generation, docstring creation, test addition, code optimization, summarization, bug fixing, code explanation, Roxygen editing, and code readability analysis. Additionally, you can define your own custom actions using a JSON file.
1713

18-
For a comprehensive understanding of the extension's functionality, you can watch a plugin showcase [video](https://www.youtube.com/watch?v=7k0KZsheLP4)
14+
- **Interactive Q&A**: Engage in interactive question-and-answer sessions with
15+
the powerful gpt model (ChatGPT) using an intuitive interface.
16+
17+
- **Persona-based Conversations**: Explore various perspectives and have
18+
conversations with different personas by selecting prompts from Awesome ChatGPT
19+
Prompts.
20+
21+
- **Code Editing Assistance**: Enhance your coding experience with an interactive
22+
editing window powered by the gpt model, offering instructions tailored for
23+
coding tasks.
24+
25+
- **Code Completion**: Enjoy the convenience of code completion similar to GitHub
26+
Copilot, leveraging the capabilities of the gpt model to suggest code snippets
27+
and completions based on context and programming patterns.
28+
29+
- **Customizable Actions**: Execute a range of actions utilizing the gpt model,
30+
such as grammar correction, translation, keyword generation, docstring creation,
31+
test addition, code optimization, summarization, bug fixing, code explanation,
32+
Roxygen editing, and code readability analysis. Additionally, you can define
33+
your own custom actions using a JSON file.
34+
35+
For a comprehensive understanding of the extension's functionality, you can watch
36+
a plugin showcase [video](https://www.youtube.com/watch?v=7k0KZsheLP4)
1937

2038
## Installation
2139

2240
- Make sure you have `curl` installed.
41+
2342
- Get an API key from OpenAI, which you can [obtain here](https://beta.openai.com/account/api-keys). (NOTE: a ChatGPT Plus subscription doesn't currently include the required API credits. You'll have to buy API credits [separately](https://platform.openai.com/account/billing/overview).)
2443

2544
The OpenAI API key can be provided in one of the following two ways:
2645

2746
1. In the configuration option `api_key_cmd`, provide the path and arguments to
2847
an executable that returns the API key via stdout.
48+
2949
1. Setting it via an environment variable called `$OPENAI_API_KEY`.
3050

3151
Custom OpenAI API host with the configuration option `api_host_cmd` or
@@ -34,6 +54,7 @@ OpenAI directly
3454

3555
Custom cURL parameters can be passed using the configuration option `extra_curl_params`.
3656
It can be useful if you need to include additional headers for requests:
57+
3758
```lua
3859
{
3960
...,
@@ -44,12 +65,45 @@ It can be useful if you need to include additional headers for requests:
4465
}
4566
```
4667

47-
For Azure deployments, you also need to set environment variables
48-
`$OPENAI_API_TYPE` to `azure`, `$OPENAI_API_BASE` to your own resource URL,
49-
e.g. `https://{your-resource-name}.openai.azure.com`, and `$OPENAI_API_AZURE_ENGINE`
50-
to your deployment ID. Optionally, if you need a different API version,
51-
set `$OPENAI_API_AZURE_VERSION` as well. Note that edit models have been deprecated
52-
so they might not work.
68+
For Azure deployments, you need to specify the URL base, the engine, and the API
69+
type. You can accomplish this in one of two ways:
70+
71+
1. Use the configuration options `api_type_cmd`, `azure_api_base`,
72+
`azure_api_engine_cmd`, and `azure_api_version_cmd`. Each of these should be
73+
an executable command that returns the corresponding value.
74+
75+
For example:
76+
77+
```lua
78+
local config = {
79+
api_host_cmd = 'echo -n ""',
80+
api_key_cmd = 'pass azure-openai-key',
81+
api_type_cmd = 'echo azure',
82+
azure_api_base_cmd = 'echo https://{your-resource-name}.openai.azure.com',
83+
azure_api_engine_cmd = 'echo chat',
84+
azure_api_version_cmd = 'echo 2023-05-15'
85+
}
86+
87+
require("chatgpt").setup(config)
88+
```
89+
90+
1. Set the values via the environment variables `$OPENAI_API_TYPE`,
91+
`$OPENAI_API_BASE`, `$OPENAI_API_AZURE_ENGINE`, and `$OPENAI_API_AZURE_VERSION`.
92+
93+
For example:
94+
95+
```bash
96+
export OPENAI_API_TYPE="azure"
97+
export OPENAI_API_BASE="https://{your-resource-name}.openai.azure.com"
98+
export OPENAI_API_AZURE_ENGINE="chat"
99+
export OPENAI_API_AZURE_VERSION="2023-05-15"
100+
```
101+
102+
Please note that edit models have been deprecated and may not function as
103+
expected.
104+
105+
If you are using [packer.nvim](https://github.com/wbthomason/packer.nvim) as
106+
plugin manager:
53107

54108
```lua
55109
-- Packer
@@ -66,6 +120,8 @@ use({
66120
}
67121
})
68122

123+
or if you are using [lazy.nvim](https://github.com/folke/lazy.nvim):
124+
69125
-- Lazy
70126
{
71127
"jackMort/ChatGPT.nvim",
@@ -84,7 +140,8 @@ use({
84140

85141
## Configuration
86142

87-
`ChatGPT.nvim` comes with the following defaults, you can override them by passing config as setup param
143+
`ChatGPT.nvim` comes with the following defaults, you can override them by
144+
passing config as setup param
88145

89146
https://github.com/jackMort/ChatGPT.nvim/blob/f1453f588eb47e49e57fa34ac1776b795d71e2f1/lua/chatgpt/config.lua#L10-L182
90147

@@ -119,26 +176,36 @@ require("chatgpt").setup({
119176
})
120177
```
121178

122-
Note that the `api_key_cmd` arguments are split by whitespace. If you need whitespace inside an argument (for example to reference a path with spaces), you can wrap it in a separate script.
179+
Note that the `api_key_cmd` arguments are split by whitespace. If you need
180+
whitespace inside an argument (for example to reference a path with spaces),
181+
you can wrap it in a separate script.
123182

124183
## Usage
125184

126185
Plugin exposes following commands:
127186

128-
#### `ChatGPT`
187+
### `ChatGPT`
188+
129189
`ChatGPT` command which opens interactive window using the `gpt-3.5-turbo`
130190
model.
131191
(also known as `ChatGPT`)
132192

133-
#### `ChatGPTActAs`
134-
`ChatGPTActAs` command which opens a prompt selection from [Awesome ChatGPT Prompts](https://github.com/f/awesome-chatgpt-prompts) to be used with the `gpt-3.5-turbo` model.
193+
### `ChatGPTActAs`
194+
195+
`ChatGPTActAs` command which opens a prompt selection from
196+
[Awesome ChatGPT Prompts](https://github.com/f/awesome-chatgpt-prompts)
197+
to be used with the `gpt-3.5-turbo` model.
135198

136199
![preview image](https://github.com/jackMort/ChatGPT.nvim/blob/media/preview-3.png?raw=true)
137200

138-
#### `ChatGPTEditWithInstructions`
139-
`ChatGPTEditWithInstructions` command which opens interactive window to edit selected text or whole window using the `code-davinci-edit-001` model (GPT 3.5 fine-tuned for coding).
201+
### `ChatGPTEditWithInstructions`
202+
203+
`ChatGPTEditWithInstructions` command which opens interactive window to edit
204+
selected text or whole window using the `code-davinci-edit-001` model (GPT 3.5
205+
fine-tuned for coding).
140206

141207
You can map it using the Lua API, e.g. using `which-key.nvim`:
208+
142209
```lua
143210
local chatgpt = require("chatgpt")
144211
wk.register({
@@ -163,7 +230,10 @@ wk.register({
163230

164231
#### `ChatGPTRun`
165232

166-
`ChatGPTRun [action]` command which runs specific actions -- see [`actions.json`](./lua/chatgpt/flows/actions/actions.json) file for a detailed list. Available actions are:
233+
`ChatGPTRun [action]` command which runs specific actions -- See
234+
[`actions.json`](./lua/chatgpt/flows/actions/actions.json) file for a detailed
235+
list. Available actions are:
236+
167237
1. `grammar_correction`
168238
2. `translate`
169239
3. `keywords`
@@ -181,6 +251,7 @@ All the above actions are using `gpt-3.5-turbo` model.
181251
It is possible to define custom actions with a JSON file. See [`actions.json`](./lua/chatgpt/flows/actions/actions.json) for an example. The path of custom actions can be set in the config (see `actions_paths` field in the config example above).
182252

183253
An example of custom action may look like this: (`#` marks comments)
254+
184255
```python
185256
{
186257
"action_name": {
@@ -205,6 +276,7 @@ An example of custom action may look like this: (`#` marks comments)
205276
}
206277
}
207278
```
279+
208280
The `edit` strategy consists in showing the output side by side with the input and
209281
available for further editing requests.
210282
For now, `edit` strategy is implemented for `chat` type only.
@@ -214,8 +286,10 @@ The `display` strategy shows the output in a float window.
214286
`append` and `replace` modify the text directly in the buffer.
215287

216288
### Interactive popup
289+
217290
When using `ChatGPT` and `ChatGPTEditWithInstructions`, the following
218291
keybindings are available:
292+
219293
- `<C-Enter>` [Both] to submit.
220294
- `<C-y>` [Both] to copy/yank last answer.
221295
- `<C-o>` [Both] Toggle settings window.
@@ -239,7 +313,9 @@ When the setting window is opened (with `<C-o>`), settings can be modified by
239313
pressing `Enter` on the related config. Settings are saved across sections
240314

241315
### Whichkey plugin mappings
242-
Add these to your [whichkey](https://github.com/folke/which-key.nvim) plugin mappings for convenient binds
316+
317+
Add these to your [whichkey](https://github.com/folke/which-key.nvim) plugin
318+
mappings for convenient binds
243319

244320
```lua
245321
c = {

lua/chatgpt/api.lua

Lines changed: 48 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -220,54 +220,60 @@ local function loadConfigFromEnv(envName, configName, callback)
220220
end
221221
end
222222

223-
local function loadApiHost(envName, configName, optionName, callback, defaultValue)
223+
local function loadOptionalConfig(envName, configName, optionName, callback, defaultValue)
224224
loadConfigFromEnv(envName, configName)
225225
if Api[configName] then
226226
callback(Api[configName])
227+
elseif Config.options[optionName] ~= nil and Config.options[optionName] ~= "" then
228+
loadConfigFromCommand(Config.options[optionName], optionName, callback, defaultValue)
227229
else
228-
if Config.options[optionName] ~= nil and Config.options[optionName] ~= "" then
229-
loadConfigFromCommand(Config.options[optionName], optionName, callback, defaultValue)
230-
else
231-
callback(defaultValue)
232-
end
230+
callback(defaultValue)
233231
end
234232
end
235233

236-
local function loadApiKey(envName, configName, optionName, callback, defaultValue)
234+
local function loadRequiredConfig(envName, configName, optionName, callback, defaultValue)
237235
loadConfigFromEnv(envName, configName, callback)
238236
if not Api[configName] then
239237
if Config.options[optionName] ~= nil and Config.options[optionName] ~= "" then
240238
loadConfigFromCommand(Config.options[optionName], optionName, callback, defaultValue)
241239
else
242-
logger.warn(envName .. " environment variable not set")
240+
logger.warn(configName .. " variable not set")
243241
return
244242
end
245243
end
246244
end
247245

248246
local function loadAzureConfigs()
249-
loadApiKey("OPENAI_API_BASE", "OPENAI_API_BASE", "azure_api_base_cmd", function(value)
250-
Api.OPENAI_API_BASE = value
251-
end)
252-
loadApiKey("OPENAI_API_AZURE_ENGINE", "OPENAI_API_AZURE_ENGINE", "azure_api_engine_cmd", function(value)
253-
Api.OPENAI_API_AZURE_ENGINE = value
247+
loadRequiredConfig("OPENAI_API_BASE", "OPENAI_API_BASE", "azure_api_base_cmd", function(base)
248+
Api.OPENAI_API_BASE = base
249+
250+
loadRequiredConfig("OPENAI_API_AZURE_ENGINE", "OPENAI_API_AZURE_ENGINE", "azure_api_engine_cmd", function(engine)
251+
Api.OPENAI_API_AZURE_ENGINE = engine
252+
253+
loadOptionalConfig(
254+
"OPENAI_API_AZURE_VERSION",
255+
"OPENAI_API_AZURE_VERSION",
256+
"azure_api_version_cmd",
257+
function(version)
258+
Api.OPENAI_API_AZURE_VERSION = version
259+
260+
if Api["OPENAI_API_BASE"] and Api["OPENAI_API_AZURE_ENGINE"] then
261+
Api.COMPLETIONS_URL = Api.OPENAI_API_BASE
262+
.. "/openai/deployments/"
263+
.. Api.OPENAI_API_AZURE_ENGINE
264+
.. "/completions?api-version="
265+
.. Api.OPENAI_API_AZURE_VERSION
266+
Api.CHAT_COMPLETIONS_URL = Api.OPENAI_API_BASE
267+
.. "/openai/deployments/"
268+
.. Api.OPENAI_API_AZURE_ENGINE
269+
.. "/chat/completions?api-version="
270+
.. Api.OPENAI_API_AZURE_VERSION
271+
end
272+
end,
273+
"2023-05-15"
274+
)
275+
end)
254276
end)
255-
loadApiHost("OPENAI_API_AZURE_VERSION", "OPENAI_API_AZURE_VERSION", "azure_api_version_cmd", function(value)
256-
Api.OPENAI_API_AZURE_VERSION = value
257-
end, "2023-05-15")
258-
259-
if Api["OPENAI_API_BASE"] and Api["OPENAI_API_AZURE_ENGINE"] then
260-
Api.COMPLETIONS_URL = Api.OPENAI_API_BASE
261-
.. "/openai/deployments/"
262-
.. Api.OPENAI_API_AZURE_ENGINE
263-
.. "/completions?api-version="
264-
.. Api.OPENAI_API_AZURE_VERSION
265-
Api.CHAT_COMPLETIONS_URL = Api.OPENAI_API_BASE
266-
.. "/openai/deployments/"
267-
.. Api.OPENAI_API_AZURE_ENGINE
268-
.. "/chat/completions?api-version="
269-
.. Api.OPENAI_API_AZURE_VERSION
270-
end
271277
end
272278

273279
local function startsWith(str, start)
@@ -283,22 +289,24 @@ local function ensureUrlProtocol(str)
283289
end
284290

285291
function Api.setup()
286-
loadApiHost("OPENAI_API_HOST", "OPENAI_API_HOST", "api_host_cmd", function(value)
287-
Api.OPENAI_API_HOST = value
292+
loadOptionalConfig("OPENAI_API_HOST", "OPENAI_API_HOST", "api_host_cmd", function(host)
293+
Api.OPENAI_API_HOST = host
288294
Api.COMPLETIONS_URL = ensureUrlProtocol(Api.OPENAI_API_HOST .. "/v1/completions")
289295
Api.CHAT_COMPLETIONS_URL = ensureUrlProtocol(Api.OPENAI_API_HOST .. "/v1/chat/completions")
290296
Api.EDITS_URL = ensureUrlProtocol(Api.OPENAI_API_HOST .. "/v1/edits")
291297
end, "api.openai.com")
292298

293-
loadApiKey("OPENAI_API_KEY", "OPENAI_API_KEY", "api_key_cmd", function(value)
294-
Api.OPENAI_API_KEY = value
295-
loadConfigFromEnv("OPENAI_API_TYPE", "OPENAI_API_TYPE")
296-
if Api["OPENAI_API_TYPE"] == "azure" then
297-
loadAzureConfigs()
298-
Api.AUTHORIZATION_HEADER = "api-key: " .. Api.OPENAI_API_KEY
299-
else
300-
Api.AUTHORIZATION_HEADER = "Authorization: Bearer " .. Api.OPENAI_API_KEY
301-
end
299+
loadRequiredConfig("OPENAI_API_KEY", "OPENAI_API_KEY", "api_key_cmd", function(key)
300+
Api.OPENAI_API_KEY = key
301+
302+
loadOptionalConfig("OPENAI_API_TYPE", "OPENAI_API_TYPE", "api_type_cmd", function(type)
303+
if type == "azure" then
304+
loadAzureConfigs()
305+
Api.AUTHORIZATION_HEADER = "api-key: " .. Api.OPENAI_API_KEY
306+
else
307+
Api.AUTHORIZATION_HEADER = "Authorization: Bearer " .. Api.OPENAI_API_KEY
308+
end
309+
end, "")
302310
end)
303311
end
304312

0 commit comments

Comments
 (0)