A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.
C++
feat(windows): fetch AI model list from provider API in Settings
DangHuynh2253da0d4e31
diff --git a/windows/Gridex/AiService.cpp b/windows/Gridex/AiService.cppindex e699757..f4a073e 100644--- a/windows/Gridex/AiService.cpp+++ b/windows/Gridex/AiService.cpp@@ -3,6 +3,7 @@#include <windows.h>#include "Models/AiService.h"#include <nlohmann/json.hpp>+#include <algorithm>// cpp-httplib for HTTP client — suppress deprecated SSL API warnings#pragma warning(push)@@ -408,4 +409,212 @@ namespace DBModels}return L"No response content";}++ // ── Fetch available models per provider ────────────+ //+ // Each provider exposes a different listing endpoint and response+ // shape. Normalise everything to a flat vector<wstring> of model IDs+ // that the Settings ComboBox can display. Keep the existing network+ // style (cpp-httplib + nlohmann::json) from the chat calls.+ ModelListResult AiService::FetchModels(const AiConfig& config)+ {+ ModelListResult r;+ auto apiKey = trimWs(config.apiKey);++ try+ {+ switch (config.provider)+ {+ case AiProvider::Anthropic:+ {+ if (apiKey.empty())+ {+ r.errorMessage = L"Anthropic API key is missing.";+ return r;+ }+ httplib::Client cli("https://api.anthropic.com");+ cli.set_connection_timeout(15);+ cli.set_read_timeout(30);+ httplib::Headers headers = {+ { "x-api-key", toUtf8(apiKey) },+ { "anthropic-version","2023-06-01" },+ };+ auto res = cli.Get("/v1/models?limit=1000", headers);+ if (!res)+ {+ r.errorMessage = L"Anthropic models request failed (no response).";+ return r;+ }+ if (res->status != 200)+ {+ r.errorMessage = fromUtf8("HTTP " + std::to_string(res->status) + ": " + res->body);+ return r;+ }+ auto json = nlohmann::json::parse(res->body);+ if (json.contains("data") && json["data"].is_array())+ {+ for (auto& m : json["data"])+ if (m.contains("id"))+ r.models.push_back(fromUtf8(m["id"].get<std::string>()));+ }+ break;+ }++ case AiProvider::OpenAI:+ {+ if (apiKey.empty())+ {+ r.errorMessage = L"OpenAI API key is missing.";+ return r;+ }+ httplib::Client cli("https://api.openai.com");+ cli.set_connection_timeout(15);+ cli.set_read_timeout(30);+ httplib::Headers headers = {+ { "Authorization", "Bearer " + toUtf8(apiKey) },+ };+ auto res = cli.Get("/v1/models", headers);+ if (!res)+ {+ r.errorMessage = L"OpenAI models request failed (no response).";+ return r;+ }+ if (res->status != 200)+ {+ r.errorMessage = fromUtf8("HTTP " + std::to_string(res->status) + ": " + res->body);+ return r;+ }+ auto json = nlohmann::json::parse(res->body);+ if (json.contains("data") && json["data"].is_array())+ {+ for (auto& m : json["data"])+ if (m.contains("id"))+ r.models.push_back(fromUtf8(m["id"].get<std::string>()));+ }+ break;+ }++ case AiProvider::Ollama:+ {+ // Ollama needs the endpoint, not an API key. Default+ // localhost:11434 when user hasn't customized it.+ std::wstring endpointW = trimWs(config.ollamaEndpoint);+ if (endpointW.empty()) endpointW = L"http://localhost:11434";+ auto endpoint = toUtf8(endpointW);+ httplib::Client cli(endpoint);+ cli.set_connection_timeout(10);+ cli.set_read_timeout(15);+ auto res = cli.Get("/api/tags");+ if (!res)+ {+ r.errorMessage = L"Ollama endpoint unreachable: " + endpointW;+ return r;+ }+ if (res->status != 200)+ {+ r.errorMessage = fromUtf8("HTTP " + std::to_string(res->status) + ": " + res->body);+ return r;+ }+ auto json = nlohmann::json::parse(res->body);+ if (json.contains("models") && json["models"].is_array())+ {+ for (auto& m : json["models"])+ if (m.contains("name"))+ r.models.push_back(fromUtf8(m["name"].get<std::string>()));+ }+ break;+ }++ case AiProvider::Gemini:+ {+ if (apiKey.empty())+ {+ r.errorMessage = L"Gemini API key is missing.";+ return r;+ }+ httplib::Client cli("https://generativelanguage.googleapis.com");+ cli.set_connection_timeout(15);+ cli.set_read_timeout(30);+ std::string path = "/v1beta/models?key=" + toUtf8(apiKey);+ auto res = cli.Get(path.c_str());+ if (!res)+ {+ r.errorMessage = L"Gemini models request failed (no response).";+ return r;+ }+ if (res->status != 200)+ {+ r.errorMessage = fromUtf8("HTTP " + std::to_string(res->status) + ": " + res->body);+ return r;+ }+ auto json = nlohmann::json::parse(res->body);+ if (json.contains("models") && json["models"].is_array())+ {+ // Gemini returns "name": "models/gemini-2.0-flash".+ // Strip the "models/" prefix so the value matches+ // what the chat endpoint expects in its URL path.+ for (auto& m : json["models"])+ {+ if (!m.contains("name")) continue;+ std::string id = m["name"].get<std::string>();+ const std::string prefix = "models/";+ if (id.rfind(prefix, 0) == 0) id = id.substr(prefix.size());+ r.models.push_back(fromUtf8(id));+ }+ }+ break;+ }++ case AiProvider::OpenRouter:+ {+ // OpenRouter /models endpoint is public — no API key+ // required just to list. If apiKey present we pass it+ // for completeness / rate-limit attribution.+ httplib::Client cli("https://openrouter.ai");+ cli.set_connection_timeout(15);+ cli.set_read_timeout(30);+ httplib::Headers headers;+ if (!apiKey.empty())+ headers.emplace("Authorization", "Bearer " + toUtf8(apiKey));+ auto res = cli.Get("/api/v1/models", headers);+ if (!res)+ {+ r.errorMessage = L"OpenRouter models request failed (no response).";+ return r;+ }+ if (res->status != 200)+ {+ r.errorMessage = fromUtf8("HTTP " + std::to_string(res->status) + ": " + res->body);+ return r;+ }+ auto json = nlohmann::json::parse(res->body);+ if (json.contains("data") && json["data"].is_array())+ {+ for (auto& m : json["data"])+ if (m.contains("id"))+ r.models.push_back(fromUtf8(m["id"].get<std::string>()));+ }+ break;+ }++ default:+ r.errorMessage = L"Unsupported provider.";+ return r;+ }++ // Alphabetize so the dropdown is easy to scan; OpenAI /+ // OpenRouter lists are unsorted by default.+ std::sort(r.models.begin(), r.models.end());+ r.success = true;+ }+ catch (const std::exception& e)+ {+ r.errorMessage = fromUtf8(std::string("Parse error: ") + e.what());+ }+ catch (...)+ {+ r.errorMessage = L"Unknown error fetching models.";+ }+ return r;+ }}diff --git a/windows/Gridex/Models/AiService.h b/windows/Gridex/Models/AiService.hindex 0242691..8c7dda7 100644--- a/windows/Gridex/Models/AiService.h+++ b/windows/Gridex/Models/AiService.h@@ -32,6 +32,17 @@ namespace DBModelsstd::wstring content;};+ // Result of a FetchModels() call. success=false → errorMessage holds+ // a user-visible reason (network error, bad key, unsupported+ // endpoint); models may still be empty on success for providers+ // without any models configured.+ struct ModelListResult+ {+ bool success = false;+ std::vector<std::wstring> models;+ std::wstring errorMessage;+ };+// AI service for text-to-SQL and chat interactionsclass AiService{@@ -50,6 +61,14 @@ namespace DBModelsconst std::wstring& naturalLanguage,const std::wstring& schemaDescription);+ // List available models for the given provider config. BLOCKS on+ // the provider's HTTP models endpoint — callers on the UI thread+ // must dispatch to a worker. Used by Settings to populate an+ // editable ComboBox so users pick from a live list instead of+ // memorizing model IDs, while still allowing a free-typed name+ // for custom OpenAI-compatible domains.+ static ModelListResult FetchModels(const AiConfig& config);+private:AiConfig config_;diff --git a/windows/Gridex/SettingsPage.cpp b/windows/Gridex/SettingsPage.cppindex 756e1c7..78e25da 100644--- a/windows/Gridex/SettingsPage.cpp+++ b/windows/Gridex/SettingsPage.cpp@@ -4,9 +4,11 @@#include <shellapi.h>#include "SettingsPage.h"#include "Models/AppSettings.h"+#include "Models/AiService.h"#include "Models/ShortcutsCatalog.h"#include "GridexVersion.h"#include "UpdateService.h"+#include <thread>#if __has_include("SettingsPage.g.cpp")#include "SettingsPage.g.cpp"#endif@@ -37,11 +39,88 @@ namespace winrt::Gridex::implementationThemeCombo().SelectedIndex(s.themeIndex);AiProviderCombo().SelectedIndex(s.aiProviderIndex);ApiKeyBox().Password(winrt::hstring(s.aiApiKey));+ // ModelBox is an editable ComboBox. Set .Text so any+ // previously-saved model (including free-typed custom+ // names) round-trips, even before Refresh populates the+ // dropdown from the provider API.ModelBox().Text(winrt::hstring(s.aiModel));OllamaEndpointBox().Text(winrt::hstring(s.ollamaEndpoint));EditorFontSizeBox().Value(static_cast<double>(s.editorFontSize));RowLimitBox().Value(static_cast<double>(s.rowLimit));+ // Refresh models: hit the provider's list endpoint on a+ // worker thread, populate ModelBox items on success. Keep+ // the user's current text selection after repopulating so+ // free-typed custom names (for OpenAI-compatible proxies+ // like DeepSeek, Groq, etc.) survive the round-trip.+ RefreshModelsBtn().Click(+ [this](winrt::Windows::Foundation::IInspectable const&, mux::RoutedEventArgs const&)+ {+ DBModels::AiConfig cfg;+ cfg.provider = static_cast<DBModels::AiProvider>(AiProviderCombo().SelectedIndex());+ cfg.apiKey = std::wstring(ApiKeyBox().Password());+ cfg.model = std::wstring(ModelBox().Text());+ cfg.ollamaEndpoint = std::wstring(OllamaEndpointBox().Text());++ RefreshModelsBtn().IsEnabled(false);+ ModelFetchStatusText().Visibility(mux::Visibility::Visible);+ ModelFetchStatusText().Text(L"Fetching models…");++ auto dispatcher = this->DispatcherQueue();+ std::thread([cfg, dispatcher,+ weak = get_weak()]()+ {+ auto res = DBModels::AiService::FetchModels(cfg);+ dispatcher.TryEnqueue([weak, res]()+ {+ auto self = weak.get();+ if (!self) return;++ self->RefreshModelsBtn().IsEnabled(true);++ if (!res.success)+ {+ self->ModelFetchStatusText().Text(+ winrt::hstring(L"Fetch failed: " + res.errorMessage));+ return;+ }++ // Preserve whatever the user typed / had+ // selected before; reassign after populating+ // so the TextBox portion of the editable+ // ComboBox keeps its value.+ auto keep = std::wstring(self->ModelBox().Text());++ self->ModelBox().Items().Clear();+ for (const auto& m : res.models)+ self->ModelBox().Items().Append(+ winrt::box_value(winrt::hstring(m)));++ // If the kept value matches one of the+ // freshly-fetched models, select it so the+ // ComboBox shows the item highlight; else+ // just leave the custom text in place.+ bool matched = false;+ for (uint32_t i = 0; i < self->ModelBox().Items().Size(); ++i)+ {+ auto item = winrt::unbox_value<winrt::hstring>(+ self->ModelBox().Items().GetAt(i));+ if (std::wstring(item) == keep)+ {+ self->ModelBox().SelectedIndex(static_cast<int32_t>(i));+ matched = true;+ break;+ }+ }+ if (!matched) self->ModelBox().Text(winrt::hstring(keep));++ self->ModelFetchStatusText().Text(+ winrt::hstring(L"Loaded " ++ std::to_wstring(res.models.size()) + L" models."));+ });+ }).detach();+ });+ThemeCombo().SelectionChanged([this](winrt::Windows::Foundation::IInspectable const&, muxc::SelectionChangedEventArgs const&){@@ -195,6 +274,9 @@ namespace winrt::Gridex::implementations.themeIndex = ThemeCombo().SelectedIndex();s.aiProviderIndex = AiProviderCombo().SelectedIndex();s.aiApiKey = std::wstring(ApiKeyBox().Password());+ // ModelBox is an editable ComboBox; .Text returns whatever the+ // user has in the edit field — a picked list item or a freely+ // typed custom model name, both save the same way.s.aiModel = std::wstring(ModelBox().Text());s.ollamaEndpoint = std::wstring(OllamaEndpointBox().Text());s.editorFontSize = static_cast<int>(EditorFontSizeBox().Value());diff --git a/windows/Gridex/SettingsPage.xaml b/windows/Gridex/SettingsPage.xamlindex af464a3..3928f3b 100644--- a/windows/Gridex/SettingsPage.xaml+++ b/windows/Gridex/SettingsPage.xaml@@ -101,10 +101,27 @@<StackPanel Spacing="4"><TextBlock Text="Model" FontSize="14" />- <TextBox x:Name="ModelBox"- PlaceholderText="e.g. claude-sonnet-4-20250514, gpt-4o, llama3, gemini-2.0-flash, openai/gpt-4o-mini"- Width="400"- HorizontalAlignment="Left" />+ <StackPanel Orientation="Horizontal" Spacing="6">+ <!-- Editable ComboBox: pick from the+ list fetched via Refresh, or type a+ custom model name (custom domains,+ OpenAI-compatible proxies, etc.). -->+ <ComboBox x:Name="ModelBox"+ IsEditable="true"+ PlaceholderText="Pick or type a model…"+ Width="400" />+ <Button x:Name="RefreshModelsBtn"+ ToolTipService.ToolTip="Fetch available models from the selected provider">+ <StackPanel Orientation="Horizontal" Spacing="6">+ <FontIcon Glyph="" FontSize="12" />+ <TextBlock Text="Refresh" FontSize="12" />+ </StackPanel>+ </Button>+ </StackPanel>+ <TextBlock x:Name="ModelFetchStatusText"+ FontSize="11"+ Foreground="{ThemeResource TextFillColorTertiaryBrush}"+ Visibility="Collapsed" /></StackPanel><StackPanel x:Name="OllamaEndpointPanel" Spacing="4">