forked from pgadmin-org/pgadmin4
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path__init__.py
More file actions
1925 lines (1664 loc) · 58.1 KB
/
__init__.py
File metadata and controls
1925 lines (1664 loc) · 58.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2026, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
"""A blueprint module implementing LLM/AI configuration."""
import json
import ssl
from flask import request
from flask_babel import gettext
from pgadmin.utils import PgAdminModule
from pgadmin.utils.preferences import Preferences
from pgadmin.utils.ajax import make_json_response, internal_server_error
from pgadmin.user_login_check import pga_login_required
from pgadmin.utils.constants import MIMETYPE_APP_JS
from pgadmin.utils.csrf import pgCSRFProtect
import config
# Try to use certifi for proper SSL certificate handling
try:
import certifi
SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where())
except ImportError:
SSL_CONTEXT = ssl.create_default_context()
# Enforce minimum TLS 1.2 to satisfy security requirements
SSL_CONTEXT.minimum_version = ssl.TLSVersion.TLSv1_2
MODULE_NAME = 'llm'
# Valid LLM providers
LLM_PROVIDERS = ['anthropic', 'openai', 'ollama', 'docker']
class LLMModule(PgAdminModule):
"""LLM configuration module for pgAdmin."""
def register_preferences(self):
"""
Register preferences for LLM providers.
"""
# Don't register AI preferences if LLM is disabled at system level
if not getattr(config, 'LLM_ENABLED', False):
return
self.preference = Preferences('ai', gettext('AI'))
# Default Provider Setting
provider_options = [
{'label': gettext('None (Disabled)'), 'value': ''},
{'label': gettext('Anthropic'), 'value': 'anthropic'},
{'label': gettext('OpenAI'), 'value': 'openai'},
{'label': gettext('Ollama'), 'value': 'ollama'},
{'label': gettext('Docker Model Runner'), 'value': 'docker'},
]
# Get default provider from config
default_provider_value = getattr(config, 'DEFAULT_LLM_PROVIDER', '')
self.default_provider = self.preference.register(
'general', 'default_provider',
gettext("Default Provider"), 'options',
default_provider_value,
category_label=gettext('AI Configuration'),
options=provider_options,
help_str=gettext(
'The LLM provider to use for AI features. '
'Select "None (Disabled)" to disable AI features. '
'Note: AI features must also be enabled in the server '
'configuration (LLM_ENABLED) for this setting to take effect.'
),
control_props={'allowClear': False}
)
# Maximum Tool Iterations
max_tool_iterations_default = getattr(
config, 'MAX_LLM_TOOL_ITERATIONS', 20
)
self.max_tool_iterations = self.preference.register(
'general', 'max_tool_iterations',
gettext("Max Tool Iterations"), 'integer',
max_tool_iterations_default,
category_label=gettext('AI Configuration'),
min_val=1,
max_val=100,
help_str=gettext(
'Maximum number of tool call iterations allowed during an AI '
'conversation. Higher values allow more complex queries but '
'may consume more resources. Default is 20.'
)
)
# Anthropic Settings
# Get defaults from config
anthropic_url_default = getattr(config, 'ANTHROPIC_API_URL', '')
anthropic_key_file_default = getattr(
config, 'ANTHROPIC_API_KEY_FILE', ''
)
anthropic_model_default = getattr(config, 'ANTHROPIC_API_MODEL', '')
self.anthropic_api_url = self.preference.register(
'anthropic', 'anthropic_api_url',
gettext("API URL"), 'text',
anthropic_url_default,
category_label=gettext('Anthropic'),
help_str=gettext(
'URL for the Anthropic API endpoint. Leave empty to use '
'the default (https://api.anthropic.com/v1). Set a custom '
'URL to use an Anthropic-compatible API provider.'
)
)
self.anthropic_api_key_file = self.preference.register(
'anthropic', 'anthropic_api_key_file',
gettext("API Key File"), 'text',
anthropic_key_file_default,
category_label=gettext('Anthropic'),
help_str=gettext(
'Path to a file containing your Anthropic API key. '
'This path must be on the server hosting pgAdmin, '
'e.g. inside the container when using Docker. '
'The file should contain only the API key. The API key '
'may be optional when using a custom API URL with a '
'provider that does not require authentication.'
)
)
# Fallback Anthropic models (used if API fetch fails)
anthropic_model_options = []
self.anthropic_api_model = self.preference.register(
'anthropic', 'anthropic_api_model',
gettext("Model"), 'options',
anthropic_model_default,
category_label=gettext('Anthropic'),
options=anthropic_model_options,
help_str=gettext(
'The Anthropic model to use. Models are loaded dynamically '
'from your API key. You can also type a custom model name. '
'Leave empty to use the default (Claude Sonnet 4).'
),
control_props={
'allowClear': True,
'creatable': True,
'tags': True,
'placeholder': gettext('Select or type a model name...'),
'optionsUrl': 'llm.models_anthropic',
'optionsRefreshUrl': 'llm.refresh_models_anthropic',
'refreshDepNames': {
'api_url': 'anthropic_api_url',
'api_key_file': 'anthropic_api_key_file'
}
}
)
# OpenAI Settings
# Get defaults from config
openai_url_default = getattr(config, 'OPENAI_API_URL', '')
openai_key_file_default = getattr(config, 'OPENAI_API_KEY_FILE', '')
openai_model_default = getattr(config, 'OPENAI_API_MODEL', '')
self.openai_api_url = self.preference.register(
'openai', 'openai_api_url',
gettext("API URL"), 'text',
openai_url_default,
category_label=gettext('OpenAI'),
help_str=gettext(
'URL for the OpenAI API endpoint. Leave empty to use '
'the default (https://api.openai.com/v1). Set a custom '
'URL to use any OpenAI-compatible API provider such as '
'LiteLLM, LM Studio, or EXO. The URL should include the '
'/v1 path prefix if required by your provider '
'(e.g., http://localhost:1234/v1).'
)
)
self.openai_api_key_file = self.preference.register(
'openai', 'openai_api_key_file',
gettext("API Key File"), 'text',
openai_key_file_default,
category_label=gettext('OpenAI'),
help_str=gettext(
'Path to a file containing your OpenAI API key. '
'This path must be on the server hosting pgAdmin, '
'e.g. inside the container when using Docker. '
'The file should contain only the API key. The API key '
'may be optional when using a custom API URL with a '
'provider that does not require authentication.'
)
)
# Fallback OpenAI models (used if API fetch fails)
openai_model_options = []
self.openai_api_model = self.preference.register(
'openai', 'openai_api_model',
gettext("Model"), 'options',
openai_model_default,
category_label=gettext('OpenAI'),
options=openai_model_options,
help_str=gettext(
'The OpenAI model to use. Models are loaded dynamically '
'from your API key. You can also type a custom model name. '
'Leave empty to use the default (GPT-4o).'
),
control_props={
'allowClear': True,
'creatable': True,
'tags': True,
'placeholder': gettext('Select or type a model name...'),
'optionsUrl': 'llm.models_openai',
'optionsRefreshUrl': 'llm.refresh_models_openai',
'refreshDepNames': {
'api_url': 'openai_api_url',
'api_key_file': 'openai_api_key_file'
}
}
)
# Ollama Settings
# Get defaults from config
ollama_url_default = getattr(config, 'OLLAMA_API_URL', '')
ollama_model_default = getattr(config, 'OLLAMA_API_MODEL', '')
self.ollama_api_url = self.preference.register(
'ollama', 'ollama_api_url',
gettext("API URL"), 'text',
ollama_url_default,
category_label=gettext('Ollama'),
help_str=gettext(
'URL for the Ollama API endpoint '
'(e.g., http://localhost:11434).'
)
)
# Fallback Ollama models (used if API fetch fails)
ollama_model_options = []
self.ollama_api_model = self.preference.register(
'ollama', 'ollama_api_model',
gettext("Model"), 'options',
ollama_model_default,
category_label=gettext('Ollama'),
options=ollama_model_options,
help_str=gettext(
'The Ollama model to use. Models are loaded dynamically '
'from your Ollama server. You can also type a custom model '
'name. Leave empty to use the default (llama3.2).'
),
control_props={
'allowClear': True,
'creatable': True,
'tags': True,
'placeholder': gettext('Select or type a model name...'),
'optionsUrl': 'llm.models_ollama',
'optionsRefreshUrl': 'llm.refresh_models_ollama',
'refreshDepNames': {
'api_url': 'ollama_api_url'
}
}
)
# Docker Model Runner Settings
# Get defaults from config
docker_url_default = getattr(config, 'DOCKER_API_URL', '')
docker_model_default = getattr(config, 'DOCKER_API_MODEL', '')
self.docker_api_url = self.preference.register(
'docker', 'docker_api_url',
gettext("API URL"), 'text',
docker_url_default,
category_label=gettext('Docker Model Runner'),
help_str=gettext(
'URL for the Docker Model Runner API endpoint '
'(e.g., http://localhost:12434). Available in Docker Desktop '
'4.40 and later. Tip: You can also use the OpenAI provider '
'with a custom API URL for any OpenAI-compatible endpoint, '
'including Docker Model Runner.'
)
)
# Fallback Docker models (used if API fetch fails)
docker_model_options = []
self.docker_api_model = self.preference.register(
'docker', 'docker_api_model',
gettext("Model"), 'options',
docker_model_default,
category_label=gettext('Docker Model Runner'),
options=docker_model_options,
help_str=gettext(
'The Docker model to use. Models are loaded dynamically '
'from your Docker Model Runner. You can also type a custom '
'model name. Leave empty to use the default (ai/qwen3-coder).'
),
control_props={
'allowClear': True,
'creatable': True,
'tags': True,
'placeholder': gettext('Select or type a model name...'),
'optionsUrl': 'llm.models_docker',
'optionsRefreshUrl': 'llm.refresh_models_docker',
'refreshDepNames': {
'api_url': 'docker_api_url'
}
}
)
def get_exposed_url_endpoints(self):
"""
Returns the list of URLs exposed to the client.
"""
return [
'llm.models_anthropic',
'llm.models_openai',
'llm.models_ollama',
'llm.models_docker',
'llm.refresh_models_anthropic',
'llm.refresh_models_openai',
'llm.refresh_models_ollama',
'llm.refresh_models_docker',
'llm.status',
# Security reports
'llm.security_report',
'llm.database_security_report',
'llm.schema_security_report',
# Security report streams
'llm.security_report_stream',
'llm.database_security_report_stream',
'llm.schema_security_report_stream',
# Performance reports
'llm.performance_report',
'llm.database_performance_report',
# Performance report streams
'llm.performance_report_stream',
'llm.database_performance_report_stream',
# Design reviews
'llm.database_design_report',
'llm.schema_design_report',
# Design report streams
'llm.database_design_report_stream',
'llm.schema_design_report_stream',
]
# Initialise the module
blueprint = LLMModule(MODULE_NAME, __name__)
@blueprint.route("/status", methods=["GET"], endpoint='status')
@pga_login_required
def get_llm_status():
"""
Get the LLM configuration status.
Returns whether LLM is enabled at system and user level,
and the configured provider and model.
"""
from pgadmin.llm.utils import (
is_llm_enabled, is_llm_enabled_system, get_default_provider,
get_anthropic_model, get_openai_model, get_ollama_model,
get_docker_model
)
provider = get_default_provider()
model = None
if provider == 'anthropic':
model = get_anthropic_model()
elif provider == 'openai':
model = get_openai_model()
elif provider == 'ollama':
model = get_ollama_model()
elif provider == 'docker':
model = get_docker_model()
return make_json_response(
success=1,
data={
'enabled': is_llm_enabled(),
'system_enabled': is_llm_enabled_system(),
'provider': provider,
'model': model
}
)
@blueprint.route(
"/models/anthropic", methods=["GET"], endpoint='models_anthropic'
)
@pga_login_required
def get_anthropic_models():
"""
Fetch available Anthropic models.
Returns models that support tool use.
"""
from pgadmin.llm.utils import get_anthropic_api_key, get_anthropic_api_url
api_key = get_anthropic_api_key()
api_url = get_anthropic_api_url()
if not api_key and not api_url:
return make_json_response(
data={'models': [], 'error': 'No API key configured'},
status=200
)
try:
models = _fetch_anthropic_models(api_key, api_url)
return make_json_response(data={'models': models}, status=200)
except Exception as e:
return make_json_response(
data={'models': [], 'error': str(e)},
status=200
)
@blueprint.route(
"/models/anthropic/refresh",
methods=["POST"],
endpoint='refresh_models_anthropic'
)
@pga_login_required
def refresh_anthropic_models():
"""
Fetch available Anthropic models using a provided API key file path
and/or custom API URL.
Used by the preferences refresh button to load models before saving.
"""
from pgadmin.llm.utils import read_api_key_file
data = request.get_json(force=True, silent=True) or {}
api_key_file = data.get('api_key_file', '')
api_url = data.get('api_url', '')
api_key = None
if api_key_file:
api_key = read_api_key_file(api_key_file)
if not api_key and not api_url:
return make_json_response(
data={'models': [],
'error': 'No API key or custom URL provided'},
status=200
)
try:
models = _fetch_anthropic_models(api_key, api_url)
return make_json_response(data={'models': models}, status=200)
except Exception as e:
return make_json_response(
data={'models': [], 'error': str(e)},
status=200
)
@blueprint.route("/models/openai", methods=["GET"], endpoint='models_openai')
@pga_login_required
def get_openai_models():
"""
Fetch available OpenAI models.
Returns models that support function calling.
"""
from pgadmin.llm.utils import get_openai_api_key, get_openai_api_url
api_key = get_openai_api_key()
api_url = get_openai_api_url()
if not api_key and not api_url:
return make_json_response(
data={'models': [], 'error': 'No API key configured'},
status=200
)
try:
models = _fetch_openai_models(api_key, api_url)
return make_json_response(data={'models': models}, status=200)
except Exception as e:
return make_json_response(
data={'models': [], 'error': str(e)},
status=200
)
@blueprint.route(
"/models/openai/refresh",
methods=["POST"],
endpoint='refresh_models_openai'
)
@pga_login_required
def refresh_openai_models():
"""
Fetch available OpenAI models using a provided API key file path
and/or custom API URL.
Used by the preferences refresh button to load models before saving.
"""
from pgadmin.llm.utils import read_api_key_file
data = request.get_json(force=True, silent=True) or {}
api_key_file = data.get('api_key_file', '')
api_url = data.get('api_url', '')
api_key = None
if api_key_file:
api_key = read_api_key_file(api_key_file)
if not api_key and not api_url:
return make_json_response(
data={'models': [], 'error': 'No API key or custom URL provided'},
status=200
)
try:
models = _fetch_openai_models(api_key, api_url)
return make_json_response(data={'models': models}, status=200)
except Exception as e:
return make_json_response(
data={'models': [], 'error': str(e)},
status=200
)
@blueprint.route("/models/ollama", methods=["GET"], endpoint='models_ollama')
@pga_login_required
def get_ollama_models():
"""
Fetch available Ollama models.
"""
from pgadmin.llm.utils import get_ollama_api_url
api_url = get_ollama_api_url()
if not api_url:
return make_json_response(
data={'models': [], 'error': 'No API URL configured'},
status=200
)
try:
models = _fetch_ollama_models(api_url)
return make_json_response(data={'models': models}, status=200)
except Exception as e:
return make_json_response(
data={'models': [], 'error': str(e)},
status=200
)
@blueprint.route(
"/models/ollama/refresh",
methods=["POST"],
endpoint='refresh_models_ollama'
)
@pga_login_required
def refresh_ollama_models():
"""
Fetch available Ollama models using a provided API URL.
Used by the preferences refresh button to load models before saving.
"""
data = request.get_json(force=True, silent=True) or {}
api_url = data.get('api_url', '')
if not api_url:
return make_json_response(
data={'models': [], 'error': 'No API URL provided'},
status=200
)
try:
models = _fetch_ollama_models(api_url)
return make_json_response(data={'models': models}, status=200)
except Exception as e:
return make_json_response(
data={'models': [], 'error': str(e)},
status=200
)
@blueprint.route("/models/docker", methods=["GET"], endpoint='models_docker')
@pga_login_required
def get_docker_models():
"""
Fetch available Docker Model Runner models.
"""
from pgadmin.llm.utils import get_docker_api_url
api_url = get_docker_api_url()
if not api_url:
return make_json_response(
data={'models': [], 'error': 'No API URL configured'},
status=200
)
try:
models = _fetch_docker_models(api_url)
return make_json_response(data={'models': models}, status=200)
except Exception as e:
return make_json_response(
data={'models': [], 'error': str(e)},
status=200
)
@blueprint.route(
"/models/docker/refresh",
methods=["POST"],
endpoint='refresh_models_docker'
)
@pga_login_required
def refresh_docker_models():
"""
Fetch available Docker models using a provided API URL.
Used by the preferences refresh button to load models before saving.
"""
data = request.get_json(force=True, silent=True) or {}
api_url = data.get('api_url', '')
if not api_url:
return make_json_response(
data={'models': [], 'error': 'No API URL provided'},
status=200
)
try:
models = _fetch_docker_models(api_url)
return make_json_response(data={'models': models}, status=200)
except Exception as e:
return make_json_response(
data={'models': [], 'error': str(e)},
status=200
)
def _fetch_anthropic_models(api_key, api_url=''):
"""
Fetch models from Anthropic API.
Returns a list of model options with label and value.
"""
import urllib.request
import urllib.error
base_url = (api_url or 'https://api.anthropic.com/v1').rstrip('/')
url = f'{base_url}/models'
headers = {
'anthropic-version': '2023-06-01'
}
if api_key:
headers['x-api-key'] = api_key
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(
req, timeout=30, context=SSL_CONTEXT
) as response:
data = json.loads(response.read().decode('utf-8'))
except urllib.error.HTTPError as e:
if e.code == 401:
raise ValueError('Invalid API key')
raise ConnectionError(f'API error: {e.code}')
except urllib.error.URLError as e:
raise ConnectionError(
f'Cannot connect to Anthropic API: {e.reason}'
)
models = []
seen = set()
for model in data.get('data', []):
model_id = model.get('id', '')
display_name = model.get('display_name', model_id)
# Skip if already seen or empty
if not model_id or model_id in seen:
continue
seen.add(model_id)
# Create a user-friendly label
if display_name and display_name != model_id:
label = f"{display_name} ({model_id})"
else:
label = model_id
models.append({
'label': label,
'value': model_id
})
if not models and api_url:
raise ConnectionError(
'No models returned. Check that the API URL is correct.'
)
# Sort alphabetically by model ID
models.sort(key=lambda x: x['value'])
return models
def _fetch_openai_models(api_key, api_url=''):
"""
Fetch models from OpenAI API or any OpenAI-compatible endpoint.
Returns a list of model options with label and value.
"""
import urllib.request
import urllib.error
base_url = (api_url or 'https://api.openai.com/v1').rstrip('/')
url = f'{base_url}/models'
headers = {
'Content-Type': 'application/json'
}
if api_key:
headers['Authorization'] = f'Bearer {api_key}'
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(
req, timeout=30, context=SSL_CONTEXT
) as response:
data = json.loads(response.read().decode('utf-8'))
except urllib.error.HTTPError as e:
if e.code == 401:
raise ValueError('Invalid API key')
raise ConnectionError(f'API error: {e.code}')
except urllib.error.URLError as e:
raise ConnectionError(
f'Cannot connect to OpenAI API: {e.reason}'
)
models = []
seen = set()
for model in data.get('data', []):
model_id = model.get('id', '')
# Skip if already seen or empty
if not model_id or model_id in seen:
continue
seen.add(model_id)
models.append({
'label': model_id,
'value': model_id
})
if not models and api_url:
raise ConnectionError(
'No models returned. Check that the API URL is correct '
'and includes the /v1 path prefix if required by your '
'provider (e.g., http://localhost:1234/v1).'
)
# Sort alphabetically
models.sort(key=lambda x: x['value'])
return models
def _fetch_ollama_models(api_url):
"""
Fetch models from Ollama API.
Returns a list of model options with label and value.
"""
import urllib.request
import urllib.error
# Normalize URL
api_url = api_url.rstrip('/')
url = f'{api_url}/api/tags'
req = urllib.request.Request(url)
try:
with urllib.request.urlopen(
req, timeout=30, context=SSL_CONTEXT
) as response:
data = json.loads(response.read().decode('utf-8'))
except urllib.error.URLError as e:
raise ConnectionError(
f'Cannot connect to Ollama: {e.reason}'
)
except OSError as e:
raise ConnectionError(
f'Error fetching models: {str(e)}'
)
models = []
for model in data.get('models', []):
name = model.get('name', '')
if name:
# Format size if available
size = model.get('size', 0)
if size:
size_gb = size / (1024 ** 3)
label = f"{name} ({size_gb:.1f} GB)"
else:
label = name
models.append({
'label': label,
'value': name
})
# Sort alphabetically
models.sort(key=lambda x: x['value'])
return models
def _fetch_docker_models(api_url):
"""
Fetch models from Docker Model Runner API.
Returns a list of model options with label and value.
Docker Model Runner uses an OpenAI-compatible API at /engines/v1/models
"""
import urllib.request
import urllib.error
# Normalize URL
api_url = api_url.rstrip('/')
url = f'{api_url}/engines/v1/models'
req = urllib.request.Request(url)
try:
with urllib.request.urlopen(
req, timeout=30, context=SSL_CONTEXT
) as response:
data = json.loads(response.read().decode('utf-8'))
except urllib.error.URLError as e:
raise ConnectionError(
f'Cannot connect to Docker Model Runner: '
f'{e.reason}. Is Docker Desktop running '
f'with model runner enabled?'
)
except OSError as e:
raise ConnectionError(
f'Error fetching models: {str(e)}'
)
models = []
seen = set()
for model in data.get('data', []):
model_id = model.get('id', '')
# Skip if already seen or empty
if not model_id or model_id in seen:
continue
seen.add(model_id)
models.append({
'label': model_id,
'value': model_id
})
# Sort alphabetically
models.sort(key=lambda x: x['value'])
return models
@blueprint.route(
"/security-report/<int:sid>",
methods=["GET"],
endpoint='security_report'
)
@pga_login_required
def generate_security_report(sid):
"""
Generate a security report for the specified server.
Uses the multi-stage pipeline to analyze server configuration.
"""
from pgadmin.llm.utils import is_llm_enabled
from pgadmin.llm.reports.generator import generate_report_sync
from pgadmin.utils.driver import get_driver
# Check if LLM is configured
if not is_llm_enabled():
return make_json_response(
success=0,
errormsg=gettext(
'LLM is not configured. Please configure an LLM provider '
'in Preferences > AI.'
)
)
# Get database connection
try:
driver = get_driver(config.PG_DEFAULT_DRIVER)
manager = driver.connection_manager(sid)
conn = manager.connection()
if not conn.connected():
return make_json_response(
success=0,
errormsg=gettext('Server is not connected.')
)
# Generate report using pipeline
context = {}
success, result = generate_report_sync(
report_type='security',
scope='server',
conn=conn,
manager=manager,
context=context
)
if success:
return make_json_response(
success=1,
data={'report': result}
)
else:
return make_json_response(
success=0,
errormsg=result
)
except Exception as e:
return make_json_response(
success=0,
errormsg=gettext('Failed to generate report: ') + str(e)
)
@blueprint.route(
"/security-report/<int:sid>/stream",
methods=["GET"],
endpoint='security_report_stream'
)
@pgCSRFProtect.exempt
@pga_login_required
def generate_security_report_stream(sid):
"""
Stream a security report for the specified server via SSE.
"""
from pgadmin.llm.utils import is_llm_enabled
from pgadmin.llm.reports.generator import (
generate_report_streaming, create_sse_response
)
from pgadmin.utils.driver import get_driver
if not is_llm_enabled():
return make_json_response(
success=0,
errormsg=gettext(
'LLM is not configured. Please configure an LLM provider '
'in Preferences > AI.'
)
)
try:
driver = get_driver(config.PG_DEFAULT_DRIVER)
manager = driver.connection_manager(sid)
conn = manager.connection()
if not conn.connected():
return make_json_response(
success=0,
errormsg=gettext('Server is not connected.')
)
context = {}
generator = generate_report_streaming(
report_type='security',
scope='server',
conn=conn,
manager=manager,
context=context
)
return create_sse_response(generator)
except Exception as e:
return make_json_response(
success=0,
errormsg=str(e)
)
def _gather_security_config(conn, manager):
"""
Gather security-related configuration from the PostgreSQL server.
"""
security_info = {
'server_version': manager.ver,
'server_version_num': manager.sversion,
}
# Get security-related settings from pg_settings
settings_query = """
SELECT name, setting, short_desc, context, source