@voyager-0x/agent-mcp
Version:
Voyager MCP Agent - A powerful Model Context Protocol agent
116 lines (100 loc) • 2.66 kB
text/typescript
/**
* AI大模型配置管理模块
* 提供统一的配置管理,供所有AI相关模块使用
*/
export interface AIModelConfig {
apiKey: string;
baseURL: string;
model: string;
debug?: boolean;
}
// 默认配置
const DEFAULT_CONFIG: Partial<AIModelConfig> = {
debug: false,
model: 'gpt-3.5-turbo',
baseURL: 'https://api.openai.com/v1',
};
class AIConfigManager {
private config: AIModelConfig | null = null;
private listeners: Array<(config: AIModelConfig) => void> = [];
/**
* 设置AI配置
*/
setConfig(config: AIModelConfig) {
this.config = { ...DEFAULT_CONFIG, ...config };
this.notifyListeners();
}
/**
* 获取AI配置
*/
getConfig(): AIModelConfig {
if (!this.config) {
throw new Error('AI配置未初始化,请先调用 setConfig() 设置配置');
}
return { ...this.config };
}
/**
* 更新部分配置
*/
updateConfig(partialConfig: Partial<AIModelConfig>) {
if (!this.config) {
throw new Error('AI配置未初始化,请先调用 setConfig() 设置配置');
}
this.config = { ...this.config, ...partialConfig };
this.notifyListeners();
}
/**
* 检查配置是否已初始化
*/
isConfigured(): boolean {
return this.config !== null;
}
/**
* 监听配置变化
*/
onConfigChange(listener: (config: AIModelConfig) => void) {
this.listeners.push(listener);
// 返回取消监听的函数
return () => {
const index = this.listeners.indexOf(listener);
if (index > -1) {
this.listeners.splice(index, 1);
}
};
}
offConfigChange(listener: (config: AIModelConfig) => void) {
const index = this.listeners.indexOf(listener);
if (index > -1) {
this.listeners.splice(index, 1);
}
}
/**
* 通知所有监听器
*/
private notifyListeners() {
if (this.config) {
this.listeners.forEach((listener) => listener(this.config!));
}
}
isDebug() {
return this.config?.debug;
}
/**
* 重置配置
*/
reset() {
this.config = null;
this.listeners = [];
}
}
// 导出单例实例
export const aiConfigManager = new AIConfigManager();
// 便捷方法
export const setAIConfig = (config: AIModelConfig) =>
aiConfigManager.setConfig(config);
export const getAIConfig = () => aiConfigManager.getConfig();
export const updateAIConfig = (config: Partial<AIModelConfig>) =>
aiConfigManager.updateConfig(config);
export const isAIConfigured = () => aiConfigManager.isConfigured();
export const onAIConfigChange = (listener: (config: AIModelConfig) => void) =>
aiConfigManager.onConfigChange(listener);