From b00bf2a0ece04ca426d9e5c4e99332fc1e51463d Mon Sep 17 00:00:00 2001 From: leo Date: Mon, 25 Aug 2025 17:18:21 +0800 Subject: [PATCH] feature: supports to read OpenAI API key from env (#1748) Signed-off-by: leo --- src/Models/OpenAI.cs | 10 +++++++++- src/Resources/Locales/en_US.axaml | 1 + src/Resources/Locales/zh_CN.axaml | 1 + src/Resources/Locales/zh_TW.axaml | 1 + src/Views/Preferences.axaml | 5 ++++- 5 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Models/OpenAI.cs b/src/Models/OpenAI.cs index f8d76328..9380a855 100644 --- a/src/Models/OpenAI.cs +++ b/src/Models/OpenAI.cs @@ -117,6 +117,12 @@ namespace SourceGit.Models set => SetProperty(ref _apiKey, value); } + public bool ReadApiKeyFromEnv + { + get => _readApiKeyFromEnv; + set => SetProperty(ref _readApiKeyFromEnv, value); + } + public string Model { get => _model; @@ -176,8 +182,9 @@ namespace SourceGit.Models public async Task ChatAsync(string prompt, string question, CancellationToken cancellation, Action onUpdate) { + var finalKey = _readApiKeyFromEnv ? Environment.GetEnvironmentVariable(_apiKey) : _apiKey; var server = new Uri(_server); - var key = new ApiKeyCredential(_apiKey); + var key = new ApiKeyCredential(finalKey); var oaiClient = _server.Contains("openai.azure.com/", StringComparison.Ordinal) ? new AzureOpenAIClient(server, key) : new OpenAIClient(key, new() { Endpoint = server }); @@ -220,6 +227,7 @@ namespace SourceGit.Models private string _name; private string _server; private string _apiKey; + private bool _readApiKeyFromEnv = false; private string _model; private bool _streaming = true; private string _analyzeDiffPrompt; diff --git a/src/Resources/Locales/en_US.axaml b/src/Resources/Locales/en_US.axaml index 6e16643f..be2fe1e6 100644 --- a/src/Resources/Locales/en_US.axaml +++ b/src/Resources/Locales/en_US.axaml @@ -530,6 +530,7 @@ Generate Subject Prompt Model Name + Entered value is the name to load API key from ENV Server Enable Streaming APPEARANCE diff --git a/src/Resources/Locales/zh_CN.axaml b/src/Resources/Locales/zh_CN.axaml index a1447d74..b6df5eef 100644 --- a/src/Resources/Locales/zh_CN.axaml +++ b/src/Resources/Locales/zh_CN.axaml @@ -534,6 +534,7 @@ Generate Subject Prompt 模型 配置名称 + 从环境变量(填写环境变量名)中读取API密钥 服务地址 启用流式输出 外观配置 diff --git a/src/Resources/Locales/zh_TW.axaml b/src/Resources/Locales/zh_TW.axaml index 93e6c2e4..5712a674 100644 --- a/src/Resources/Locales/zh_TW.axaml +++ b/src/Resources/Locales/zh_TW.axaml @@ -534,6 +534,7 @@ 產生提交訊息提示詞 模型 名稱 + 從環境變數中(輸入為環境變數名稱)載入金鑰 伺服器 啟用串流輸出 外觀設定 diff --git a/src/Views/Preferences.axaml b/src/Views/Preferences.axaml index 141262e4..d7f56ca1 100644 --- a/src/Views/Preferences.axaml +++ b/src/Views/Preferences.axaml @@ -788,7 +788,10 @@ - + +