11import * as vscode from 'vscode' ;
2+ import { createOpenAIApi } from './openai-utils' ;
23
34/**
45 * Configuration keys used in the AI commit extension.
@@ -26,18 +27,25 @@ export class ConfigurationManager {
2627 private static instance : ConfigurationManager ;
2728 private configCache : Map < string , any > = new Map ( ) ;
2829 private disposable : vscode . Disposable ;
30+ private context : vscode . ExtensionContext ;
2931
30- private constructor ( ) {
32+ private constructor ( context : vscode . ExtensionContext ) {
33+ this . context = context ;
3134 this . disposable = vscode . workspace . onDidChangeConfiguration ( ( event ) => {
3235 if ( event . affectsConfiguration ( 'ai-commit' ) ) {
3336 this . configCache . clear ( ) ;
37+
38+ if ( event . affectsConfiguration ( 'ai-commit.OPENAI_BASE_URL' ) ||
39+ event . affectsConfiguration ( 'ai-commit.OPENAI_API_KEY' ) ) {
40+ this . updateModelList ( ) ;
41+ }
3442 }
3543 } ) ;
3644 }
3745
38- static getInstance ( ) : ConfigurationManager {
39- if ( ! this . instance ) {
40- this . instance = new ConfigurationManager ( ) ;
46+ static getInstance ( context ?: vscode . ExtensionContext ) : ConfigurationManager {
47+ if ( ! this . instance && context ) {
48+ this . instance = new ConfigurationManager ( context ) ;
4149 }
4250 return this . instance ;
4351 }
@@ -53,4 +61,40 @@ export class ConfigurationManager {
5361 dispose ( ) {
5462 this . disposable . dispose ( ) ;
5563 }
64+
65+ /**
66+ * Updates the list of available OpenAI models.
67+ */
68+ private async updateModelList ( ) {
69+ try {
70+ const openai = createOpenAIApi ( ) ;
71+ const models = await openai . models . list ( ) ;
72+
73+ // Save available models to extension state
74+ await this . context . globalState . update ( 'availableModels' , models . data . map ( model => model . id ) ) ;
75+
76+ // Get the current selected model
77+ const config = vscode . workspace . getConfiguration ( 'ai-commit' ) ;
78+ const currentModel = config . get < string > ( 'OPENAI_MODEL' ) ;
79+
80+ // If the current selected model is not in the available list, set it to the default value
81+ const availableModels = models . data . map ( model => model . id ) ;
82+ if ( ! availableModels . includes ( currentModel ) ) {
83+ await config . update ( 'OPENAI_MODEL' , 'gpt-4' , vscode . ConfigurationTarget . Global ) ;
84+ }
85+ } catch ( error ) {
86+ console . error ( 'Failed to fetch OpenAI models:' , error ) ;
87+ }
88+ }
89+
90+ /**
91+ * Retrieves the list of available OpenAI models.
92+ * @returns {Promise<string[]> } The list of available models.
93+ */
94+ public async getAvailableModels ( ) : Promise < string [ ] > {
95+ if ( ! this . context . globalState . get < string [ ] > ( 'availableModels' ) ) {
96+ await this . updateModelList ( ) ;
97+ }
98+ return this . context . globalState . get < string [ ] > ( 'availableModels' , [ ] ) ;
99+ }
56100}
0 commit comments